Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cohorts): kind-aware completion and readiness stamp (#75736)

Matheus Batistaff6cffc8d175
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
index a281e04cf316..9f9368775053 100644
--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr
@@ -28,6 +28,7 @@
'last_error_at',
'pending_version',
'people',
+ 'person_filters_shape_hash',
'version',
])
# ---
@@ -159,7 +160,6 @@
'last_calculation_duration_ms',
'last_realtime_cohort_calculation_at',
'name',
- 'person_filters_shape_hash',
'query',
])
# ---
@@ -543,6 +543,7 @@
'objects',
'pending_version',
'people',
+ 'person_filters_shape_hash',
'properties',
'remove_user_by_uuid',
'save',
diff --git a/posthog/models/resource_transfer/visitors/cohort.py b/posthog/models/resource_transfer/visitors/cohort.py
index 6661175229da..986af3930e9a 100644
--- a/posthog/models/resource_transfer/visitors/cohort.py
+++ b/posthog/models/resource_transfer/visitors/cohort.py
@@ -25,6 +25,7 @@ class CohortVisitor(
"last_backfill_person_properties_at",
"filters_shape_hash",
"behavioral_filters_shape_hash",
+ "person_filters_shape_hash",
"count",
"version",
"pending_version",
diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.py
index b5c8c0d3dc7b..8a20a2beb3d7 100644
--- a/posthog/settings/cohorts.py
+++ b/posthog/settings/cohorts.py
@@ -30,8 +30,33 @@ BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED: bool = get_from_env(
BEHAVIORAL_BACKFILL_FINALIZER_ENABLED: bool = get_from_env(
"BEHAVIORAL_BACKFILL_FINALIZER_ENABLED", False, type_cast=str_to_bool
)
+# Whether the finalizer may terminalize person-property runs and stamp
+# `last_backfill_person_properties_at`. Separate from the finalizer gate above, which is already on
+# for behavioral runs, so this is the only thing standing between an enabled person seed path and a
+# live person stamp.
+#
+# Keep it off until the flags service stops accepting that stamp as proof the membership table is
+# populated. `Cohort::uses_realtime_membership` takes *either* backfill timestamp, because ~19k
+# cohorts still carry a person stamp written by the legacy realtime workflow before #57545 removed
+# that write, and for those it correctly means "the legacy pipeline computed this cohort into
+# cohort_membership". A stamp written here means something different: only the person half is
+# backfilled. Until the two can be told apart, a person stamp landing on a cohort whose behavioral
+# half is unseeded routes flag evaluation through `cohort_membership` anyway, which under-matches
+# "in cohort" targeting and over-matches negated targeting. `Cohort.is_flag_compatible` fail-closes
+# on this; the flags service does not.
+#
+# Also keep it off until a person-leaf edit supersedes the cohort's active person-property runs,
+# the way `_supersede_cohort_events_backfills` does for behavioral ones (the B7.3b receiver).
+# Without that, the person stamp's only edit-time fence is the hash CAS in `_stamp_readiness`,
+# which passes again after an A->B->A revert and stamps readiness over a backfill whose Stage 2
+# state went stale in the B window — the `superseded_at` refusal that closes this for behavioral
+# runs never fires because nothing sets it on the person path.
+BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED: bool = get_from_env(
+ "BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED", False, type_cast=str_to_bool
+)
# Bounds one finalizer pass: held runs come back every pass, so an unbounded scan would grow with a
-# stalled seeder instead of staying proportional to what a pass can actually resolve.
+# stalled seeder instead of staying proportional to what a pass can actually resolve. Split evenly
+# across the finalizable kinds, so opening the person readiness gate halves the behavioral share.
BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS: int = get_from_env(
"BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS", 500, type_cast=int
)
diff --git a/products/cohorts/backend/backfill/__init__.py b/products/cohorts/backend/backfill/__init__.py
index 5a68ac42b452..561a9431f674 100644
--- a/products/cohorts/backend/backfill/__init__.py
+++ b/products/cohorts/backend/backfill/__init__.py
@@ -4,7 +4,11 @@ from products.cohorts.backend.backfill.pinning import (
pin_conditions_for_cohorts,
pin_person_conditions_for_cohorts,
)
-from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash, stamp_events_readiness
+from products.cohorts.backend.backfill.readiness import (
+ ensure_filters_shape_hash,
+ stamp_events_readiness,
+ stamp_person_properties_readiness,
+)
from products.cohorts.backend.backfill.runs import (
check_person_run_preconditions,
check_run_preconditions,
@@ -31,5 +35,6 @@ __all__ = [
"pin_conditions_for_cohorts",
"pin_person_conditions_for_cohorts",
"stamp_events_readiness",
+ "stamp_person_properties_readiness",
"supersede_active_runs",
]
diff --git a/products/cohorts/backend/backfill/finalize.py b/products/cohorts/backend/backfill/finalize.py
index 037a0380e633..481aa26603d0 100644
--- a/products/cohorts/backend/backfill/finalize.py
+++ b/products/cohorts/backend/backfill/finalize.py
@@ -1,7 +1,12 @@
-"""Terminalizes behavioral backfill runs the Rust seeder has fully observed.
+"""Terminalizes backfill runs the Rust seeder has fully observed.
-Only ``last_backfill_events_at`` is stamped; mixed person+behavioral cohorts stay flag-incompatible
-until the person-properties column is stamped too (intended fail-closed).
+A run stamps the readiness column of its own kind: behavioral runs stamp ``last_backfill_events_at``,
+person-property runs stamp ``last_backfill_person_properties_at``. A mixed cohort needs both runs to
+finalize before it is flag-compatible (intended fail-closed).
+
+The person half is gated dark by ``BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED`` until the flags
+service can tell a stamp written here apart from the legacy ones it currently reads as proof that
+``cohort_membership`` is populated. See ``_finalizable_kinds``.
The seeder writes a definitive per-participation outcome (``reconcile_completed_at`` /
``superseded_at`` / retryable ``error``) before it sets ``run.reconcile_observed_at`` as its last
@@ -9,6 +14,7 @@ write. This finalizer trusts those columns — never Kafka — and CASes the run
``reconciling`` once every participation has a terminal outcome.
"""
+from collections.abc import Callable
from dataclasses import dataclass
from uuid import UUID
@@ -22,7 +28,7 @@ from prometheus_client import Counter, Gauge
from posthog.tasks.utils import CeleryQueue
-from products.cohorts.backend.backfill.readiness import stamp_events_readiness
+from products.cohorts.backend.backfill.readiness import stamp_events_readiness, stamp_person_properties_readiness
from products.cohorts.backend.models.backfill import (
CohortBackfillKind,
CohortBackfillRun,
@@ -42,22 +48,27 @@ FLAGS_CACHE_TASK = "products.feature_flags.backend.tasks.update_team_service_fla
READINESS_STAMPS_COUNTER = Counter(
"posthog_cohort_backfill_readiness_stamps_total",
- "Backfill participations resolved by the finalizer, by outcome",
- ["result"], # labels: "stamped", "superseded"
+ "Backfill participations resolved by the finalizer, by outcome and backfill kind",
+ # Split by kind for the same reason as by result: a person-side supersession spike is invisible
+ # summed against behavioral traffic.
+ ["result", "kind"], # result: "stamped", "superseded"; kind: the CohortBackfillKind
)
RUNS_FINALIZED_COUNTER = Counter(
"posthog_cohort_backfill_runs_finalized_total",
- "Backfill runs terminalized by the finalizer, by terminal status",
- ["status"], # labels: "completed", "superseded"
+ "Backfill runs terminalized by the finalizer, by terminal status and backfill kind",
+ ["status", "kind"], # status: "completed", "superseded"; kind: the CohortBackfillKind
)
-# Split by reason: a shortfall is routine backpressure, an error is a crashed pass. Summing them
+# Split by reason: a shortfall is routine backpressure, an error is a crashed pass, and a gated run
+# is an expected backlog waiting on `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED`. Summing them
# would leave an alert unable to tell which one is happening.
HELD_RUNS_GAUGE = Gauge(
"posthog_cohort_backfill_finalizer_held_runs",
"Observed backfill runs the finalizer left in reconciling, by reason",
- ["reason"], # labels: "shortfall" (an outcome was missing), "error" (the pass raised)
+ # labels: "shortfall" (an outcome was missing), "error" (the pass raised), "gated" (a person
+ # run parked behind the readiness gate)
+ ["reason"],
multiprocess_mode="max",
)
@@ -69,10 +80,38 @@ class FinalizerPass:
superseded: int = 0
held: int = 0
errored: int = 0
+ gated: int = 0
stamped_participations: int = 0
invalidated_teams: int = 0
+# Every kind this finalizer knows how to stamp. Discovery draws from these keys, so the lookup below
+# can only ever see a kind it has a stamp for, which is what guarantees a run is never stamped into
+# the wrong column. It also means a kind added to the vocabulary without a stamp here is filtered out
+# of discovery and simply never finalized: it sits in `reconciling` indefinitely, with no exception,
+# no error count, and no gauge movement. `test_every_backfill_kind_has_a_stamp` turns that silence
+# into a CI failure instead.
+_STAMP_BY_KIND: dict[str, Callable[[CohortBackfillRun, int], bool]] = {
+ CohortBackfillKind.BEHAVIORAL: stamp_events_readiness,
+ CohortBackfillKind.PERSON_PROPERTY: stamp_person_properties_readiness,
+}
+
+
+def _finalizable_kinds() -> tuple[str, ...]:
+ """The kinds this pass may terminalize, narrowed by the person readiness gate.
+
+ Gating discovery rather than the stamp is deliberate: a stamp function that returned ``False``
+ would mark the participation superseded, which is terminal, and would silently throw away a
+ completed person backfill. Filtering here leaves the run `reconciling` instead, so it finalizes
+ normally once the gate opens. See ``BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED`` for why the
+ person stamp is held back: the flags service still reads it as proof that `cohort_membership`
+ is populated, which is true of the legacy rows but not of one this finalizer writes.
+ """
+ if settings.BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED:
+ return tuple(_STAMP_BY_KIND)
+ return (CohortBackfillKind.BEHAVIORAL,)
+
+
def _dispatch_flags_cache_update(team_id: int) -> None:
# send_task bypasses the task decorator's options, so the queue must be routed explicitly.
current_app.send_task(FLAGS_CACHE_TASK, args=(team_id,), queue=CeleryQueue.FEATURE_FLAGS.value)
@@ -87,20 +126,46 @@ def finalize_backfill_runs() -> FinalizerPass:
_publish_held_runs(result)
return result
+ if not settings.BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED:
+ # The kind filter below holds these runs invisibly: discovery never surfaces them, so
+ # `result.held` stays 0 and nothing else reports how much is waiting behind the gate.
+ result.gated = (
+ CohortBackfillRun.objects.unscoped()
+ .filter(
+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY,
+ status=CohortBackfillRunStatus.RECONCILING,
+ reconcile_observed_at__isnull=False,
+ )
+ .count()
+ )
+
# Deliberate, documented cross-team scan: the finalizer serves all teams. Each row is re-locked
- # per team inside the loop, so the unscoped read is discovery only. Oldest-observed first, which
- # the partial index already orders by, so a capped pass drains the backlog in arrival order.
- observed = list(
- CohortBackfillRun.objects.unscoped()
+ # per team inside the loop, so the unscoped read is discovery only. The kind predicate does two
+ # jobs: while `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` is off it holds person runs in
+ # `reconciling` rather than stamping them, and it is what makes "a kind with no stamp is never
+ # discovered", rather than "is discovered and then raises", protect `_STAMP_BY_KIND`.
+ #
+ # One query per kind, each with its own slice of the budget: the person backlog parked while
+ # the readiness gate was off all sorts ahead of live behavioral runs under
+ # `reconcile_observed_at`, so a single shared cap would hand it the entire budget for the first
+ # passes after the gate opens. Per-kind equality is also what keeps the walk cheap:
+ # `cohort_bfr_reconciling_idx` leads with `backfill_kind`, so each query enters the index at its
+ # own kind and reads `reconcile_observed_at` already ordered — the cap terminates the walk
+ # rather than bounding a sort, and neither kind pays for the other's parked backlog.
+ kinds = _finalizable_kinds()
+ per_kind = max(1, settings.BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS // len(kinds))
+ observed = [
+ row
+ for kind in kinds
+ for row in CohortBackfillRun.objects.unscoped()
.filter(
- # Only the events column is stamped, so never terminalize a person-properties run.
- backfill_kind=CohortBackfillKind.BEHAVIORAL,
+ backfill_kind=kind,
status=CohortBackfillRunStatus.RECONCILING,
reconcile_observed_at__isnull=False,
)
.order_by("reconcile_observed_at")
- .values_list("id", "team_id")[: settings.BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS]
- )
+ .values_list("id", "team_id")[:per_kind]
+ ]
teams_to_invalidate: set[int] = set()
for run_id, team_id in observed:
@@ -133,6 +198,7 @@ def finalize_backfill_runs() -> FinalizerPass:
def _publish_held_runs(result: FinalizerPass) -> None:
HELD_RUNS_GAUGE.labels(reason="shortfall").set(result.held)
HELD_RUNS_GAUGE.labels(reason="error").set(result.errored)
+ HELD_RUNS_GAUGE.labels(reason="gated").set(result.gated)
def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool:
@@ -169,6 +235,7 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool
team_id=team_id,
participations=len(participations),
)
+ stamp_readiness = _STAMP_BY_KIND[run.backfill_kind]
for participation in participations:
# Supersede trumps completion, so check it first.
if participation.superseded_at is not None:
@@ -178,16 +245,16 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool
stamped += 1
continue
if participation.reconcile_completed_at is not None:
- if stamp_events_readiness(run, participation.cohort_id):
+ if stamp_readiness(run, participation.cohort_id):
stamped += 1
invalidate_team = True
result.stamped_participations += 1
- READINESS_STAMPS_COUNTER.labels(result="stamped").inc()
+ READINESS_STAMPS_COUNTER.labels(result="stamped", kind=run.backfill_kind).inc()
else:
- # stamp_events_readiness superseded the participation (and, for a cohort-scoped
- # run, possibly the run row itself) inside this transaction.
+ # The stamp superseded the participation (and, for a cohort-scoped run, possibly
+ # the run row itself) inside this transaction.
superseded += 1
- READINESS_STAMPS_COUNTER.labels(result="superseded").inc()
+ READINESS_STAMPS_COUNTER.labels(result="superseded", kind=run.backfill_kind).inc()
continue
# No outcome despite reconcile_observed_at being set. An empty error means the seeder
@@ -223,18 +290,18 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool
if transitioned:
if terminal_status == CohortBackfillRunStatus.COMPLETED:
result.completed += 1
- RUNS_FINALIZED_COUNTER.labels(status="completed").inc()
+ RUNS_FINALIZED_COUNTER.labels(status="completed", kind=run.backfill_kind).inc()
else:
result.superseded += 1
- RUNS_FINALIZED_COUNTER.labels(status="superseded").inc()
+ RUNS_FINALIZED_COUNTER.labels(status="superseded", kind=run.backfill_kind).inc()
else:
# We hold the run row's FOR UPDATE lock, so a missed CAS can only mean our own
- # stamp_events_readiness call superseded a cohort-scoped run inside this transaction —
+ # readiness stamp superseded a cohort-scoped run inside this transaction —
# the run is terminal (superseded + finished_at) and counted as such. That reads the
# one-participation invariant checked above: with more, a run that also stamped a cohort
# would land here and be counted purely superseded.
result.superseded += 1
- RUNS_FINALIZED_COUNTER.labels(status="superseded").inc()
+ RUNS_FINALIZED_COUNTER.labels(status="superseded", kind=run.backfill_kind).inc()
# Re-fire invalidation when completing a run whose stamps landed in an earlier pass, covering
# a crash between that pass's commit and its post-commit invalidation. (A crash after this
diff --git a/products/cohorts/backend/backfill/readiness.py b/products/cohorts/backend/backfill/readiness.py
index cc429cb51e61..8e6d3f384aaf 100644
--- a/products/cohorts/backend/backfill/readiness.py
+++ b/products/cohorts/backend/backfill/readiness.py
@@ -1,3 +1,14 @@
+"""Shape-hash maintenance and the CAS that opens a cohort's readiness for flag targeting.
+
+Both ``stamp_*_readiness`` functions share one contract. They intentionally bypass signals, so the
+caller must explicitly invalidate the feature-flag and behavioral-cohort caches after a successful
+stamp; and they must be called inside a transaction, because the cohort stamp and the participation
+CAS that ratifies it have to commit or roll back together.
+"""
+
+from dataclasses import dataclass
+from uuid import UUID
+
from django.db.models.functions import Now
import structlog
@@ -57,6 +68,36 @@ def ensure_filters_shape_hash(cohort: Cohort) -> str:
return cohort.filters_shape_hash or ""
+@dataclass(frozen=True)
+class _ReadinessSpec:
+ """The columns one backfill kind's readiness stamp keys on.
+
+ ``hash_field`` names the same column on both models: the fingerprint the run pinned on the
+ participation, and the cohort's current one it is CAS'd against.
+
+ ``readiness`` names the stamped column, not the run kind, and the log field it feeds is named
+ for it. Deliberately not the ``CohortBackfillKind`` vocabulary the metrics label ``kind`` with:
+ a behavioral run stamps ``last_backfill_events_at``, so one value would have to be wrong.
+ """
+
+ readiness: str
+ hash_field: str
+ stamp_field: str
+
+
+_EVENTS = _ReadinessSpec(
+ readiness="events",
+ hash_field="behavioral_filters_shape_hash",
+ stamp_field="last_backfill_events_at",
+)
+
+_PERSON_PROPERTIES = _ReadinessSpec(
+ readiness="person_properties",
+ hash_field="person_filters_shape_hash",
+ stamp_field="last_backfill_person_properties_at",
+)
+
+
def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
"""CAS-stamp event readiness for one pinned cohort.
@@ -64,61 +105,60 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
``last_backfill_events_at`` when the behavioral leaves change (see ``_maintain_filter_shape_hashes``).
A person-property or cohort-reference edit mid-backfill shifts the full hash without touching
events readiness, so keying on the full hash would wrongly supersede a still-valid events backfill.
+ """
+ return _stamp_readiness(run, cohort_id, _EVENTS)
+
- This update intentionally bypasses signals. The caller must explicitly invalidate feature-flag
- and behavioral-cohort caches after a successful stamp.
+def stamp_person_properties_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
+ """CAS-stamp person-property readiness for one pinned cohort.
- Call inside a transaction: the cohort stamp and the participation CAS that ratifies it must
- commit or roll back together.
+ The mirror of :func:`stamp_events_readiness`, keyed on the person shape hash so a behavioral
+ edit mid-backfill cannot supersede a still-valid person backfill.
+
+ The stamp asserts the cohort's person properties were backfilled as far back as the run's pinned
+ ``person_scan_since`` horizon, not over all history: a person who last changed before that
+ horizon and has produced nothing since is outside what the run scanned.
"""
+ return _stamp_readiness(run, cohort_id, _PERSON_PROPERTIES)
+
+
+def _stamp_readiness(run: CohortBackfillRun, cohort_id: int, spec: _ReadinessSpec) -> bool:
+ """The kind-agnostic stamp protocol behind the two public wrappers."""
participation = CohortBackfillRunCohort.objects.for_team(run.team_id).get(run_id=run.id, cohort_id=cohort_id)
if participation.superseded_at is not None:
- # A superseded participation is terminal. Refuse even when its pinned behavioral hash matches
- # the cohort's current one again (A->B->A edit-revert): the events backfill it covered is gone.
- logger.info("cohort_backfill_readiness_stamp_refused_superseded", run_id=str(run.id), cohort_id=cohort_id)
+ # A superseded participation is terminal. Refuse even when its pinned hash matches the
+ # cohort's current one again (A->B->A edit-revert): the backfill it covered is gone.
+ logger.info(
+ "cohort_backfill_readiness_stamp_refused_superseded",
+ run_id=str(run.id),
+ cohort_id=cohort_id,
+ readiness=spec.readiness,
+ )
return False
- updated = Cohort.objects.filter(
- id=cohort_id,
- team_id=run.team_id,
- behavioral_filters_shape_hash=participation.behavioral_filters_shape_hash,
- last_backfill_events_at__isnull=True,
- ).update(last_backfill_events_at=Now())
+ pinned = getattr(participation, spec.hash_field)
+ # Reused by the rollback below, so both writes fence on the same pinned fingerprint.
+ cohort_fence = {"id": cohort_id, "team_id": run.team_id, spec.hash_field: pinned}
+
+ updated = Cohort.objects.filter(**cohort_fence, **{f"{spec.stamp_field}__isnull": True}).update(
+ **{spec.stamp_field: Now()}
+ )
if updated:
# ``superseded_at__isnull`` guards a supersession racing in after the up-front check; a
# 0-row stamp then means the participation lost the race, so refuse (finalizer treats it
# as superseded) rather than claim success.
- stamped = (
- CohortBackfillRunCohort.objects.for_team(run.team_id)
- .filter(id=participation.id, superseded_at__isnull=True)
- .update(stamped_at=Now(), error="")
- )
+ stamped = _ratify(run, participation.id)
if not stamped:
# The cohort stamp above is this transaction's own uncommitted write, so take it back:
# leaving it would open ``is_flag_compatible`` on a backfill that just lost the race.
- Cohort.objects.filter(
- id=cohort_id,
- team_id=run.team_id,
- behavioral_filters_shape_hash=participation.behavioral_filters_shape_hash,
- ).update(last_backfill_events_at=None)
- return bool(stamped)
+ Cohort.objects.filter(**cohort_fence).update(**{spec.stamp_field: None})
+ return stamped
current_readiness = (
- Cohort.objects.filter(id=cohort_id, team_id=run.team_id)
- .values_list("behavioral_filters_shape_hash", "last_backfill_events_at")
- .first()
+ Cohort.objects.filter(id=cohort_id, team_id=run.team_id).values_list(spec.hash_field, spec.stamp_field).first()
)
- if (
- current_readiness is not None
- and current_readiness[0] == participation.behavioral_filters_shape_hash
- and current_readiness[1] is not None
- ):
- stamped = (
- CohortBackfillRunCohort.objects.for_team(run.team_id)
- .filter(id=participation.id, superseded_at__isnull=True)
- .update(stamped_at=Now(), error="")
- )
- return bool(stamped)
+ if current_readiness is not None and current_readiness[0] == pinned and current_readiness[1] is not None:
+ return _ratify(run, participation.id)
error = "Cohort definition changed before readiness was stamped"
# ``superseded_at__isnull`` keeps an earlier supersession's timestamp and message rather than
@@ -137,5 +177,19 @@ def stamp_events_readiness(run: CohortBackfillRun, cohort_id: int) -> bool:
CohortBackfillRunStatus.RECONCILING,
),
).update(status=CohortBackfillRunStatus.SUPERSEDED, finished_at=Now(), error=error)
- logger.info("cohort_backfill_readiness_stamp_superseded", run_id=str(run.id), cohort_id=cohort_id)
+ logger.info(
+ "cohort_backfill_readiness_stamp_superseded",
+ run_id=str(run.id),
+ cohort_id=cohort_id,
+ readiness=spec.readiness,
+ )
return False
+
+
+def _ratify(run: CohortBackfillRun, participation_id: UUID) -> bool:
+ """Mark the participation as the one that earned the cohort's stamp, unless it lost the race."""
+ return bool(
+ CohortBackfillRunCohort.objects.for_team(run.team_id)
+ .filter(id=participation_id, superseded_at__isnull=True)
+ .update(stamped_at=Now(), error="")
+ )
diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.py
index e4bce4092f08..678bde0a1204 100644
--- a/products/cohorts/backend/backfill/runs.py
+++ b/products/cohorts/backend/backfill/runs.py
@@ -467,7 +467,7 @@ def supersede_active_runs(team_id: int, cohort_ids: Iterable[int], *, kind: Coho
error = "Cohort definition changed during backfill"
with transaction.atomic():
# Resolve the targets first, then write run rows before participation rows. The finalizer
- # locks in that order (run FOR UPDATE, then participations via stamp_events_readiness), so
+ # locks in that order (run FOR UPDATE, then participations via the readiness stamp), so
# the opposite order here would deadlock the two on a cohort-scoped run.
targets = list(
CohortBackfillRunCohort.objects.for_team(team_id)
diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.py
index 160ff5a06fa6..672a65d625f6 100644
--- a/products/cohorts/backend/backfill/test/test_finalize.py
+++ b/products/cohorts/backend/backfill/test/test_finalize.py
@@ -5,7 +5,7 @@ from unittest import mock
from django.core.cache import cache
from django.db import connection
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
@@ -13,7 +13,7 @@ from parameterized import parameterized
from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs
-from products.cohorts.backend.backfill.finalize import FLAGS_CACHE_TASK, finalize_backfill_runs
+from products.cohorts.backend.backfill.finalize import _STAMP_BY_KIND, FLAGS_CACHE_TASK, finalize_backfill_runs
from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash
from products.cohorts.backend.models.backfill import (
CohortBackfillKind,
@@ -27,9 +27,20 @@ from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.dependencies import _behavioral_cohort_ids_key
+class TestFinalizerKindCoverage(SimpleTestCase):
+ def test_every_backfill_kind_has_a_stamp(self) -> None:
+ unmapped = set(CohortBackfillKind.values) - set(_STAMP_BY_KIND)
+ assert not unmapped, (
+ f"{sorted(unmapped)} has no entry in finalize._STAMP_BY_KIND, so the finalizer's "
+ "discovery filters those runs out entirely: they park in reconciling forever with no "
+ "exception, no error count, and no gauge movement"
+ )
+
+
@override_settings(
REALTIME_COHORT_TEAM_ALLOWLIST="all",
BEHAVIORAL_BACKFILL_FINALIZER_ENABLED=True,
+ BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=True,
)
class TestBackfillFinalizer(BaseTest):
def setUp(self) -> None:
@@ -59,25 +70,36 @@ class TestBackfillFinalizer(BaseTest):
"time_interval": "day",
"operator": "gte",
"operator_value": 2,
- }
+ },
+ {
+ "type": "person",
+ "key": "email",
+ "value": ["[email protected]"],
+ "operator": "exact",
+ "conditionHash": "person-condition-hash",
+ },
],
}
}
- def _make_participation(self, run: CohortBackfillRun, outcome: str) -> tuple[Cohort, CohortBackfillRunCohort]:
- cohort = Cohort.objects.create(
- team=self.team,
- cohort_type=CohortType.REALTIME,
- filters=self._behavioral_filters(),
- )
- ensure_filters_shape_hash(cohort)
- cohort.refresh_from_db()
+ def _make_participation(
+ self, run: CohortBackfillRun, outcome: str, cohort: Cohort | None = None
+ ) -> tuple[Cohort, CohortBackfillRunCohort]:
+ if cohort is None:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ cohort_type=CohortType.REALTIME,
+ filters=self._behavioral_filters(),
+ )
+ ensure_filters_shape_hash(cohort)
+ cohort.refresh_from_db()
participation = CohortBackfillRunCohort.objects.for_team(self.team.id).create(
run=run,
team_id=self.team.id,
cohort=cohort,
filters_shape_hash=cohort.filters_shape_hash or "",
behavioral_filters_shape_hash=cohort.behavioral_filters_shape_hash or "",
+ person_filters_shape_hash=cohort.person_filters_shape_hash or "",
pinned_filters=cohort.filters,
)
# Simulate the Rust seeder's per-participation outcome writes (the columns are the interface).
@@ -103,12 +125,18 @@ class TestBackfillFinalizer(BaseTest):
return cohort, participation
def _make_run(
- self, outcomes: list[str], *, observed: bool = True, scope: str = CohortBackfillScope.TEAM
+ self,
+ outcomes: list[str],
+ *,
+ observed: bool = True,
+ scope: str = CohortBackfillScope.TEAM,
+ kind: str = CohortBackfillKind.BEHAVIORAL,
+ cohorts: list[Cohort] | None = None,
) -> tuple[CohortBackfillRun, list[Cohort]]:
cohort_scoped = scope == CohortBackfillScope.COHORT
run = CohortBackfillRun.objects.for_team(self.team.id).create(
team_id=self.team.id,
- backfill_kind=CohortBackfillKind.BEHAVIORAL,
+ backfill_kind=kind,
trigger_kind=(
CohortBackfillTrigger.COHORT_CREATED if cohort_scoped else CohortBackfillTrigger.TEAM_ENABLEMENT
),
@@ -117,7 +145,11 @@ class TestBackfillFinalizer(BaseTest):
reconcile_observed_at=timezone.now() if observed else None,
timezone="UTC",
)
- cohorts = [self._make_participation(run, outcome)[0] for outcome in outcomes]
+ shared = cohorts if cohorts is not None else [None] * len(outcomes)
+ cohorts = [
+ self._make_participation(run, outcome, cohort=cohort)[0]
+ for outcome, cohort in zip(outcomes, shared, strict=True)
+ ]
if cohort_scoped:
run.cohort = cohorts[0]
run.save(update_fields=["cohort"])
@@ -166,28 +198,98 @@ class TestBackfillFinalizer(BaseTest):
self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)
self.assertIsNone(cohorts[0].last_backfill_events_at)
- def test_observed_person_run_is_untouched(self) -> None:
- run = CohortBackfillRun.objects.for_team(self.team.id).create(
- team_id=self.team.id,
- backfill_kind=CohortBackfillKind.PERSON_PROPERTY,
- trigger_kind=CohortBackfillTrigger.TEAM_ENABLEMENT,
- scope=CohortBackfillScope.TEAM,
- status=CohortBackfillRunStatus.RECONCILING,
- reconcile_observed_at=timezone.now(),
- timezone="UTC",
+ def test_one_pass_finalizes_each_kind_into_its_own_column(self) -> None:
+ behavioral, behavioral_cohorts = self._make_run(["completed"])
+ person, person_cohorts = self._make_run(["completed"], kind=CohortBackfillKind.PERSON_PROPERTY)
+
+ result = finalize_backfill_runs()
+
+ behavioral.refresh_from_db()
+ person.refresh_from_db()
+ behavioral_cohorts[0].refresh_from_db()
+ person_cohorts[0].refresh_from_db()
+ self.assertEqual(result.completed, 2)
+ self.assertEqual(behavioral.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(person.status, CohortBackfillRunStatus.COMPLETED)
+ # Each run stamps its own column and leaves the other for its sibling to earn. Both cohorts
+ # are mixed, so neither is flag-compatible off one run.
+ self.assertIsNotNone(behavioral_cohorts[0].last_backfill_events_at)
+ self.assertIsNone(behavioral_cohorts[0].last_backfill_person_properties_at)
+ self.assertIsNotNone(person_cohorts[0].last_backfill_person_properties_at)
+ self.assertIsNone(person_cohorts[0].last_backfill_events_at)
+ self.assertFalse(behavioral_cohorts[0].is_flag_compatible)
+ self.assertFalse(person_cohorts[0].is_flag_compatible)
+
+ def test_mixed_cohort_earns_both_stamps_from_two_runs_on_one_cohort(self) -> None:
+ # The production shape `cohort_bfr_active_team_kind_uq` permits: one mixed cohort reached by
+ # two team-scoped runs, one per kind. The second stamp must neither be blocked by nor clobber
+ # the first — only with both columns does the cohort become flag-compatible.
+ behavioral, cohorts = self._make_run(["completed"])
+ person, _ = self._make_run(["completed"], kind=CohortBackfillKind.PERSON_PROPERTY, cohorts=cohorts)
+
+ result = finalize_backfill_runs()
+
+ behavioral.refresh_from_db()
+ person.refresh_from_db()
+ cohorts[0].refresh_from_db()
+ self.assertEqual(result.completed, 2)
+ self.assertEqual(behavioral.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(person.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertIsNotNone(cohorts[0].last_backfill_events_at)
+ self.assertIsNotNone(cohorts[0].last_backfill_person_properties_at)
+ self.assertTrue(cohorts[0].is_flag_compatible)
+
+ @override_settings(BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=False)
+ def test_person_run_is_held_not_superseded_while_the_readiness_gate_is_off(self) -> None:
+ behavioral, behavioral_cohorts = self._make_run(["completed"])
+ person, person_cohorts = self._make_run(["completed"], kind=CohortBackfillKind.PERSON_PROPERTY)
+
+ result = finalize_backfill_runs()
+
+ behavioral.refresh_from_db()
+ person.refresh_from_db()
+ behavioral_cohorts[0].refresh_from_db()
+ person_cohorts[0].refresh_from_db()
+ person_participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run_id=person.id)
+ # The behavioral run is unaffected: the gate narrows discovery by kind, not the whole pass.
+ self.assertEqual(behavioral.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertIsNotNone(behavioral_cohorts[0].last_backfill_events_at)
+ # No stamp: the flags service reads this column as proof cohort_membership is populated.
+ self.assertIsNone(person_cohorts[0].last_backfill_person_properties_at)
+ # Held, not discarded. Gating inside the stamp would supersede the participation, throwing
+ # away a completed person backfill that should finalize once the gate opens.
+ self.assertEqual(person.status, CohortBackfillRunStatus.RECONCILING)
+ self.assertIsNone(person_participation.superseded_at)
+ self.assertIsNone(person_participation.stamped_at)
+ self.assertEqual(result.completed, 1)
+ # The backlog behind the gate is otherwise invisible: discovery never surfaces these runs,
+ # so `held` stays 0.
+ self.assertEqual(result.gated, 1)
+ self.assertEqual(result.held, 0)
+
+ @override_settings(BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS=2)
+ def test_budget_is_sliced_per_kind_so_a_person_backlog_cannot_starve_behavioral_runs(self) -> None:
+ # Two kinds split the cap one slot each. Both person runs are older than the behavioral one,
+ # so under a single shared cap they would take the whole budget. Cohort scope because
+ # `cohort_bfr_active_team_kind_uq` forbids two active team-scoped runs of one kind per team.
+ first_person, _ = self._make_run(
+ ["completed"], kind=CohortBackfillKind.PERSON_PROPERTY, scope=CohortBackfillScope.COHORT
)
- cohort, participation = self._make_participation(run, "completed")
+ second_person, _ = self._make_run(
+ ["completed"], kind=CohortBackfillKind.PERSON_PROPERTY, scope=CohortBackfillScope.COHORT
+ )
+ behavioral, _ = self._make_run(["completed"])
result = finalize_backfill_runs()
- run.refresh_from_db()
- cohort.refresh_from_db()
- participation.refresh_from_db()
- self.assertEqual(result.runs_scanned, 0)
- self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)
- self.assertIsNone(cohort.last_backfill_events_at)
- self.assertIsNone(cohort.last_backfill_person_properties_at)
- self.assertIsNone(participation.stamped_at)
+ for run in (first_person, second_person, behavioral):
+ run.refresh_from_db()
+ self.assertEqual(result.completed, 2)
+ self.assertEqual(first_person.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(behavioral.status, CohortBackfillRunStatus.COMPLETED)
+ # The slice still truncates, so a pass stays bounded in the runs it walks and the older
+ # person backlog does not take the behavioral slot.
+ self.assertEqual(second_person.status, CohortBackfillRunStatus.RECONCILING)
def test_second_fire_is_a_noop(self) -> None:
run, _cohorts = self._make_run(["completed", "completed"])
diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.py
index 5a5945ba75ba..1f9672a5d394 100644
--- a/products/cohorts/backend/backfill/test/test_readiness.py
+++ b/products/cohorts/backend/backfill/test/test_readiness.py
@@ -6,17 +6,48 @@ from django.test import override_settings
from django.test.utils import CaptureQueriesContext
from django.utils import timezone
-from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash, stamp_events_readiness
-from products.cohorts.backend.backfill.runs import create_backfill_run_for_cohort
+from parameterized import parameterized
+
+from products.cohorts.backend.backfill.readiness import (
+ ensure_filters_shape_hash,
+ stamp_events_readiness,
+ stamp_person_properties_readiness,
+)
+from products.cohorts.backend.backfill.runs import create_backfill_run_for_cohort, create_person_backfill_run_for_cohort
from products.cohorts.backend.models.backfill import CohortBackfillRunCohort, CohortBackfillRunStatus
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
+# (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.
+KINDS = [
+ (
+ "events",
+ create_backfill_run_for_cohort,
+ stamp_events_readiness,
+ "behavioral_filters_shape_hash",
+ "last_backfill_events_at",
+ (30, "person-a"),
+ (7, "person-b"),
+ ),
+ (
+ "person_properties",
+ create_person_backfill_run_for_cohort,
+ stamp_person_properties_readiness,
+ "person_filters_shape_hash",
+ "last_backfill_person_properties_at",
+ (7, "person-b"),
+ (30, "person-a"),
+ ),
+]
+
@override_settings(
REALTIME_COHORT_TEAM_ALLOWLIST="all",
BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,
BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,
+ BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED=True,
)
class TestBackfillReadiness(BaseTest):
def setUp(self) -> None:
@@ -53,82 +84,90 @@ class TestBackfillReadiness(BaseTest):
)
return {"properties": {"type": "AND", "values": values}}
- def _cohort_and_run(self):
+ def _cohort_and_run(self, make_run=create_backfill_run_for_cohort):
cohort = Cohort.objects.create(
team=self.team,
cohort_type=CohortType.REALTIME,
- filters=self._filters(7),
+ filters=self._filters(7, person_hash="person-a"),
)
- run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ run = make_run(self.team.id, cohort.id, "cohort_created")
assert run is not None
return cohort, run
- def test_stamp_uses_one_conditional_cohort_update(self) -> None:
- cohort, run = self._cohort_and_run()
+ @parameterized.expand(KINDS)
+ def test_stamp_uses_one_conditional_cohort_update(
+ self, _name: str, make_run, stamp, hash_column: str, stamp_column: str, *_edits
+ ) -> None:
+ cohort, run = self._cohort_and_run(make_run)
with CaptureQueriesContext(connection) as queries:
- self.assertTrue(stamp_events_readiness(run, cohort.id))
+ self.assertTrue(stamp(run, cohort.id))
cohort.refresh_from_db()
participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
- self.assertIsNotNone(cohort.last_backfill_events_at)
+ self.assertIsNotNone(getattr(cohort, stamp_column))
self.assertIsNotNone(participation.stamped_at)
cohort_updates = [query["sql"] for query in queries if query["sql"].startswith('UPDATE "posthog_cohort"')]
self.assertEqual(len(cohort_updates), 1)
- self.assertIn('"behavioral_filters_shape_hash"', cohort_updates[0])
- self.assertIn('"last_backfill_events_at" IS NULL', cohort_updates[0])
-
- def test_edit_between_completion_and_stamp_fails_cas(self) -> None:
- cohort, run = self._cohort_and_run()
- cohort.filters = self._filters(30)
+ self.assertIn(f'"{hash_column}"', cohort_updates[0])
+ self.assertIn(f'"{stamp_column}" IS NULL', cohort_updates[0])
+
+ @parameterized.expand(KINDS)
+ def test_edit_of_the_stamped_kind_fails_cas(
+ self, _name: str, make_run, stamp, _hash: str, stamp_column: str, same_kind_edit, _other
+ ) -> None:
+ cohort, run = self._cohort_and_run(make_run)
+ # Shift the leaves of the kind under test, leaving the other kind's hash alone.
+ cohort.filters = self._filters(same_kind_edit[0], person_hash=same_kind_edit[1])
cohort.save(update_fields=["filters"])
- self.assertFalse(stamp_events_readiness(run, cohort.id))
+ self.assertFalse(stamp(run, cohort.id))
cohort.refresh_from_db()
run.refresh_from_db()
- self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(getattr(cohort, stamp_column))
self.assertEqual(run.status, CohortBackfillRunStatus.SUPERSEDED)
- def test_person_only_edit_between_completion_and_stamp_stamps_readiness(self) -> None:
- # A person-property edit shifts the full filters hash but not the behavioral one, and does
- # not null events readiness. The events backfill is still valid, so the stamp must succeed
- # rather than supersede the run (the sibling behavioral edit above correctly supersedes).
- cohort = Cohort.objects.create(
- team=self.team,
- cohort_type=CohortType.REALTIME,
- filters=self._filters(7, person_hash="person-a"),
- )
- run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
- assert run is not None
+ @parameterized.expand(KINDS)
+ def test_edit_of_the_other_kind_still_stamps_readiness(
+ self, _name: str, make_run, stamp, _hash: str, stamp_column: str, _same, other_kind_edit
+ ) -> None:
+ # An edit shifts the full filters hash but only nulls the readiness of the kind it touched.
+ # The other kind's backfill is still valid, so its stamp must succeed rather than supersede
+ # the run (the sibling test above correctly supersedes on a same-kind edit).
+ cohort, run = self._cohort_and_run(make_run)
old_full_hash = cohort.filters_shape_hash
-
- cohort.filters = self._filters(7, person_hash="person-b")
+ cohort.filters = self._filters(other_kind_edit[0], person_hash=other_kind_edit[1])
cohort.save(update_fields=["filters"])
cohort.refresh_from_db()
self.assertNotEqual(cohort.filters_shape_hash, old_full_hash)
- self.assertTrue(stamp_events_readiness(run, cohort.id))
+ self.assertTrue(stamp(run, cohort.id))
cohort.refresh_from_db()
run.refresh_from_db()
participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
- self.assertIsNotNone(cohort.last_backfill_events_at)
+ self.assertIsNotNone(getattr(cohort, stamp_column))
self.assertIsNotNone(participation.stamped_at)
self.assertIsNone(participation.superseded_at)
self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)
- def test_already_stamped_readiness_is_not_overwritten(self) -> None:
- cohort, run = self._cohort_and_run()
+ @parameterized.expand(KINDS)
+ def test_already_stamped_readiness_is_not_overwritten(
+ self, _name: str, make_run, stamp, _hash: str, stamp_column: str, *_edits
+ ) -> None:
+ # The only path that reads the spec's columns back as a projection, so a transposed
+ # `values_list` would surface here and nowhere else.
+ cohort, run = self._cohort_and_run(make_run)
first_stamp = timezone.now()
- Cohort.objects.filter(id=cohort.id).update(last_backfill_events_at=first_stamp)
+ Cohort.objects.filter(id=cohort.id).update(**{stamp_column: first_stamp})
- self.assertTrue(stamp_events_readiness(run, cohort.id))
+ self.assertTrue(stamp(run, cohort.id))
cohort.refresh_from_db()
run.refresh_from_db()
participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
- self.assertEqual(cohort.last_backfill_events_at, first_stamp)
+ self.assertEqual(getattr(cohort, stamp_column), first_stamp)
self.assertIsNotNone(participation.stamped_at)
self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)
@@ -141,9 +180,9 @@ class TestBackfillReadiness(BaseTest):
# A -> B -> A: edit the behavioral window away and back so the cohort's current hash matches
# the pinned one again. The up-front guard must still refuse the terminal participation.
- cohort.filters = self._filters(30)
+ cohort.filters = self._filters(30, person_hash="person-a")
cohort.save(update_fields=["filters"])
- cohort.filters = self._filters(7)
+ cohort.filters = self._filters(7, person_hash="person-a")
cohort.save(update_fields=["filters"])
cohort.refresh_from_db()
participation.refresh_from_db()
@@ -156,8 +195,11 @@ class TestBackfillReadiness(BaseTest):
self.assertIsNone(cohort.last_backfill_events_at)
self.assertIsNone(participation.stamped_at)
- def test_supersession_racing_the_stamp_rolls_the_cohort_back(self) -> None:
- cohort, run = self._cohort_and_run()
+ @parameterized.expand(KINDS)
+ def test_supersession_racing_the_stamp_rolls_the_cohort_back(
+ self, _name: str, make_run, stamp, _hash: str, stamp_column: str, *_edits
+ ) -> None:
+ cohort, run = self._cohort_and_run(make_run)
participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run=run)
superseded: list[bool] = []
@@ -173,11 +215,11 @@ class TestBackfillReadiness(BaseTest):
# A supersession commits after the cohort stamp but before the participation CAS ratifies
# it. The stamp is this transaction's own write, so it has to be taken back.
with connection.execute_wrapper(supersede_after_the_cohort_stamp):
- self.assertFalse(stamp_events_readiness(run, cohort.id))
+ self.assertFalse(stamp(run, cohort.id))
cohort.refresh_from_db()
participation.refresh_from_db()
- self.assertIsNone(cohort.last_backfill_events_at)
+ self.assertIsNone(getattr(cohort, stamp_column))
self.assertIsNone(participation.stamped_at)
# The rollback must leave the participation terminal — the finalizer reads superseded_at to
# decide the run's outcome, so clearing it here would make the run reconcile forever.
diff --git a/rust/cohort-core/src/filters/loader.rs b/rust/cohort-core/src/filters/loader.rs
index e1a340835d53..9fd43c0186ab 100644
--- a/rust/cohort-core/src/filters/loader.rs
+++ b/rust/cohort-core/src/filters/loader.rs
@@ -16,12 +16,12 @@ use crate::metrics::{
FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_INVALID_SHAPE_HASH,
FILTER_CATALOG_TZ_FALLBACK,
};
-use crate::seed::BehavioralShapeHash;
+use crate::seed::{BehavioralShapeHash, PersonShapeHash, ScopeKind, ShapeHashError};
/// Realtime cohorts to load, mirroring the Node filter manager's predicate, joined to
/// `posthog_team` for the team timezone the bucket variants use for calendar-day computation.
pub const REALTIME_COHORTS_SQL: &str = "SELECT c.id, c.team_id, c.filters, \
- c.behavioral_filters_shape_hash, t.timezone \
+ c.behavioral_filters_shape_hash, c.person_filters_shape_hash, t.timezone \
FROM posthog_cohort c \
JOIN posthog_team t ON t.id = c.team_id \
WHERE c.cohort_type = 'realtime' AND c.deleted = false AND c.filters IS NOT NULL";
@@ -33,6 +33,7 @@ pub struct CohortRow {
pub team_id: i32,
pub filters: Value,
pub behavioral_filters_shape_hash: Option<String>,
+ pub person_filters_shape_hash: Option<String>,
/// `posthog_team.timezone` — a non-null IANA zone name (default `"UTC"`).
pub timezone: String,
}
@@ -62,23 +63,22 @@ pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> F
match builder.add_cohort(cohort_id, team_id, &row.filters) {
Ok(()) => {
- match row.behavioral_filters_shape_hash {
- // Python's canonical extractor returns an empty string when a cohort has no
- // behavioral leaves. It is an expected unknown guard, not malformed data.
- None => {}
- Some(raw_hash) if raw_hash.is_empty() => {}
- Some(raw_hash) => match BehavioralShapeHash::parse(&raw_hash) {
- Ok(hash) => builder.set_behavioral_shape_hash(cohort_id, hash),
- Err(error) => {
- counter!(FILTER_CATALOG_INVALID_SHAPE_HASH).increment(1);
- warn!(
- cohort_id = cohort_id.0,
- team_id = team_id.0,
- error = %error,
- "ignoring invalid persisted behavioral shape hash",
- );
- }
- },
+ let cohort = (cohort_id, team_id);
+ if let Some(hash) = shape_guard(
+ row.behavioral_filters_shape_hash.as_deref(),
+ BehavioralShapeHash::parse,
+ ScopeKind::Behavioral,
+ cohort,
+ ) {
+ builder.set_behavioral_shape_hash(cohort_id, hash);
+ }
+ if let Some(hash) = shape_guard(
+ row.person_filters_shape_hash.as_deref(),
+ PersonShapeHash::parse,
+ ScopeKind::PersonProperty,
+ cohort,
+ ) {
+ builder.set_person_shape_hash(cohort_id, hash);
}
}
Err(err) => {
@@ -100,6 +100,33 @@ pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> F
)
}
+/// One persisted shape-hash column as a reconcile guard, or `None` when there is nothing to guard
+/// with. Python's canonical extractor returns an empty string for a cohort with no leaves of that
+/// kind, so NULL and `""` are expected absences rather than malformed data; only a value that
+/// fails the newtype's bounds is counted and warned.
+fn shape_guard<T>(
+ raw: Option<&str>,
+ parse: fn(&str) -> Result<T, ShapeHashError>,
+ kind: ScopeKind,
+ (cohort_id, team_id): (CohortId, TeamId),
+) -> Option<T> {
+ let raw = raw.filter(|hash| !hash.is_empty())?;
+ match parse(raw) {
+ Ok(hash) => Some(hash),
+ Err(error) => {
+ counter!(FILTER_CATALOG_INVALID_SHAPE_HASH, "kind" => kind.as_str()).increment(1);
+ warn!(
+ cohort_id = cohort_id.0,
+ team_id = team_id.0,
+ kind = kind.as_str(),
+ error = %error,
+ "ignoring invalid persisted shape hash",
+ );
+ None
+ }
+ }
+}
+
/// Resolve a team's `posthog_team.timezone`, falling back to UTC for an unrecognized zone. Counts
/// and logs the fallback with the offending `team_id`. The raw string goes only to the `warn!`,
/// never the (label-free) counter.
@@ -132,13 +159,19 @@ mod tests {
team_id,
filters,
behavioral_filters_shape_hash: None,
+ person_filters_shape_hash: None,
timezone: timezone.to_string(),
}
}
- fn row_with_shape_hash(id: i32, team_id: i32, shape_hash: Option<&str>) -> CohortRow {
- let mut row = row(id, team_id, behavioral_cohort());
- row.behavioral_filters_shape_hash = shape_hash.map(str::to_string);
+ const PERSON_SHAPE_HASH: &str = "persisted-person-hash";
+
+ /// A parseable cohort with its two guard columns set independently, so no assertion can pass
+ /// while the loader reads the wrong one.
+ fn row_with_guards(id: i32, behavioral: Option<&str>, person: Option<&str>) -> CohortRow {
+ let mut row = row(id, 7, behavioral_cohort());
+ row.behavioral_filters_shape_hash = behavioral.map(str::to_string);
+ row.person_filters_shape_hash = person.map(str::to_string);
row
}
@@ -166,17 +199,22 @@ mod tests {
}
#[test]
- fn build_catalog_carries_only_valid_persisted_behavioral_shape_hashes() {
+ fn build_catalog_carries_only_valid_persisted_shape_hashes() {
assert!(REALTIME_COHORTS_SQL.contains("c.behavioral_filters_shape_hash"));
+ assert!(REALTIME_COHORTS_SQL.contains("c.person_filters_shape_hash"));
let mut malformed = row(5, 7, json!({ "bogus": true }));
malformed.behavioral_filters_shape_hash = Some(SHAPE_HASH.to_string());
+ malformed.person_filters_shape_hash = Some(PERSON_SHAPE_HASH.to_string());
let catalog = build_catalog_from_rows(
vec![
- row_with_shape_hash(1, 7, Some(SHAPE_HASH)),
- row_with_shape_hash(2, 7, None),
- row_with_shape_hash(3, 7, Some("")),
- row_with_shape_hash(4, 7, Some("non-ascii-é")),
+ row_with_guards(1, Some(SHAPE_HASH), Some(PERSON_SHAPE_HASH)),
+ row_with_guards(2, None, None),
+ row_with_guards(3, Some(""), Some("")),
+ row_with_guards(4, Some("non-ascii-é"), Some("non-ascii-é")),
malformed,
+ // A cohort with leaves of only one kind carries only that kind's guard.
+ row_with_guards(6, Some(SHAPE_HASH), None),
+ row_with_guards(7, None, Some(PERSON_SHAPE_HASH)),
],
false,
);
@@ -186,10 +224,19 @@ mod tests {
team.behavioral_shape_hashes[&CohortId(1)].as_str(),
SHAPE_HASH,
);
- assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(2)));
- assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(3)));
- assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(4)));
- assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(5)));
+ assert_eq!(
+ team.person_shape_hashes[&CohortId(1)].as_str(),
+ PERSON_SHAPE_HASH,
+ );
+ // NULL, empty (no leaves of that kind), invalid, and unparsed-cohort rows all carry no guard.
+ for absent in [2, 3, 4, 5] {
+ assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(absent)));
+ assert!(!team.person_shape_hashes.contains_key(&CohortId(absent)));
+ }
+ assert!(team.behavioral_shape_hashes.contains_key(&CohortId(6)));
+ assert!(!team.person_shape_hashes.contains_key(&CohortId(6)));
+ assert!(!team.behavioral_shape_hashes.contains_key(&CohortId(7)));
+ assert!(team.person_shape_hashes.contains_key(&CohortId(7)));
assert!(team.cohorts.contains_key(&CohortId(3)));
assert!(
team.cohorts.contains_key(&CohortId(4)),
diff --git a/rust/cohort-core/src/filters/reverse_index.rs b/rust/cohort-core/src/filters/reverse_index.rs
index 4ddf2376cf0d..4f10ef1d5eeb 100644
--- a/rust/cohort-core/src/filters/reverse_index.rs
+++ b/rust/cohort-core/src/filters/reverse_index.rs
@@ -23,7 +23,7 @@ use crate::leaf_state::variant::StateVariant;
use crate::metrics::{
COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,
};
-use crate::seed::BehavioralShapeHash;
+use crate::seed::{BehavioralShapeHash, PersonShapeHash};
#[derive(Debug, Clone, Copy)]
pub struct LeafStateMeta {
@@ -73,6 +73,8 @@ pub struct TeamFilters {
pub cohorts: HashMap<CohortId, CohortTree>,
/// Persisted behavioral leaf-shape hashes used to fence reconcile work from cohort edits.
pub behavioral_shape_hashes: HashMap<CohortId, BehavioralShapeHash>,
+ /// The person-property counterpart, fencing a person-property run's reconcile.
+ pub person_shape_hashes: HashMap<CohortId, PersonShapeHash>,
/// The team's resolved IANA timezone, used by bucket variants for calendar-day computation.
pub timezone: Tz,
}
@@ -98,6 +100,7 @@ impl Default for TeamFilters {
eligibility: HashMap::new(),
cohorts: HashMap::new(),
behavioral_shape_hashes: HashMap::new(),
+ person_shape_hashes: HashMap::new(),
timezone: UTC,
}
}
@@ -123,6 +126,7 @@ pub struct TeamFiltersBuilder {
/// Per-cohort eligibility signals captured during parse.
flags: HashMap<CohortId, CohortParseFlags>,
behavioral_shape_hashes: HashMap<CohortId, BehavioralShapeHash>,
+ person_shape_hashes: HashMap<CohortId, PersonShapeHash>,
}
impl LeafSink for TeamFiltersBuilder {
@@ -167,6 +171,11 @@ impl TeamFiltersBuilder {
self.behavioral_shape_hashes.insert(cohort_id, hash);
}
+ /// The person-property counterpart of [`TeamFiltersBuilder::set_behavioral_shape_hash`].
+ pub fn set_person_shape_hash(&mut self, cohort_id: CohortId, hash: PersonShapeHash) {
+ self.person_shape_hashes.insert(cohort_id, hash);
+ }
+
pub fn add_cohort(
&mut self,
cohort_id: CohortId,
@@ -290,6 +299,8 @@ impl TeamFiltersBuilder {
.collect();
let mut behavioral_shape_hashes = self.behavioral_shape_hashes;
behavioral_shape_hashes.retain(|cohort_id, _| self.cohorts.contains_key(cohort_id));
+ let mut person_shape_hashes = self.person_shape_hashes;
+ person_shape_hashes.retain(|cohort_id, _| self.cohorts.contains_key(cohort_id));
TeamFilters {
by_condition_to_lsk: sorted_vec_map(self.by_condition_to_lsk),
@@ -308,6 +319,7 @@ impl TeamFiltersBuilder {
eligibility,
cohorts: self.cohorts,
behavioral_shape_hashes,
+ person_shape_hashes,
timezone,
}
}
@@ -520,7 +532,7 @@ mod tests {
}
#[test]
- fn freeze_retains_behavioral_shape_hashes_only_for_parsed_cohorts() {
+ fn freeze_retains_shape_hashes_only_for_parsed_cohorts() {
let mut builder = TeamFiltersBuilder::default();
builder.set_behavioral_shape_hash(
CohortId(1),
@@ -528,11 +540,16 @@ mod tests {
);
builder
.set_behavioral_shape_hash(CohortId(99), BehavioralShapeHash::parse("orphan").unwrap());
+ builder.set_person_shape_hash(
+ CohortId(1),
+ PersonShapeHash::parse("persisted-person").unwrap(),
+ );
+ builder.set_person_shape_hash(CohortId(99), PersonShapeHash::parse("orphan").unwrap());
builder
.add_cohort(
CohortId(1),
TeamId(7),
- &wrap(vec![behavioral_performed_event(7)]),
+ &wrap(vec![behavioral_performed_event(7), person_leaf()]),
)
.unwrap();
@@ -541,7 +558,12 @@ mod tests {
frozen.behavioral_shape_hashes[&CohortId(1)].as_str(),
"persisted",
);
+ assert_eq!(
+ frozen.person_shape_hashes[&CohortId(1)].as_str(),
+ "persisted-person",
+ );
assert!(!frozen.behavioral_shape_hashes.contains_key(&CohortId(99)));
+ assert!(!frozen.person_shape_hashes.contains_key(&CohortId(99)));
}
#[test]
diff --git a/rust/cohort-core/src/metrics.rs b/rust/cohort-core/src/metrics.rs
index a45e1ef9a08e..13a67bbace94 100644
--- a/rust/cohort-core/src/metrics.rs
+++ b/rust/cohort-core/src/metrics.rs
@@ -10,9 +10,11 @@ pub const FILTER_CATALOG_SKIPPED_LEAVES: &str = "filter_catalog_skipped_leaves_t
pub const FILTER_CATALOG_COHORT_PARSE_ERRORS: &str = "filter_catalog_cohort_parse_errors_total";
/// Teams whose timezone did not parse as an IANA zone and fell back to UTC (counter).
pub const FILTER_CATALOG_TZ_FALLBACK: &str = "filter_catalog_tz_fallback_total";
-/// Cohorts whose persisted `behavioral_filters_shape_hash` failed to parse (counter). The cohort
-/// loads but reads as `HashUnknown`, so every reconcile for it discards — **alert on a sustained
-/// non-zero level**, it signals drift between the Python hash extractor and the Rust bounds.
+/// Cohorts whose persisted shape hash failed to parse, labelled by the `kind` whose column it was
+/// — `behavioral_filters_shape_hash` or `person_filters_shape_hash` (counter). The cohort loads but
+/// reads as `HashUnknown` for that kind, so every reconcile of that kind discards — **alert on a
+/// sustained non-zero level**, it signals drift between that kind's Python hash extractor and the
+/// Rust bounds. The two extractors are independent, so alert per `kind` rather than on the sum.
pub const FILTER_CATALOG_INVALID_SHAPE_HASH: &str = "filter_catalog_invalid_shape_hash_total";
/// Cohorts classified by composition eligibility at freeze, labelled by `class` (counter).
pub const COHORT_ELIGIBILITY_TOTAL: &str = "cohort_eligibility_total";
diff --git a/rust/cohort-core/src/seed/decode.rs b/rust/cohort-core/src/seed/decode.rs
index f46f676075a0..ffa55ebf47d4 100644
--- a/rust/cohort-core/src/seed/decode.rs
+++ b/rust/cohort-core/src/seed/decode.rs
@@ -7,7 +7,9 @@
use serde::Deserialize;
use super::person::{PersonSeed, PERSON_KIND, PERSON_SCHEMA_VERSION};
-use super::reconcile::{ReconcileTile, RECONCILE_KIND, RECONCILE_SCHEMA_VERSION};
+use super::reconcile::{
+ ReconcileTile, RECONCILE_KIND, RECONCILE_PERSON_KIND, RECONCILE_SCHEMA_VERSION,
+};
use super::tile::{SeedTile, SCHEMA_VERSION, TILE_KIND};
/// The probe outcome for a supported-or-not payload. `UnknownKind` covers kinds this consumer does
@@ -33,16 +35,20 @@ pub fn decode_seed(payload: &[u8]) -> Result<DecodedSeed, serde_json::Error> {
TILE_KIND if probe.schema_version == SCHEMA_VERSION => {
Ok(DecodedSeed::Tile(serde_json::from_slice(payload)?))
}
- RECONCILE_KIND if probe.schema_version == RECONCILE_SCHEMA_VERSION => {
+ RECONCILE_KIND | RECONCILE_PERSON_KIND
+ if probe.schema_version == RECONCILE_SCHEMA_VERSION =>
+ {
Ok(DecodedSeed::Reconcile(serde_json::from_slice(payload)?))
}
PERSON_KIND if probe.schema_version == PERSON_SCHEMA_VERSION => {
Ok(DecodedSeed::Person(serde_json::from_slice(payload)?))
}
- TILE_KIND | RECONCILE_KIND | PERSON_KIND => Ok(DecodedSeed::UnsupportedSchema {
- kind: probe.kind,
- schema_version: probe.schema_version,
- }),
+ TILE_KIND | RECONCILE_KIND | RECONCILE_PERSON_KIND | PERSON_KIND => {
+ Ok(DecodedSeed::UnsupportedSchema {
+ kind: probe.kind,
+ schema_version: probe.schema_version,
+ })
+ }
_ => Ok(DecodedSeed::UnknownKind {
kind: probe.kind,
schema_version: probe.schema_version,
@@ -58,8 +64,8 @@ mod tests {
use crate::filters::TeamId;
use crate::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, ReconcileTile, RunId, SChunkMs,
- ScannedAtMs,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, PersonShapeHash,
+ ReconcileScope, ReconcileTile, RunId, SChunkMs, ScannedAtMs,
};
use super::*;
@@ -82,10 +88,12 @@ mod tests {
serde_json::to_value(ReconcileTile::new(
TeamId(2),
crate::filters::CohortId(42),
- BehavioralShapeHash::parse(
- "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- )
- .unwrap(),
+ ReconcileScope::Behavioral(
+ BehavioralShapeHash::parse(
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ )
+ .unwrap(),
+ ),
RunId(Uuid::nil()),
))
.unwrap()
@@ -120,6 +128,29 @@ mod tests {
DecodedSeed::Reconcile(serde_json::from_value(reconcile.clone()).unwrap()),
);
+ // A person-scoped reconcile rides its own kind, which this probe must admit — a consumer
+ // without this arm routes it to `UnknownKind` instead.
+ let person_reconcile = serde_json::to_value(ReconcileTile::new(
+ TeamId(2),
+ crate::filters::CohortId(42),
+ ReconcileScope::PersonProperty(
+ PersonShapeHash::parse(
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ )
+ .unwrap(),
+ ),
+ RunId(Uuid::nil()),
+ ))
+ .unwrap();
+ assert_eq!(
+ person_reconcile["kind"],
+ serde_json::json!("reconcile_person")
+ );
+ assert_eq!(
+ decode(&person_reconcile).unwrap(),
+ DecodedSeed::Reconcile(serde_json::from_value(person_reconcile.clone()).unwrap()),
+ );
+
let person = person_json();
assert_eq!(
decode(&person).unwrap(),
@@ -161,16 +192,22 @@ mod tests {
}
);
- let mut newer_reconcile = reconcile.clone();
- newer_reconcile["schema_version"] = serde_json::json!(2);
- newer_reconcile["filters_hash"] = serde_json::json!("");
- assert_eq!(
- decode(&newer_reconcile).unwrap(),
- DecodedSeed::UnsupportedSchema {
- kind: "reconcile".to_string(),
- schema_version: 2,
- },
- );
+ // Both reconcile kinds have to reach the unsupported-schema arm. A person tile at a future
+ // schema that missed it would count as `unknown_kind` instead, reading as "some other
+ // producer's message" rather than "this message is ours and we are too old for it".
+ for base in [&reconcile, &person_reconcile] {
+ let mut newer_reconcile = base.clone();
+ let kind = newer_reconcile["kind"].as_str().unwrap().to_string();
+ newer_reconcile["schema_version"] = serde_json::json!(2);
+ newer_reconcile["filters_hash"] = serde_json::json!("");
+ assert_eq!(
+ decode(&newer_reconcile).unwrap(),
+ DecodedSeed::UnsupportedSchema {
+ kind,
+ schema_version: 2,
+ },
+ );
+ }
// A supported kind/schema with a malformed body is a decode error, not a skip: the probe
// admits it, the full parse rejects it (zero count here).
diff --git a/rust/cohort-core/src/seed/mod.rs b/rust/cohort-core/src/seed/mod.rs
index 999cc9518fe7..5e6d0344310b 100644
--- a/rust/cohort-core/src/seed/mod.rs
+++ b/rust/cohort-core/src/seed/mod.rs
@@ -20,6 +20,7 @@ pub use decode::{decode_seed, DecodedSeed};
pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs, ScannedAtMs};
pub use person::{PersonSeed, PersonSeedError, MAX_PERSON_SEED_HASHES};
pub use reconcile::{
- BehavioralShapeHash, BehavioralShapeHashError, ReconcileCompleteMarker, ReconcileTile,
+ BehavioralShapeHash, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope, ReconcileTile,
+ ReconcileTileError, ScopeKind, ShapeHashError, UnknownScopeKind,
};
pub use tile::SeedTile;
diff --git a/rust/cohort-core/src/seed/reconcile.rs b/rust/cohort-core/src/seed/reconcile.rs
index 2bb599e37857..80d34e2e1e88 100644
--- a/rust/cohort-core/src/seed/reconcile.rs
+++ b/rust/cohort-core/src/seed/reconcile.rs
@@ -13,22 +13,32 @@ use super::ids::RunId;
pub(super) const RECONCILE_SCHEMA_VERSION: u32 = 1;
pub(super) const RECONCILE_KIND: &str = "reconcile";
+pub(super) const RECONCILE_PERSON_KIND: &str = "reconcile_person";
+
+/// The bounds every persisted shape-hash column shares: non-empty, ASCII, at most 64 bytes.
+fn validate_shape_hash(value: &str) -> Result<(), ShapeHashError> {
+ if value.is_empty() {
+ return Err(ShapeHashError::Empty);
+ }
+ if value.len() > 64 {
+ return Err(ShapeHashError::TooLong(value.len()));
+ }
+ if !value.is_ascii() {
+ return Err(ShapeHashError::NonAscii);
+ }
+ Ok(())
+}
/// The persisted behavioral filter-shape fingerprint that fences a reconcile job from cohort edits.
-#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+///
+/// Distinct from [`PersonShapeHash`] despite sharing its bounds: the type is what stops a person
+/// hash from ever being compared against a behavioral one.
+#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BehavioralShapeHash(Box<str>);
impl BehavioralShapeHash {
- pub fn parse(value: &str) -> Result<Self, BehavioralShapeHashError> {
- if value.is_empty() {
- return Err(BehavioralShapeHashError::Empty);
- }
- if value.len() > 64 {
- return Err(BehavioralShapeHashError::TooLong(value.len()));
- }
- if !value.is_ascii() {
- return Err(BehavioralShapeHashError::NonAscii);
- }
+ pub fn parse(value: &str) -> Result<Self, ShapeHashError> {
+ validate_shape_hash(value)?;
Ok(Self(value.into()))
}
@@ -37,82 +47,133 @@ impl BehavioralShapeHash {
}
}
-impl fmt::Display for BehavioralShapeHash {
+/// The persisted person-property filter-shape fingerprint, the person-run counterpart of
+/// [`BehavioralShapeHash`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct PersonShapeHash(Box<str>);
+
+impl PersonShapeHash {
+ pub fn parse(value: &str) -> Result<Self, ShapeHashError> {
+ validate_shape_hash(value)?;
+ Ok(Self(value.into()))
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum ShapeHashError {
+ #[error("shape hash must not be empty")]
+ Empty,
+ #[error("shape hash must be at most 64 bytes, got {0}")]
+ TooLong(usize),
+ #[error("shape hash must contain only ASCII characters")]
+ NonAscii,
+}
+
+/// Which definition fingerprint a reconcile is fenced by. Also the run kind it belongs to, so it
+/// doubles as the queue-supersession key and a `&'static str` metric label.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum ScopeKind {
+ Behavioral,
+ PersonProperty,
+}
+
+impl ScopeKind {
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Behavioral => "behavioral",
+ Self::PersonProperty => "person_property",
+ }
+ }
+}
+
+impl fmt::Display for ScopeKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
-impl FromStr for BehavioralShapeHash {
- type Err = BehavioralShapeHashError;
+impl FromStr for ScopeKind {
+ type Err = UnknownScopeKind;
fn from_str(value: &str) -> Result<Self, Self::Err> {
- Self::parse(value)
+ match value {
+ "behavioral" => Ok(Self::Behavioral),
+ "person_property" => Ok(Self::PersonProperty),
+ other => Err(UnknownScopeKind(other.to_string())),
+ }
}
}
-impl Serialize for BehavioralShapeHash {
- fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- serializer.serialize_str(self.as_str())
- }
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("unknown scope kind {0:?}")]
+pub struct UnknownScopeKind(pub String);
+
+/// Which definition fingerprint fences a reconcile from edits. On the wire the hash rides the
+/// original `filters_hash` field and the variant rides the top-level `kind`: a behavioral tile
+/// keeps the pre-person `"reconcile"` bytes, a person tile is `"reconcile_person"`. Riding the
+/// kind rather than a body field is what protects a mixed-deploy fleet: a consumer predating the
+/// split routes a person tile to `UnknownKind` and skip-commits it before the tile can reach its
+/// reconcile queue — where, parsed as behavioral, it would evict a queued behavioral job for the
+/// same cohort and leave that run permanently short a marker.
+///
+/// The skip is still a loss: the person run settles as a shortfall an operator re-dispatches after
+/// the fleet upgrade, so every consumer must carry this decode before any producer emits a person
+/// tile.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ReconcileScope {
+ Behavioral(BehavioralShapeHash),
+ PersonProperty(PersonShapeHash),
}
-impl<'de> Deserialize<'de> for BehavioralShapeHash {
- fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
- let value = String::deserialize(deserializer)?;
- Self::parse(&value).map_err(|_| {
- DeError::invalid_value(
- Unexpected::Str(&value),
- &"a non-empty ASCII behavioral shape hash of at most 64 bytes",
- )
+impl ReconcileScope {
+ pub fn parse(kind: ScopeKind, hash: &str) -> Result<Self, ShapeHashError> {
+ Ok(match kind {
+ ScopeKind::Behavioral => Self::Behavioral(BehavioralShapeHash::parse(hash)?),
+ ScopeKind::PersonProperty => Self::PersonProperty(PersonShapeHash::parse(hash)?),
})
}
-}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
-pub enum BehavioralShapeHashError {
- #[error("behavioral shape hash must not be empty")]
- Empty,
- #[error("behavioral shape hash must be at most 64 bytes, got {0}")]
- TooLong(usize),
- #[error("behavioral shape hash must contain only ASCII characters")]
- NonAscii,
+ pub const fn kind(&self) -> ScopeKind {
+ match self {
+ Self::Behavioral(_) => ScopeKind::Behavioral,
+ Self::PersonProperty(_) => ScopeKind::PersonProperty,
+ }
+ }
+
+ pub fn hash_str(&self) -> &str {
+ match self {
+ Self::Behavioral(hash) => hash.as_str(),
+ Self::PersonProperty(hash) => hash.as_str(),
+ }
+ }
}
-/// A control tile that requests one partition's full current snapshot for one behavioral cohort.
-/// Field order is the wire order.
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+/// A control tile that requests one partition's full current snapshot for one cohort, fenced by the
+/// dispatching run's [`ReconcileScope`].
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+#[serde(try_from = "ReconcileTileWire")]
pub struct ReconcileTile {
- #[serde(deserialize_with = "deserialize_schema_version")]
- schema_version: u32,
- kind: ReconcileKind,
- #[serde(
- serialize_with = "serialize_team_id",
- deserialize_with = "deserialize_team_id"
- )]
team_id: TeamId,
- #[serde(
- serialize_with = "serialize_cohort_id",
- deserialize_with = "deserialize_cohort_id"
- )]
cohort_id: CohortId,
- filters_hash: BehavioralShapeHash,
+ scope: ReconcileScope,
run_id: RunId,
}
impl ReconcileTile {
- pub fn new(
+ pub const fn new(
team_id: TeamId,
cohort_id: CohortId,
- filters_hash: BehavioralShapeHash,
+ scope: ReconcileScope,
run_id: RunId,
) -> Self {
Self {
- schema_version: RECONCILE_SCHEMA_VERSION,
- kind: ReconcileKind,
team_id,
cohort_id,
- filters_hash,
+ scope,
run_id,
}
}
@@ -125,8 +186,8 @@ impl ReconcileTile {
self.cohort_id
}
- pub fn filters_hash(&self) -> &BehavioralShapeHash {
- &self.filters_hash
+ pub const fn scope(&self) -> &ReconcileScope {
+ &self.scope
}
pub const fn run_id(&self) -> RunId {
@@ -134,43 +195,104 @@ impl ReconcileTile {
}
}
-/// A zero-sized discriminant proven to be [`RECONCILE_KIND`] during deserialization.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-struct ReconcileKind;
+/// The wire projection. Field order here is the wire order; the scope's kind picks the top-level
+/// `kind` string, so a behavioral tile's bytes stay identical to the pre-person contract.
+#[derive(Serialize)]
+struct ReconcileTileOut<'a> {
+ schema_version: u32,
+ kind: &'static str,
+ team_id: i32,
+ cohort_id: i32,
+ filters_hash: &'a str,
+ run_id: RunId,
+}
-impl Serialize for ReconcileKind {
+impl Serialize for ReconcileTile {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- serializer.serialize_str(RECONCILE_KIND)
+ ReconcileTileOut {
+ schema_version: RECONCILE_SCHEMA_VERSION,
+ kind: match self.scope.kind() {
+ ScopeKind::Behavioral => RECONCILE_KIND,
+ ScopeKind::PersonProperty => RECONCILE_PERSON_KIND,
+ },
+ team_id: self.team_id.0,
+ cohort_id: self.cohort_id.0,
+ filters_hash: self.scope.hash_str(),
+ run_id: self.run_id,
+ }
+ .serialize(serializer)
}
}
-impl<'de> Deserialize<'de> for ReconcileKind {
- fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
- let value = String::deserialize(deserializer)?;
- if value != RECONCILE_KIND {
- return Err(DeError::invalid_value(
- Unexpected::Str(&value),
- &"seed kind \"reconcile\"",
- ));
- }
- Ok(Self)
- }
+/// The raw wire fields, funneled through [`TryFrom`] so an unparseable hash or an unrecognized kind
+/// fails the decode rather than half-building a tile.
+#[derive(Deserialize)]
+struct ReconcileTileWire {
+ #[serde(deserialize_with = "deserialize_schema_version")]
+ #[allow(dead_code)] // Validated by its deserializer, never read.
+ schema_version: u32,
+ kind: ReconcileKind,
+ team_id: i32,
+ cohort_id: i32,
+ filters_hash: String,
+ run_id: RunId,
}
-fn serialize_team_id<S: Serializer>(value: &TeamId, serializer: S) -> Result<S::Ok, S::Error> {
- serializer.serialize_i32(value.0)
+impl TryFrom<ReconcileTileWire> for ReconcileTile {
+ type Error = ReconcileTileError;
+
+ fn try_from(wire: ReconcileTileWire) -> Result<Self, Self::Error> {
+ let kind = wire.kind.scope_kind();
+ let scope = ReconcileScope::parse(kind, &wire.filters_hash).map_err(|source| {
+ ReconcileTileError {
+ kind,
+ hash: wire.filters_hash.clone(),
+ source,
+ }
+ })?;
+ Ok(Self::new(
+ TeamId(wire.team_id),
+ CohortId(wire.cohort_id),
+ scope,
+ wire.run_id,
+ ))
+ }
}
-fn deserialize_team_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TeamId, D::Error> {
- i32::deserialize(deserializer).map(TeamId)
+/// Serde stringifies a `try_from` error, so the offending value and reason have to ride the message
+/// — a decode failure is skip-and-count, and this line is the only forensics an operator gets.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("malformed {kind} shape hash {hash:?}: {source}")]
+pub struct ReconcileTileError {
+ kind: ScopeKind,
+ hash: String,
+ #[source]
+ source: ShapeHashError,
}
-fn serialize_cohort_id<S: Serializer>(value: &CohortId, serializer: S) -> Result<S::Ok, S::Error> {
- serializer.serialize_i32(value.0)
+/// The wire `kind` discriminant, proven to be [`RECONCILE_KIND`] or [`RECONCILE_PERSON_KIND`]
+/// during deserialization.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct ReconcileKind(ScopeKind);
+
+impl ReconcileKind {
+ const fn scope_kind(self) -> ScopeKind {
+ self.0
+ }
}
-fn deserialize_cohort_id<'de, D: Deserializer<'de>>(deserializer: D) -> Result<CohortId, D::Error> {
- i32::deserialize(deserializer).map(CohortId)
+impl<'de> Deserialize<'de> for ReconcileKind {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let value = String::deserialize(deserializer)?;
+ match value.as_str() {
+ RECONCILE_KIND => Ok(Self(ScopeKind::Behavioral)),
+ RECONCILE_PERSON_KIND => Ok(Self(ScopeKind::PersonProperty)),
+ _ => Err(DeError::invalid_value(
+ Unexpected::Str(&value),
+ &"seed kind \"reconcile\" or \"reconcile_person\"",
+ )),
+ }
+ }
}
fn deserialize_schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
@@ -281,10 +403,14 @@ mod tests {
const SHA256: &str = "9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de";
fn tile() -> ReconcileTile {
+ scoped_tile(ScopeKind::Behavioral)
+ }
+
+ fn scoped_tile(kind: ScopeKind) -> ReconcileTile {
ReconcileTile::new(
TeamId(2),
CohortId(42),
- BehavioralShapeHash::parse(SHA256).unwrap(),
+ ReconcileScope::parse(kind, SHA256).unwrap(),
RunId(Uuid::nil()),
)
}
@@ -342,6 +468,50 @@ mod tests {
}
}
+ #[test]
+ fn a_person_tile_rides_its_own_kind_and_legacy_bytes_stay_behavioral() {
+ // The distinct kind is what routes a person tile to `UnknownKind` on a consumer predating
+ // the split, instead of parsing as behavioral and evicting a queued behavioral job.
+ let person = scoped_tile(ScopeKind::PersonProperty);
+ assert_eq!(
+ serde_json::to_string(&person).unwrap(),
+ r#"{"schema_version":1,"kind":"reconcile_person","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000"}"#
+ );
+ assert_eq!(
+ serde_json::from_str::<ReconcileTile>(&serde_json::to_string(&person).unwrap())
+ .unwrap(),
+ person,
+ );
+
+ // Bytes a pre-person seeder produced decode as the behavioral scope.
+ assert_eq!(
+ serde_json::from_value::<ReconcileTile>(serde_json::to_value(tile()).unwrap()).unwrap(),
+ tile(),
+ );
+ }
+
+ #[test]
+ fn a_decode_failure_names_the_kind_and_the_offending_hash() {
+ let mut broken = serde_json::to_value(scoped_tile(ScopeKind::PersonProperty)).unwrap();
+ broken["filters_hash"] = serde_json::json!("non-ascii-é");
+ let error = serde_json::from_value::<ReconcileTile>(broken)
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("person_property"), "{error}");
+ assert!(error.contains("non-ascii-é"), "{error}");
+ assert!(error.contains("ASCII"), "{error}");
+ }
+
+ #[test]
+ fn the_scope_kind_token_round_trips() {
+ // The same string is the persisted `backfill_kind` value, the queue-supersession key, and
+ // a metric label.
+ for kind in [ScopeKind::Behavioral, ScopeKind::PersonProperty] {
+ assert_eq!(kind.as_str().parse::<ScopeKind>().unwrap(), kind);
+ }
+ assert!("person".parse::<ScopeKind>().is_err());
+ }
+
#[test]
fn reconcile_complete_marker_has_the_exact_wire_contract() {
let marker = ReconcileCompleteMarker::new(
@@ -382,20 +552,27 @@ mod tests {
}
#[test]
- fn behavioral_shape_hash_matches_the_persisted_output_bounds() {
- assert_eq!(BehavioralShapeHash::parse(SHA256).unwrap().as_str(), SHA256,);
- assert_eq!(BehavioralShapeHash::parse("a").unwrap().as_str(), "a",);
- assert_eq!(
- BehavioralShapeHash::parse(""),
- Err(BehavioralShapeHashError::Empty),
- );
- assert_eq!(
- BehavioralShapeHash::parse(&"x".repeat(65)),
- Err(BehavioralShapeHashError::TooLong(65)),
- );
- assert_eq!(
- BehavioralShapeHash::parse("é"),
- Err(BehavioralShapeHashError::NonAscii),
+ fn both_shape_hashes_match_the_persisted_column_bounds() {
+ for kind in [ScopeKind::Behavioral, ScopeKind::PersonProperty] {
+ let parse = |value: &str| ReconcileScope::parse(kind, value);
+ assert_eq!(parse(SHA256).unwrap().hash_str(), SHA256, "{kind}");
+ assert_eq!(parse("a").unwrap().hash_str(), "a", "{kind}");
+ assert_eq!(parse("").unwrap_err(), ShapeHashError::Empty, "{kind}");
+ assert_eq!(
+ parse(&"x".repeat(65)).unwrap_err(),
+ ShapeHashError::TooLong(65),
+ "{kind}",
+ );
+ assert_eq!(parse("é").unwrap_err(), ShapeHashError::NonAscii, "{kind}");
+ }
+ }
+
+ #[test]
+ fn scopes_of_different_kinds_never_compare_equal() {
+ assert_ne!(
+ *scoped_tile(ScopeKind::Behavioral).scope(),
+ *scoped_tile(ScopeKind::PersonProperty).scope(),
+ "the same hash under two kinds is two different fences",
);
}
}
diff --git a/rust/cohort-seeder/src/app/completion.rs b/rust/cohort-seeder/src/app/completion.rs
index 4ad6a9acef56..cc32cb46f63b 100644
--- a/rust/cohort-seeder/src/app/completion.rs
+++ b/rust/cohort-seeder/src/app/completion.rs
@@ -1,9 +1,12 @@
//! App layer: the automatic reconcile-dispatch driver, dark by default. Ticked from the orchestrator
-//! poll arm after `fill_claim_slots`, it discovers seeding/reconciling behavioral runs, transitions a
-//! fully-confirmed run `seeding → reconciling`, produces the reconcile control tiles, and persists the
-//! dispatch record (produce HWMs + marker-watch start positions + fence epoch) through the same store
-//! path the CLI uses. Its second, independently gated half publishes the marker-watch directives and
-//! runs the per-run observation pass; either half alone is a valid configuration.
+//! poll arm after `fill_claim_slots`, it discovers the seeding and not-yet-observed reconciling runs
+//! of the configured kinds (an observed run's remaining work belongs to Django's finalizer, so it
+//! leaves the working set and survives only in the reconciling-run gauge, counted separately),
+//! transitions a fully-confirmed run `seeding → reconciling`, produces the reconcile control tiles,
+//! and persists the dispatch record (produce HWMs + marker-watch start positions + fence epoch)
+//! through the same store path the CLI uses. Its second, independently gated half publishes the
+//! marker-watch directives and runs the per-run observation pass; either half alone is a valid
+//! configuration.
//!
//! Dispatch runs in a spawned task, never inline: producing `cohorts × COHORT_PARTITION_COUNT` control
//! tiles and awaiting their delivery acks can exceed the orchestrator's liveness deadline. An
@@ -45,11 +48,11 @@ use crate::observability::metrics::{
RECONCILE_ZERO_MARKER_RUNS, RUNS_OBSERVED, RUNS_RECONCILING,
};
use crate::store::completion::{
- cas_run_reconciling, confirm_reconciling, discover_completions,
+ cas_run_reconciling, confirm_reconciling, count_reconciling_by_kind, discover_completions,
mark_run_observed_unreconcilable, runs_with_all_chunks_confirmed, CompletionStoreError,
DiscoveredCompletion, ObservationParticipation, ReconcilingClaim,
};
-use crate::store::runs::ReconcileRunError;
+use crate::store::runs::{ReconcileRunError, RunKind};
use super::observe::{
observe_run, CommittedOffsetSource, ObservationStore, ObserveError, ObserveStep, ObserveTarget,
@@ -179,6 +182,9 @@ struct ObserveArm {
pub struct CompletionDriver {
pool: PgPool,
allowlist: TeamAllowlist,
+ /// The backfill kinds discovery binds. `[Behavioral]` unless the person seed path is on, which
+ /// keeps a person run invisible to this protocol while its gate is off.
+ kinds: &'static [RunKind],
dispatch: Option<DispatchArm>,
observe: Option<ObserveArm>,
in_flight: Arc<Mutex<HashSet<RunId>>>,
@@ -190,10 +196,11 @@ pub struct CompletionDriver {
impl CompletionDriver {
/// Base driver with neither half armed. `main` adds the halves the config enables.
- pub fn new(pool: PgPool, allowlist: TeamAllowlist) -> Self {
+ pub fn new(pool: PgPool, allowlist: TeamAllowlist, kinds: &'static [RunKind]) -> Self {
Self {
pool,
allowlist,
+ kinds,
dispatch: None,
observe: None,
in_flight: Arc::new(Mutex::new(HashSet::new())),
@@ -242,7 +249,7 @@ impl CompletionDriver {
/// and observe the reconciling ones (observe arm). A discovery failure is logged and retried next
/// tick; the dark path (driver absent) costs zero queries.
pub async fn tick(&self) {
- let discovered = match discover_completions(&self.pool, &self.allowlist).await {
+ let discovered = match discover_completions(&self.pool, &self.allowlist, self.kinds).await {
Ok(discovered) => discovered,
Err(error) => {
warn!(error = %error, "completion discovery failed");
@@ -251,10 +258,21 @@ impl CompletionDriver {
};
let now = Utc::now();
- let mut reconciling = 0_u64;
+ // Per kind, not summed: "person runs are piling up undispatched" is the failure this protocol
+ // exists to prevent, and it is invisible against behavioral traffic. Counted separately from
+ // discovery because discovery deliberately drops observed runs, and a backlog parked behind
+ // Django's readiness gate is made entirely of those.
+ let reconciling =
+ match count_reconciling_by_kind(&self.pool, &self.allowlist, self.kinds).await {
+ Ok(counts) => Some(counts),
+ Err(error) => {
+ warn!(error = %error, "counting reconciling runs failed");
+ None
+ }
+ };
let mut oldest_stalled: Option<DateTime<Utc>> = None;
let mut directives = Vec::new();
- let mut undispatched = HashSet::new();
+ let mut undispatched: HashMap<RunId, RunKind> = HashMap::new();
// Collected across the loop and resolved with one batched chunk-ledger read below, so the
// pass never issues a query per planned run.
let mut planned = Vec::new();
@@ -268,17 +286,21 @@ impl CompletionDriver {
for completion in discovered {
match &completion.phase {
CompletionPhase::Observed => {
- reconciling += 1;
+ // Discovery filters these out — the run's remaining work is Django's. The arm
+ // stays because the classifier still names the state.
}
CompletionPhase::Reconciling(dispatched) => {
- reconciling += 1;
// Age from the dispatch, not the run's creation: a run that legitimately spent
// days seeding would otherwise read as stalled-by-days the instant it dispatches.
track_oldest(&mut oldest_stalled, dispatched.epoch.as_datetime());
if let (Some(observe), Some(broker)) = (&self.observe, &broker) {
let started = Instant::now();
// One read per run per tick, shared by the watch directive and the pass.
- match observe.store.load_participations(completion.run_id).await {
+ match observe
+ .store
+ .load_participations(completion.run_id, completion.kind)
+ .await
+ {
Ok(participations) => {
directives.push(build_directive(
&completion,
@@ -305,8 +327,7 @@ impl CompletionDriver {
}
}
CompletionPhase::ReconcilingUndispatched(reason) => {
- reconciling += 1;
- undispatched.insert(completion.run_id);
+ undispatched.insert(completion.run_id, completion.kind);
// A run holds this phase until a re-dispatch records — across a whole
// observe-only rollout window, if auto-dispatch is off. Count and warn once per
// stretch so the signal measures broken dispatch records rather than how many
@@ -334,7 +355,11 @@ impl CompletionDriver {
"reconciling run has no usable dispatch record; re-dispatching"
);
}
- self.spawn_dispatch(completion.run_id, DispatchKind::ReDispatch);
+ self.spawn_dispatch(
+ completion.run_id,
+ completion.kind,
+ DispatchKind::ReDispatch,
+ );
} else if first_sighting {
warn!(
run_id = ?completion.run_id,
@@ -346,7 +371,7 @@ impl CompletionDriver {
CompletionPhase::SeedingPlanned => {
// Only the dispatch arm consumes these, so observe-only skips the batch read.
if self.dispatch.is_some() {
- planned.push(completion.run_id);
+ planned.push((completion.run_id, completion.kind));
}
}
CompletionPhase::SeedingUnplanned => {}
@@ -361,16 +386,39 @@ impl CompletionDriver {
// Forget runs that have left the phase, so a later relapse counts as a fresh event.
lock_recoverable(&self.reported_undispatched)
- .retain(|run_id, _| undispatched.contains(run_id));
+ .retain(|run_id, _| undispatched.contains_key(run_id));
- gauge!(RUNS_RECONCILING).set(reconciling as f64);
+ // Publish every discovered kind each tick, including the zeroes: a labelled gauge that is
+ // only set when non-empty keeps its last reading forever once that kind drains.
+ let mut undispatched_by_kind: HashMap<RunKind, u64> = HashMap::new();
+ for kind in self.kinds {
+ undispatched_by_kind.entry(*kind).or_default();
+ }
+ for kind in undispatched.values() {
+ *undispatched_by_kind.entry(*kind).or_default() += 1;
+ }
+ // Left at its previous reading when the count failed: zeroing it would read as "the backlog
+ // drained" rather than "we could not tell".
+ if let Some(mut reconciling) = reconciling {
+ for kind in self.kinds {
+ reconciling.entry(*kind).or_default();
+ }
+ for (kind, count) in &reconciling {
+ gauge!(RUNS_RECONCILING, "kind" => kind.as_str()).set(*count as f64);
+ }
+ }
// A standing count: the first-sighting counter goes flat while runs stay stranded.
- gauge!(RECONCILE_RUNS_UNDISPATCHED).set(undispatched.len() as f64);
+ for (kind, count) in &undispatched_by_kind {
+ gauge!(RECONCILE_RUNS_UNDISPATCHED, "kind" => kind.as_str()).set(*count as f64);
+ }
- match runs_with_all_chunks_confirmed(&self.pool, &planned).await {
+ let planned_ids: Vec<RunId> = planned.iter().map(|(run_id, _)| *run_id).collect();
+ match runs_with_all_chunks_confirmed(&self.pool, &planned_ids).await {
Ok(confirmed) => {
- for run_id in confirmed {
- self.spawn_dispatch(run_id, DispatchKind::Fresh);
+ for (run_id, kind) in planned {
+ if confirmed.contains(&run_id) {
+ self.spawn_dispatch(run_id, kind, DispatchKind::Fresh);
+ }
}
}
Err(error) => {
@@ -409,6 +457,7 @@ impl CompletionDriver {
let target = ObserveTarget {
run_id: completion.run_id,
team_id: completion.team_id,
+ kind: completion.kind,
epoch: dispatched.epoch,
hwms: dispatched.hwms.clone(),
watch: dispatched.watch.clone(),
@@ -426,17 +475,18 @@ impl CompletionDriver {
if summary.completed + summary.partial + summary.shortfall > 0
|| summary.zero_markers
{
- counter!(RUNS_OBSERVED).increment(1);
+ counter!(RUNS_OBSERVED, "kind" => target.kind.as_str()).increment(1);
}
if summary.zero_markers {
// A counter, not a gauge: a settled run is `Observed` on the next tick, so a
// fleet-wide gate-off would be a single-tick blip most scrapes would miss.
- counter!(RECONCILE_ZERO_MARKER_RUNS).increment(1);
+ counter!(RECONCILE_ZERO_MARKER_RUNS, "kind" => target.kind.as_str())
+ .increment(1);
}
ObserveOutcome::default()
}
Ok(ObserveStep::ObservedAllComplete) => {
- counter!(RUNS_OBSERVED).increment(1);
+ counter!(RUNS_OBSERVED, "kind" => target.kind.as_str()).increment(1);
ObserveOutcome::default()
}
Ok(ObserveStep::LivenessLagging(partitions)) => ObserveOutcome {
@@ -472,7 +522,7 @@ impl CompletionDriver {
/// Spawns a dispatch task unless the dispatch arm is disarmed, one is already in flight for this
/// run on this replica, or the arm is at its concurrency budget. A run that misses the budget
/// keeps its phase and is picked up on a later tick.
- fn spawn_dispatch(&self, run_id: RunId, kind: DispatchKind) {
+ fn spawn_dispatch(&self, run_id: RunId, run_kind: RunKind, kind: DispatchKind) {
let Some(dispatch) = &self.dispatch else {
return;
};
@@ -487,14 +537,15 @@ impl CompletionDriver {
let dispatch = tokio::spawn(async move {
let _permit = permit;
let _guard = guard;
- run_dispatch(&context, run_id, kind).await;
+ run_dispatch(&context, run_id, run_kind, kind).await;
});
// `run_dispatch` reports its own failures, so a `JoinError` is a panic. Dropping the handle
// would make a deterministic one — a poison row, say — an invisible per-tick respawn loop.
tokio::spawn(async move {
if let Err(error) = dispatch.await {
- counter!(RECONCILE_DISPATCHES, "outcome" => "panicked").increment(1);
- warn!(error = %error, run_id = ?run_id, "reconcile dispatch task panicked");
+ counter!(RECONCILE_DISPATCHES, "outcome" => "panicked", "kind" => run_kind.as_str())
+ .increment(1);
+ warn!(error = %error, run_id = ?run_id, kind = run_kind.as_str(), "reconcile dispatch task panicked");
}
});
}
@@ -616,12 +667,16 @@ fn lock_recoverable<T>(value: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
/// produce/record failure leaves the run `reconciling` with no record, which the next tick sees as
/// `ReconcilingUndispatched` and re-dispatches. On shutdown mid-dispatch the same recovery converges
/// per the crash-recovery matrix.
-async fn run_dispatch(context: &DispatchArm, run_id: RunId, kind: DispatchKind) {
- let claim = match acquire_claim(context, run_id, kind).await {
+async fn run_dispatch(context: &DispatchArm, run_id: RunId, run_kind: RunKind, kind: DispatchKind) {
+ // Person and behavioral dispatch share every counter here, and a person-side spike summed
+ // against behavioral traffic is invisible.
+ let run_kind_label = run_kind.as_str();
+ let claim = match acquire_claim(context, run_id, run_kind, kind).await {
Ok(Some(claim)) => claim,
Ok(None) => {
- counter!(RECONCILE_CAS_LOST).increment(1);
- counter!(RECONCILE_DISPATCHES, "outcome" => "cas_lost").increment(1);
+ counter!(RECONCILE_CAS_LOST, "kind" => run_kind_label).increment(1);
+ counter!(RECONCILE_DISPATCHES, "outcome" => "cas_lost", "kind" => run_kind_label)
+ .increment(1);
return;
}
Err(error) => {
@@ -641,7 +696,12 @@ async fn run_dispatch(context: &DispatchArm, run_id: RunId, kind: DispatchKind)
Ok(PreparedDispatch::Certified(certified)) => certified,
Ok(PreparedDispatch::Uncertified(_)) => {
warn!(run_id = ?run_id, "dispatch was not certified under Complete; leaving reconciling");
- counter!(RECONCILE_DISPATCHES, "outcome" => "prepare_failed").increment(1);
+ counter!(
+ RECONCILE_DISPATCHES,
+ "outcome" => "prepare_failed",
+ "kind" => run_kind_label,
+ )
+ .increment(1);
return;
}
Err(PrepareReconcileDispatchError::Run(ReconcileRunError::NoActiveParticipations(_))) => {
@@ -650,10 +710,17 @@ async fn run_dispatch(context: &DispatchArm, run_id: RunId, kind: DispatchKind)
// finalizer only discovers runs carrying `reconcile_observed_at`, and without it the
// run would classify as `ReconcilingUndispatched` and re-spawn this no-op forever.
warn!(run_id = ?run_id, "no active participations; marking observed for Django to terminalize");
- if let Err(error) = mark_run_observed_unreconcilable(&context.pool, run_id).await {
+ if let Err(error) =
+ mark_run_observed_unreconcilable(&context.pool, run_id, run_kind).await
+ {
warn!(error = %error, run_id = ?run_id, "marking an unreconcilable run observed failed");
}
- counter!(RECONCILE_DISPATCHES, "outcome" => "no_participations").increment(1);
+ counter!(
+ RECONCILE_DISPATCHES,
+ "outcome" => "no_participations",
+ "kind" => run_kind_label,
+ )
+ .increment(1);
return;
}
Err(PrepareReconcileDispatchError::Incomplete {
@@ -667,12 +734,18 @@ async fn run_dispatch(context: &DispatchArm, run_id: RunId, kind: DispatchKind)
if let Err(error) = claim.revert(&context.pool).await {
warn!(error = %error, run_id = ?run_id, "reverting the reconciling CAS failed");
}
- counter!(RECONCILE_DISPATCHES, "outcome" => "revert").increment(1);
+ counter!(RECONCILE_DISPATCHES, "outcome" => "revert", "kind" => run_kind_label)
+ .increment(1);
return;
}
Err(error) => {
warn!(error = %error, run_id = ?run_id, "preparing reconcile dispatch failed; leaving reconciling");
- counter!(RECONCILE_DISPATCHES, "outcome" => "prepare_failed").increment(1);
+ counter!(
+ RECONCILE_DISPATCHES,
+ "outcome" => "prepare_failed",
+ "kind" => run_kind_label,
+ )
+ .increment(1);
return;
}
};
@@ -689,24 +762,29 @@ async fn run_dispatch(context: &DispatchArm, run_id: RunId, kind: DispatchKind)
.await
{
Ok(_) => {
- counter!(RECONCILE_DISPATCHES, "outcome" => "dispatched").increment(1);
+ counter!(RECONCILE_DISPATCHES, "outcome" => "dispatched", "kind" => run_kind_label)
+ .increment(1);
}
Err(error) => {
let outcome = error.outcome();
warn!(error = %error, run_id = ?run_id, "reconcile dispatch failed; leaving reconciling for re-dispatch");
- counter!(RECONCILE_DISPATCHES, "outcome" => outcome).increment(1);
+ counter!(RECONCILE_DISPATCHES, "outcome" => outcome, "kind" => run_kind_label)
+ .increment(1);
}
}
}
+/// Both claims bind `run_kind`, so a claim is also the proof that the run row still holds the kind
+/// discovery reported — everything downstream inherits it without re-checking.
async fn acquire_claim(
context: &DispatchArm,
run_id: RunId,
+ run_kind: RunKind,
kind: DispatchKind,
) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {
match kind {
- DispatchKind::Fresh => cas_run_reconciling(&context.pool, run_id).await,
- DispatchKind::ReDispatch => confirm_reconciling(&context.pool, run_id).await,
+ DispatchKind::Fresh => cas_run_reconciling(&context.pool, run_id, run_kind).await,
+ DispatchKind::ReDispatch => confirm_reconciling(&context.pool, run_id, run_kind).await,
}
}
diff --git a/rust/cohort-seeder/src/app/observe.rs b/rust/cohort-seeder/src/app/observe.rs
index 0d28e6ed8749..f4a638f7bcf9 100644
--- a/rust/cohort-seeder/src/app/observe.rs
+++ b/rust/cohort-seeder/src/app/observe.rs
@@ -26,8 +26,8 @@ use sqlx::PgPool;
use tracing::warn;
use crate::domain::{
- BehavioralShapeHash, DispatchEpoch, LivenessCheck, MarkerLedger, MarkerWatch, ObservationEnds,
- PartitionBitmap, ReconcileHwms, RunId, SeedGroupCommits, SettledVerdict,
+ DispatchEpoch, LivenessCheck, MarkerLedger, MarkerWatch, ObservationEnds, PartitionBitmap,
+ ReconcileHwms, ReconcileScope, RunId, SeedGroupCommits, SettledVerdict,
};
use crate::kafka::committed::SeedGroupOffsetReader;
use crate::kafka::producer::SeedTileProducer;
@@ -35,11 +35,12 @@ use crate::observability::metrics::{
RECONCILE_COHORTS_COMPLETED, RECONCILE_COHORTS_PARTIAL, RECONCILE_COHORTS_SHORTFALL,
};
use crate::store::completion::{
- load_current_behavioral_hashes, load_observation_participations, mark_participation_completed,
+ load_current_shape_hashes, load_observation_participations, mark_participation_completed,
mark_run_observed, persist_observation_ends, record_participation_partial,
- record_participation_shortfall, CompletionStoreError, CurrentBehavioralHash,
+ record_participation_shortfall, CompletionStoreError, CurrentShapeHash,
ObservationParticipation,
};
+use crate::store::runs::RunKind;
use crate::store::{render_error_chain, RenderedError};
/// The dispatch record the observer needs, lifted from a `Reconciling(DispatchedReconcile)` phase.
@@ -47,6 +48,8 @@ use crate::store::{render_error_chain, RenderedError};
pub struct ObserveTarget {
pub run_id: RunId,
pub team_id: TeamId,
+ /// Selects which shape-hash column the pass reads on both sides of the attribution compare.
+ pub kind: RunKind,
pub epoch: DispatchEpoch,
pub hwms: ReconcileHwms,
pub watch: MarkerWatch,
@@ -107,7 +110,8 @@ pub async fn observe_run(
.await?;
}
store.mark_observed(target.run_id, target.epoch).await?;
- counter!(RECONCILE_COHORTS_COMPLETED).increment(active.len() as u64);
+ counter!(RECONCILE_COHORTS_COMPLETED, "kind" => target.kind.as_str())
+ .increment(active.len() as u64);
return Ok(ObserveStep::ObservedAllComplete);
}
@@ -168,7 +172,8 @@ async fn apply_verdict(
.mark_completed(target.run_id, target.epoch, participation.cohort_id)
.await?;
}
- counter!(RECONCILE_COHORTS_COMPLETED).increment(active.len() as u64);
+ counter!(RECONCILE_COHORTS_COMPLETED, "kind" => target.kind.as_str())
+ .increment(active.len() as u64);
Ok(SettleSummary {
completed: active.len(),
..SettleSummary::default()
@@ -183,7 +188,8 @@ async fn apply_verdict(
.mark_completed(target.run_id, target.epoch, *cohort_id)
.await?;
}
- counter!(RECONCILE_COHORTS_COMPLETED).increment(complete.len() as u64);
+ counter!(RECONCILE_COHORTS_COMPLETED, "kind" => target.kind.as_str())
+ .increment(complete.len() as u64);
let (partial, shortfall) =
attribute_incomplete(store, target, active, &incomplete).await?;
Ok(SettleSummary {
@@ -213,8 +219,9 @@ async fn apply_verdict(
}
}
-/// Split each short cohort into a terminal supersede (hash diverged / cohort deleted / indeterminate)
-/// or a retryable shortfall (hash still matches the pinned one).
+/// Split each short cohort into a terminal supersede (shape diverged / cohort deleted /
+/// indeterminate) or a retryable shortfall (the shape still matches the pinned one). The comparison
+/// is [`ReconcileScope`] equality, so a person run is never satisfied by a behavioral shape.
async fn attribute_incomplete(
store: &dyn ObservationStore,
target: &ObserveTarget,
@@ -223,21 +230,20 @@ async fn attribute_incomplete(
) -> Result<(usize, usize), ObserveError> {
let cohort_ids: Vec<CohortId> = incomplete.iter().map(|(cohort_id, _)| *cohort_id).collect();
let current = store
- .load_current_hashes(target.team_id, &cohort_ids)
+ .load_current_hashes(target.team_id, &cohort_ids, target.kind)
.await?;
- let pinned: HashMap<CohortId, &BehavioralShapeHash> = active
- .iter()
- .map(|p| (p.cohort_id, &p.behavioral_filters_shape_hash))
- .collect();
+ let pinned: HashMap<CohortId, &ReconcileScope> =
+ active.iter().map(|p| (p.cohort_id, &p.scope)).collect();
+ let kind_label = target.kind.as_str();
let mut partial = 0;
let mut shortfall = 0;
for (cohort_id, bitmap) in incomplete {
let missing = render_missing(*bitmap);
let hash_matches = match current.get(cohort_id) {
- Some(CurrentBehavioralHash::Present(current_hash)) => pinned
+ Some(CurrentShapeHash::Present(current_scope)) => pinned
.get(cohort_id)
- .is_some_and(|pinned_hash| *pinned_hash == current_hash),
+ .is_some_and(|pinned_scope| *pinned_scope == current_scope),
// Deleted / Indeterminate / absent row all read as diverged: terminal.
_ => false,
};
@@ -247,7 +253,7 @@ async fn attribute_incomplete(
.record_shortfall(target.run_id, target.epoch, *cohort_id, &error)
.await?;
shortfall += 1;
- counter!(RECONCILE_COHORTS_SHORTFALL).increment(1);
+ counter!(RECONCILE_COHORTS_SHORTFALL, "kind" => kind_label).increment(1);
} else {
let error = RenderedError::from_message(format!(
"reconcile superseded by a cohort change: {missing}"
@@ -256,7 +262,7 @@ async fn attribute_incomplete(
.record_partial(target.run_id, target.epoch, *cohort_id, &error)
.await?;
partial += 1;
- counter!(RECONCILE_COHORTS_PARTIAL).increment(1);
+ counter!(RECONCILE_COHORTS_PARTIAL, "kind" => kind_label).increment(1);
}
}
Ok((partial, shortfall))
@@ -292,12 +298,14 @@ pub trait ObservationStore: Send + Sync {
async fn load_participations(
&self,
run_id: RunId,
+ kind: RunKind,
) -> Result<Vec<ObservationParticipation>, CompletionStoreError>;
async fn load_current_hashes(
&self,
team_id: TeamId,
cohort_ids: &[CohortId],
- ) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError>;
+ kind: RunKind,
+ ) -> Result<HashMap<CohortId, CurrentShapeHash>, CompletionStoreError>;
async fn persist_ends(
&self,
run_id: RunId,
@@ -347,16 +355,18 @@ impl ObservationStore for PgObservationStore {
async fn load_participations(
&self,
run_id: RunId,
+ kind: RunKind,
) -> Result<Vec<ObservationParticipation>, CompletionStoreError> {
- load_observation_participations(&self.pool, run_id).await
+ load_observation_participations(&self.pool, run_id, kind).await
}
async fn load_current_hashes(
&self,
team_id: TeamId,
cohort_ids: &[CohortId],
- ) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError> {
- load_current_behavioral_hashes(&self.pool, team_id, cohort_ids).await
+ kind: RunKind,
+ ) -> Result<HashMap<CohortId, CurrentShapeHash>, CompletionStoreError> {
+ load_current_shape_hashes(&self.pool, team_id, cohort_ids, kind).await
}
async fn persist_ends(
@@ -505,8 +515,8 @@ mod tests {
DispatchEpoch::from_dispatched_at(chrono::Utc.timestamp_opt(1_700_000_000, 0).unwrap())
}
- fn hash(value: &str) -> BehavioralShapeHash {
- BehavioralShapeHash::parse(value).unwrap()
+ fn scope(kind: RunKind, value: &str) -> ReconcileScope {
+ ReconcileScope::parse(kind.scope(), value).unwrap()
}
fn full_hwms() -> ReconcileHwms {
@@ -527,9 +537,17 @@ mod tests {
}
fn participation(cohort: i32, bits: PartitionBitmap) -> ObservationParticipation {
+ scoped_participation(RunKind::Behavioral, cohort, bits)
+ }
+
+ fn scoped_participation(
+ kind: RunKind,
+ cohort: i32,
+ bits: PartitionBitmap,
+ ) -> ObservationParticipation {
ObservationParticipation {
cohort_id: CohortId(cohort),
- behavioral_filters_shape_hash: hash("pinned"),
+ scope: scope(kind, "pinned"),
bits,
reconcile_completed_at: None,
superseded_at: None,
@@ -550,9 +568,14 @@ mod tests {
}
fn target(ends: Option<ObservationEnds>) -> ObserveTarget {
+ scoped_target(RunKind::Behavioral, ends)
+ }
+
+ fn scoped_target(kind: RunKind, ends: Option<ObservationEnds>) -> ObserveTarget {
ObserveTarget {
run_id: run_id(),
team_id: TeamId(2),
+ kind,
epoch: epoch(),
hwms: full_hwms(),
watch: MarkerWatch {
@@ -647,7 +670,7 @@ mod tests {
#[derive(Default)]
struct FakeStore {
participations: Vec<ObservationParticipation>,
- current: HashMap<CohortId, CurrentBehavioralHash>,
+ current: HashMap<CohortId, CurrentShapeHash>,
calls: Mutex<Vec<StoreCall>>,
fence_lost_on_completed: bool,
}
@@ -667,6 +690,7 @@ mod tests {
async fn load_participations(
&self,
_run_id: RunId,
+ _kind: RunKind,
) -> Result<Vec<ObservationParticipation>, CompletionStoreError> {
Ok(self.participations.clone())
}
@@ -675,7 +699,8 @@ mod tests {
&self,
_team_id: TeamId,
cohort_ids: &[CohortId],
- ) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError> {
+ _kind: RunKind,
+ ) -> Result<HashMap<CohortId, CurrentShapeHash>, CompletionStoreError> {
Ok(cohort_ids
.iter()
.filter_map(|cohort_id| {
@@ -875,8 +900,14 @@ mod tests {
participation(11, PartitionBitmap::default()),
],
current: HashMap::from([
- (CohortId(10), CurrentBehavioralHash::Present(hash("pinned"))),
- (CohortId(11), CurrentBehavioralHash::Present(hash("pinned"))),
+ (
+ CohortId(10),
+ CurrentShapeHash::Present(scope(RunKind::Behavioral, "pinned")),
+ ),
+ (
+ CohortId(11),
+ CurrentShapeHash::Present(scope(RunKind::Behavioral, "pinned")),
+ ),
]),
..FakeStore::default()
};
@@ -914,24 +945,28 @@ mod tests {
}
#[tokio::test]
- async fn hash_attribution_splits_diverged_deleted_indeterminate_and_matching() {
+ async fn shape_attribution_splits_diverged_deleted_indeterminate_and_matching() {
+ let kind = RunKind::Behavioral;
let store = FakeStore {
participations: vec![
- participation(10, complete_bits()), // complete
- participation(11, one_short_bits()), // diverged ⇒ partial
- participation(12, one_short_bits()), // matching ⇒ shortfall
- participation(13, one_short_bits()), // deleted ⇒ partial
- participation(14, one_short_bits()), // indeterminate ⇒ partial
- participation(15, one_short_bits()), // absent row ⇒ partial
+ scoped_participation(kind, 10, complete_bits()), // complete
+ scoped_participation(kind, 11, one_short_bits()), // diverged ⇒ partial
+ scoped_participation(kind, 12, one_short_bits()), // matching ⇒ shortfall
+ scoped_participation(kind, 13, one_short_bits()), // deleted ⇒ partial
+ scoped_participation(kind, 14, one_short_bits()), // indeterminate ⇒ partial
+ scoped_participation(kind, 15, one_short_bits()), // absent row ⇒ partial
],
current: HashMap::from([
(
CohortId(11),
- CurrentBehavioralHash::Present(hash("diverged")),
+ CurrentShapeHash::Present(scope(kind, "diverged")),
),
- (CohortId(12), CurrentBehavioralHash::Present(hash("pinned"))),
- (CohortId(13), CurrentBehavioralHash::Deleted),
- (CohortId(14), CurrentBehavioralHash::Indeterminate),
+ (
+ CohortId(12),
+ CurrentShapeHash::Present(scope(kind, "pinned")),
+ ),
+ (CohortId(13), CurrentShapeHash::Deleted),
+ (CohortId(14), CurrentShapeHash::Indeterminate),
]),
..FakeStore::default()
};
@@ -942,7 +977,7 @@ mod tests {
&store,
&committed,
&ends,
- &target(Some(caught_up_ends())),
+ &scoped_target(kind, Some(caught_up_ends())),
&store.participations,
)
.await
@@ -955,7 +990,7 @@ mod tests {
partial: 4,
shortfall: 1,
zero_markers: false,
- })
+ }),
);
let calls = store.calls();
assert_eq!(calls.first(), Some(&StoreCall::Completed(CohortId(10))));
@@ -971,6 +1006,36 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn a_matching_hash_of_the_other_kind_never_saves_a_shortfall_from_supersession() {
+ // The store is kind-scoped, but the compare is the last line of defence: a cohort whose
+ // *other* shape still equals the pinned string must not read as "unchanged".
+ let store = FakeStore {
+ participations: vec![scoped_participation(
+ RunKind::PersonProperty,
+ 10,
+ one_short_bits(),
+ )],
+ current: HashMap::from([(
+ CohortId(10),
+ CurrentShapeHash::Present(scope(RunKind::Behavioral, "pinned")),
+ )]),
+ ..FakeStore::default()
+ };
+
+ observe_run(
+ &store,
+ &FakeCommittedOffsets::default(),
+ &FakeTopicOffsets::default(),
+ &scoped_target(RunKind::PersonProperty, Some(caught_up_ends())),
+ &store.participations,
+ )
+ .await
+ .unwrap();
+
+ assert!(store.calls().contains(&StoreCall::Partial(CohortId(10))));
+ }
+
#[tokio::test]
async fn superseded_participations_are_excluded_and_all_superseded_observes() {
let mut superseded = participation(10, PartitionBitmap::default());
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index ab3f2a2ec6cb..12d86d4e1798 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -172,7 +172,7 @@ impl SeederOrchestrator {
&self.pool,
&self.store,
&self.allowlist,
- self.settings.discovery_kinds(),
+ self.settings.seed_kinds(),
self.settings.plan_caps,
&mut reported_runs,
)
diff --git a/rust/cohort-seeder/src/app/reconcile_dispatch.rs b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
index fd5f954bde92..64318efb361e 100644
--- a/rust/cohort-seeder/src/app/reconcile_dispatch.rs
+++ b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
@@ -62,6 +62,10 @@ impl PreparedReconcileDispatch {
self.run.run_id()
}
+ pub const fn run_kind(&self) -> RunKind {
+ self.run.kind()
+ }
+
pub const fn run_status(&self) -> RunStatus {
self.run.status()
}
@@ -115,6 +119,10 @@ impl PreparedDispatch {
self.inner().run_id()
}
+ pub fn run_kind(&self) -> RunKind {
+ self.inner().run_kind()
+ }
+
pub fn run_status(&self) -> RunStatus {
self.inner().run_status()
}
@@ -132,6 +140,8 @@ impl PreparedDispatch {
}
}
+/// The run's own row decides its kind; every kind-bound read below follows from it, so a caller
+/// never has to name one. [`PreparedDispatch::run_kind`] hands it back for the claim.
pub async fn prepare_reconcile_dispatch(
pool: &PgPool,
run_id: RunId,
@@ -142,7 +152,7 @@ pub async fn prepare_reconcile_dispatch(
let progress = PgChunkStore::new(pool.clone())
.chunk_progress(run_id)
.await?;
- let planning_proven = read_planning_stamp(pool, run_id, RunKind::Behavioral)
+ let planning_proven = read_planning_stamp(pool, run_id, run.kind())
.await?
.is_some();
validate_completion(run_id, progress.remaining(), planning_proven, completion)?;
@@ -568,7 +578,9 @@ mod tests {
ReconcileTile::new(
TeamId(2),
CohortId(cohort_id),
- crate::domain::BehavioralShapeHash::parse("behavioral-shape").unwrap(),
+ crate::domain::ReconcileScope::Behavioral(
+ crate::domain::BehavioralShapeHash::parse("behavioral-shape").unwrap(),
+ ),
RunId(Uuid::nil()),
)
}
diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rs
index 5d055e80f046..3f07ae27e81d 100644
--- a/rust/cohort-seeder/src/app/settings.rs
+++ b/rust/cohort-seeder/src/app/settings.rs
@@ -23,6 +23,10 @@ pub struct PersonSettings {
/// long person scan cannot stall live behavioral seeding.
pub max_concurrent_chunks: NonZeroUsize,
pub emit_nonmatchers: bool,
+ /// Whether completion discovery may surface person runs. Separate from the seed gate so the
+ /// reconcile half can be staged after the processor fleet decodes `reconcile_person` tiles —
+ /// seeding a person run is inert, dispatching its tiles to an old processor is not.
+ pub reconcile_dispatch: bool,
}
impl PersonSettings {
@@ -112,15 +116,25 @@ impl OrchestratorSettings {
self.person.as_ref()
}
- /// The backfill kinds discovery binds. With the person gate off this is `['behavioral']`, so
- /// the running binary's behavior is identical to today's.
- pub(super) fn discovery_kinds(&self) -> &'static [RunKind] {
+ /// The backfill kinds run discovery binds: the person seed path is on or it is not.
+ pub fn seed_kinds(&self) -> &'static [RunKind] {
if self.person.is_some() {
&[RunKind::Behavioral, RunKind::PersonProperty]
} else {
&[RunKind::Behavioral]
}
}
+
+ /// The backfill kinds completion discovery binds. Narrower than [`Self::seed_kinds`] on
+ /// purpose: seeding a person run is inert, dispatching its reconcile tiles to a processor that
+ /// cannot decode them is not, so the reconcile gate stages after the seed gate.
+ pub fn completion_kinds(&self) -> &'static [RunKind] {
+ if self.person.is_some_and(|person| person.reconcile_dispatch) {
+ &[RunKind::Behavioral, RunKind::PersonProperty]
+ } else {
+ &[RunKind::Behavioral]
+ }
+ }
}
impl TryFrom<&Config> for OrchestratorSettings {
@@ -144,6 +158,7 @@ impl TryFrom<&Config> for OrchestratorSettings {
)
.ok_or(OrchestratorSettingsError::ZeroPersonConcurrency)?,
emit_nonmatchers: config.seeder_person_emit_nonmatchers,
+ reconcile_dispatch: config.seeder_person_reconcile_dispatch_enabled,
};
person.validate_scan_budget(config.seeder_ch_max_execution_time_secs)?;
Ok::<_, OrchestratorSettingsError>(person)
@@ -370,21 +385,48 @@ mod tests {
}
}
- /// Dark-by-default: with the gate off discovery binds behavioral only; enabling it validates
- /// the person rates the way `ZeroTileRate` guards the behavioral pacer.
+ /// Dark-by-default: with the gates off discovery binds behavioral only; enabling them validates
+ /// the person rates the way `ZeroTileRate` guards the behavioral pacer. The two gates stage
+ /// separately — seeding a person run is inert, dispatching its tiles to a processor that cannot
+ /// decode the person kind is not, and that run cannot be recovered by flipping the gate back.
#[test]
fn person_settings_are_gated_and_validated() {
let config = Config::init_from_hashmap(&HashMap::new()).unwrap();
let dark = OrchestratorSettings::try_from(&config).unwrap();
assert!(dark.person().is_none());
- assert_eq!(dark.discovery_kinds(), &[RunKind::Behavioral]);
+ assert_eq!(dark.seed_kinds(), &[RunKind::Behavioral]);
+ assert_eq!(dark.completion_kinds(), &[RunKind::Behavioral]);
+
+ // The reconcile gate alone arms nothing: there is no person seed path to reconcile.
+ let mut reconcile_only = config.clone();
+ reconcile_only.seeder_person_reconcile_dispatch_enabled = true;
+ let reconcile_only = OrchestratorSettings::try_from(&reconcile_only).unwrap();
+ assert!(reconcile_only.person().is_none());
+ assert_eq!(reconcile_only.seed_kinds(), &[RunKind::Behavioral]);
+ assert_eq!(reconcile_only.completion_kinds(), &[RunKind::Behavioral]);
let mut enabled = config.clone();
enabled.seeder_person_seeds_enabled = true;
- let lit = OrchestratorSettings::try_from(&enabled).unwrap();
+ // Seeding without dispatch is the staging step: person runs are discovered and seed, then
+ // park in `seeding` because completion discovery still never surfaces them.
+ let seeds_only = OrchestratorSettings::try_from(&enabled).unwrap();
+ assert!(seeds_only.person().is_some());
+ assert_eq!(
+ seeds_only.seed_kinds(),
+ &[RunKind::Behavioral, RunKind::PersonProperty]
+ );
+ assert_eq!(seeds_only.completion_kinds(), &[RunKind::Behavioral]);
+
+ let mut both = enabled.clone();
+ both.seeder_person_reconcile_dispatch_enabled = true;
+ let lit = OrchestratorSettings::try_from(&both).unwrap();
assert!(lit.person().is_some());
assert_eq!(
- lit.discovery_kinds(),
+ lit.seed_kinds(),
+ &[RunKind::Behavioral, RunKind::PersonProperty]
+ );
+ assert_eq!(
+ lit.completion_kinds(),
&[RunKind::Behavioral, RunKind::PersonProperty]
);
diff --git a/rust/cohort-seeder/src/bin/reconcile_dispatch.rs b/rust/cohort-seeder/src/bin/reconcile_dispatch.rs
index 2b10945254fb..a77c4e43ea4c 100644
--- a/rust/cohort-seeder/src/bin/reconcile_dispatch.rs
+++ b/rust/cohort-seeder/src/bin/reconcile_dispatch.rs
@@ -18,7 +18,7 @@ use cohort_seeder::store::chunks::PgChunkStore;
use cohort_seeder::store::completion::{
cas_run_reconciling, confirm_reconciling, ReconcilingClaim,
};
-use cohort_seeder::store::runs::RunStatus;
+use cohort_seeder::store::runs::{RunKind, RunStatus};
use common_database::get_pool_with_config;
use envconfig::Envconfig;
use sqlx::PgPool;
@@ -31,16 +31,17 @@ const PARTITION_VERIFY_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, Parser)]
#[command(
name = "reconcile_dispatch",
- about = "Dispatch partition-targeted reconcile snapshots for one behavioral cohort backfill run",
- long_about = "Dispatch partition-targeted reconcile snapshots for one behavioral cohort \
- backfill run.\n\nThe default invocation is a mutation: on a complete run it \
- transitions the run to reconciling and persists the dispatch record (produce \
- HWMs + marker-watch positions). Re-run with --dry-run first to validate the run \
- and print the plan without touching it. --allow-incomplete produces tiles but \
- never persists."
+ about = "Dispatch partition-targeted reconcile snapshots for one cohort backfill run",
+ long_about = "Dispatch partition-targeted reconcile snapshots for one cohort backfill run. \
+ The run's own row decides which definition fingerprint fences the snapshot, so \
+ behavioral and person-property runs are dispatched the same way.\n\nThe default \
+ invocation is a mutation: on a complete run it transitions the run to \
+ reconciling and persists the dispatch record (produce HWMs + marker-watch \
+ positions). Re-run with --dry-run first to validate the run and print the plan \
+ without touching it. --allow-incomplete produces tiles but never persists."
)]
struct Args {
- /// Behavioral cohort backfill run UUID.
+ /// Cohort backfill run UUID.
run_id: Uuid,
/// Validate the run and print what would be dispatched, without claiming it or producing tiles.
@@ -86,9 +87,10 @@ async fn async_main(args: Args, config: Config) -> Result<()> {
.context("validating reconcile dispatch")?;
if args.dry_run {
println!(
- "dry run: run {} would dispatch {} active cohorts across {} seed partitions; \
+ "dry run: run {} ({}) would dispatch {} active cohorts across {} seed partitions; \
{}/{} chunks unconfirmed; {}",
prepared.run_id().0,
+ prepared.run_kind().as_str(),
prepared.cohort_count(),
COHORT_PARTITION_COUNT,
prepared.remaining_chunks(),
@@ -100,6 +102,11 @@ async fn async_main(args: Args, config: Config) -> Result<()> {
);
return Ok(());
}
+ validate_person_dispatch(
+ run_id,
+ prepared.run_kind(),
+ config.seeder_person_reconcile_dispatch_enabled,
+ )?;
eprintln!(
"Dispatching {} active cohorts across {} seed partitions for run {}.",
prepared.cohort_count(),
@@ -120,7 +127,8 @@ async fn async_main(args: Args, config: Config) -> Result<()> {
PreparedDispatch::Certified(certified) => {
let run_id = certified.prepared().run_id();
let status = certified.prepared().run_status();
- let claim = acquire_claim(&pool, run_id, status).await?;
+ let claim =
+ acquire_claim(&pool, run_id, certified.prepared().run_kind(), status).await?;
// `plan_chunks` gates its INSERT on a non-locking `status = 'seeding'` read, so a
// statement whose snapshot predates the CAS can still add pending chunks the CAS's own
// snapshot could not see. Re-read the ledger now that the run is frozen in
@@ -199,17 +207,31 @@ async fn async_main(args: Args, config: Config) -> Result<()> {
async fn acquire_claim(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
status: RunStatus,
) -> Result<ReconcilingClaim> {
let claim = match status {
- RunStatus::Seeding => cas_run_reconciling(pool, run_id).await,
- RunStatus::Reconciling => confirm_reconciling(pool, run_id).await,
+ RunStatus::Seeding => cas_run_reconciling(pool, run_id, kind).await,
+ RunStatus::Reconciling => confirm_reconciling(pool, run_id, kind).await,
other => bail!("run {run_id:?} has status {other:?}; expected seeding or reconciling"),
}
.context("claiming the run for reconcile dispatch")?;
claim.context("the run changed state before it could be claimed for dispatch; re-run")
}
+/// The kind is derived from the run row, so without this the CLI would put person-scoped tiles on
+/// the seed topic while the fleet-wide gate is still off. Keyed on the reconcile gate rather than
+/// the seed gate: producing tiles is the step an old processor cannot survive, and the two are
+/// staged separately. Called after the dry-run early return, so a rehearsal stays allowed.
+fn validate_person_dispatch(run_id: RunId, kind: RunKind, dispatch_enabled: bool) -> Result<()> {
+ anyhow::ensure!(
+ kind != RunKind::PersonProperty || dispatch_enabled,
+ "run {run_id:?} is a person_property run; set SEEDER_PERSON_RECONCILE_DISPATCH_ENABLED \
+ once every processor decodes reconcile_person tiles"
+ );
+ Ok(())
+}
+
fn validate_partition_count(configured: u32) -> Result<()> {
anyhow::ensure!(
configured == COHORT_PARTITION_COUNT,
@@ -265,4 +287,17 @@ mod tests {
assert!(validate_partition_count(COHORT_PARTITION_COUNT).is_ok());
assert!(validate_partition_count(8).is_err());
}
+
+ /// The gate an operator would otherwise be the only thing standing between a person run and
+ /// `reconcile_person` tiles a processor predating the split skip-commits without a marker,
+ /// stranding the run a marker short of complete.
+ #[test]
+ fn cli_dispatches_a_person_run_only_once_the_reconcile_gate_is_open() {
+ let run_id = RunId(Uuid::parse_str(RUN_ID).unwrap());
+ assert!(validate_person_dispatch(run_id, RunKind::PersonProperty, false).is_err());
+ assert!(validate_person_dispatch(run_id, RunKind::PersonProperty, true).is_ok());
+ // The gate is person-only: a behavioral run dispatches whatever it is set to.
+ assert!(validate_person_dispatch(run_id, RunKind::Behavioral, false).is_ok());
+ assert!(validate_person_dispatch(run_id, RunKind::Behavioral, true).is_ok());
+ }
}
diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rs
index 150417e5d2b6..3b30dce701d0 100644
--- a/rust/cohort-seeder/src/config.rs
+++ b/rust/cohort-seeder/src/config.rs
@@ -184,6 +184,32 @@ pub struct Config {
#[envconfig(default = "false")]
pub seeder_person_seeds_enabled: bool,
+ /// Enable the person-property *reconcile* path: completion discovery widens to `person_property`
+ /// runs, so a fully-seeded one transitions `seeding -> reconciling` and produces
+ /// `reconcile_person` tiles. The orchestrator also needs `SEEDER_PERSON_SEEDS_ENABLED` before
+ /// this does anything, since there is no person seed path to reconcile without it; the CLI
+ /// reads this flag on its own and will dispatch a person run's tiles with seeds off.
+ ///
+ /// Deploy order, in this order, no overlap:
+ /// 1. Roll the processor fleet-wide with a build that decodes `reconcile_person` tiles and
+ /// loads the person shape-hash map. An older processor routes the person kind to
+ /// `UnknownKind` and skip-commits it without a marker, stranding the run as a shortfall.
+ /// 2. Flip `SEEDER_PERSON_SEEDS_ENABLED` and let person runs seed.
+ /// 3. Flip this once step 1 is confirmed everywhere.
+ /// 4. Flip Django's `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` once both preconditions in
+ /// its `posthog/settings/cohorts.py` docstring hold: the flags service no longer reads
+ /// `last_backfill_person_properties_at` as proof `cohort_membership` is populated, and a
+ /// person-leaf edit supersedes the cohort's active person runs. Until then the finalizer
+ /// skips person runs, so they stay `reconciling` after step 3 and
+ /// `seeder_runs_reconciling{kind="person_property"}` climbs. That is expected, not a
+ /// stalled dispatch.
+ ///
+ /// Flipping this back off does not undo a bad rollout: a run already in `reconciling` stops
+ /// being discovered, so it never reaches `reconcile_observed_at` and never finalizes. Recovery
+ /// is an operator re-dispatch through the CLI after the fleet is upgraded.
+ #[envconfig(default = "false")]
+ pub seeder_person_reconcile_dispatch_enabled: bool,
+
/// Person-seed produce rate, shared across concurrent person chunks and separate from
/// `seeder_tiles_per_sec` so the two throughputs tune independently.
#[envconfig(default = "2000")]
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 2251f6d89149..e08880d69e9a 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -28,8 +28,8 @@ pub use chunk::{
ScannedChunk, StreamedChunk, UnknownChunkStatus,
};
pub use cohort_core::seed::{
- BehavioralShapeHash, BehavioralShapeHashError, PersonSeed, ReconcileCompleteMarker,
- ReconcileTile, SeedTile,
+ BehavioralShapeHash, PersonSeed, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope,
+ ReconcileTile, ScopeKind, SeedTile, ShapeHashError, UnknownScopeKind,
};
pub(crate) use completion::MARKER_WATCH_SCHEMA;
pub use completion::{
diff --git a/rust/cohort-seeder/src/kafka/producer.rs b/rust/cohort-seeder/src/kafka/producer.rs
index 0877e15c5a5b..4f76421436a9 100644
--- a/rust/cohort-seeder/src/kafka/producer.rs
+++ b/rust/cohort-seeder/src/kafka/producer.rs
@@ -274,7 +274,9 @@ mod tests {
let tile = ReconcileTile::new(
TeamId(2),
CohortId(42),
- crate::domain::BehavioralShapeHash::parse("shape").unwrap(),
+ crate::domain::ReconcileScope::Behavioral(
+ crate::domain::BehavioralShapeHash::parse("shape").unwrap(),
+ ),
crate::domain::RunId(Uuid::nil()),
);
diff --git a/rust/cohort-seeder/src/main.rs b/rust/cohort-seeder/src/main.rs
index da86d8a96b73..6d0b4995ce2c 100644
--- a/rust/cohort-seeder/src/main.rs
+++ b/rust/cohort-seeder/src/main.rs
@@ -31,6 +31,7 @@ use cohort_seeder::kafka::markers::MarkerWatcher;
use cohort_seeder::kafka::pacing::TilePacer;
use cohort_seeder::kafka::producer::SeedTileProducer;
use cohort_seeder::observability;
+use cohort_seeder::store::runs::RunKind;
common_alloc::used!();
@@ -117,9 +118,16 @@ async fn async_main(config: Config) -> Result<()> {
scanner: PersonScanner::new(clickhouse_client),
pacer: TilePacer::new(person_settings.seeds_per_sec),
});
- let completion = build_completion(&config, &pool, &producer, observe_policy, watch_handle)
- .await
- .context("validating completion driver policies")?;
+ let completion = build_completion(
+ &config,
+ settings.completion_kinds(),
+ &pool,
+ &producer,
+ observe_policy,
+ watch_handle,
+ )
+ .await
+ .context("validating completion driver policies")?;
let claimed_by = format!("cohort-seeder:{}", uuid::Uuid::now_v7());
let orchestrator = SeederOrchestrator::new(
pool,
@@ -172,6 +180,7 @@ struct WiredCompletion {
/// name would otherwise surface only as runs stuck re-dispatching forever.
async fn build_completion(
config: &Config,
+ kinds: &'static [RunKind],
pool: &sqlx::PgPool,
producer: &SeedTileProducer,
observe_policy: ObservePolicy,
@@ -199,7 +208,7 @@ async fn build_completion(
.context("joining membership topic verification task")?
.context("verifying the membership topic is reachable")?;
- let mut driver = CompletionDriver::new(pool.clone(), config.team_allowlist.clone());
+ let mut driver = CompletionDriver::new(pool.clone(), config.team_allowlist.clone(), kinds);
if let AutoDispatchPolicy::Enabled(register_backfill) = dispatch_policy {
let max_inflight = NonZeroUsize::new(config.seeder_max_inflight_tiles)
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index f7f3c904fe70..5e30d5c10e1d 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -40,10 +40,14 @@ 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).
pub const RECONCILE_CAS_LOST: &str = "seeder_reconcile_cas_lost_total";
pub const RECONCILE_RECORD_INVALID: &str = "seeder_reconcile_record_invalid_total";
pub const RECONCILE_DISPATCHES_IN_FLIGHT: &str = "seeder_reconcile_dispatches_in_flight";
+/// Runs currently in the reconcile protocol, labelled by the run's `kind` (gauge). Published for
+/// every discovered kind each tick, zeroes included, so a drained kind does not freeze.
pub const RUNS_RECONCILING: &str = "seeder_runs_reconciling";
// Liveness, marker watcher, and observation.
pub const RECONCILE_MARKERS_OBSERVED: &str = "seeder_reconcile_markers_observed_total";
@@ -51,16 +55,27 @@ pub const RECONCILE_MARKER_PARSE_FAILURES: &str = "seeder_reconcile_marker_parse
pub const RECONCILE_MARKER_WATCH_LAG: &str = "seeder_reconcile_marker_watch_lag";
pub const RECONCILE_LIVENESS_LAGGING_PARTITIONS: &str =
"seeder_reconcile_liveness_lagging_partitions";
+/// Cohort participations settled complete, labelled by the run's `kind` (counter).
pub const RECONCILE_COHORTS_COMPLETED: &str = "seeder_reconcile_cohorts_completed_total";
+/// Cohort participations terminally superseded while short, labelled by the run's `kind`
+/// (counter).
pub const RECONCILE_COHORTS_PARTIAL: &str = "seeder_reconcile_cohorts_partial_total";
+/// Cohort participations short of their markers with the pinned shape unchanged — the retryable
+/// half of the split — labelled by the run's `kind` (counter).
pub const RECONCILE_COHORTS_SHORTFALL: &str = "seeder_reconcile_cohorts_shortfall_total";
+/// Runs that settled without a single marker — the shape a processor that cannot decode the
+/// tile's kind produces — labelled by the run's `kind` (counter).
pub const RECONCILE_ZERO_MARKER_RUNS: &str = "seeder_reconcile_zero_marker_runs_total";
+/// Runs the observation pass settled, labelled by the run's `kind` (counter).
pub const RUNS_OBSERVED: &str = "seeder_runs_observed_total";
pub const RECONCILE_WATCH_TRUNCATED: &str = "seeder_reconcile_watch_truncated_total";
pub const RECONCILE_OBSERVATION_STALLED_AGE_SECONDS: &str =
"seeder_reconcile_observation_stalled_age_seconds";
pub const RECONCILE_OBSERVATION_PASS_SECONDS: &str = "seeder_reconcile_observation_pass_seconds";
pub const RECONCILE_OBSERVE_ERRORS: &str = "seeder_reconcile_observe_errors_total";
+/// Reconciling runs with no usable dispatch record, labelled by the run's `kind` (gauge).
+/// Published for every discovered kind each tick, zeroes included, so a drained kind does not
+/// freeze at its last reading.
pub const RECONCILE_RUNS_UNDISPATCHED: &str = "seeder_reconcile_runs_undispatched";
// Person-property seed path.
pub const PERSONS_SCANNED: &str = "seeder_persons_scanned_total";
diff --git a/rust/cohort-seeder/src/store/completion.rs b/rust/cohort-seeder/src/store/completion.rs
index b59b1b5ee795..ae76fcf54d90 100644
--- a/rust/cohort-seeder/src/store/completion.rs
+++ b/rust/cohort-seeder/src/store/completion.rs
@@ -7,6 +7,15 @@
//! status = 'reconciling'`. A miss returns [`CompletionStoreError::CompletionFenceLost`], mirroring
//! the chunk store's `LeaseLost`: a stale writer (an older dispatch superseded by a re-dispatch, or a
//! run Django has already moved on) can never clobber the ruling dispatch's state.
+//!
+//! The two backfill kinds share these tables and are kept disjoint three different ways, so it is
+//! worth naming them separately: every statement that *selects* a run by id — discovery, the CAS,
+//! the claim, the unreconcilable observe — binds the caller's [`RunKind`] in SQL, so a run id under
+//! the wrong kind matches no row; the participation loads carry no kind predicate and instead parse
+//! only the matching hash column, where the other kind's `''` fails closed; and `backfill_kind` is
+//! write-once at run creation, which is what lets a kind read at discovery stay authoritative for
+//! the rest of the dispatch. The observation writes are the exception that proves it: they fence on
+//! the dispatch epoch alone, which a kind-bound claim is the only way to mint.
use chrono::{DateTime, Utc};
use cohort_core::filters::{CohortId, TeamId};
@@ -18,9 +27,9 @@ use std::collections::{HashMap, HashSet};
use std::fmt;
use crate::domain::{
- BehavioralShapeHash, BehavioralShapeHashError, CompletionParts, CompletionPhase,
- CompletionStatus, DispatchEpoch, MarkerWatch, ObservationEnds, PartitionBitmap,
- PartitionBitmapError, ReconcileHwms, RunId, WatchPositions, MARKER_WATCH_SCHEMA,
+ CompletionParts, CompletionPhase, CompletionStatus, DispatchEpoch, MarkerWatch,
+ ObservationEnds, PartitionBitmap, PartitionBitmapError, ReconcileHwms, ReconcileScope, RunId,
+ ScopeKind, ShapeHashError, WatchPositions, MARKER_WATCH_SCHEMA,
};
use super::runs::RunKind;
@@ -31,7 +40,7 @@ use super::{RenderedError, PERSISTED_ERROR_LIMIT};
/// byte-identical and the composed SQL is a compile-time constant (mirrors `runs::run_columns!`).
macro_rules! completion_columns {
() => {
- "id, team_id, status, chunks_planned_at, reconcile_dispatched_at, \
+ "id, team_id, backfill_kind, status, chunks_planned_at, reconcile_dispatched_at, \
reconcile_observed_at, reconcile_hwms, marker_watch"
};
}
@@ -55,6 +64,15 @@ macro_rules! confirmed_chunk_status {
};
}
+// The kind predicate binds the caller's allowed-kind set, mirroring `runs::discover_runs`: with the
+// person gate off, discovery binds `['behavioral']` and the person path stays inert.
+//
+// An already-observed reconciling run is excluded, because the driver has no work left for one —
+// Django terminalizes it. Returning it is not free: `completion_columns!` hydrates `reconcile_hwms`
+// and `marker_watch`, two per-partition JSONB documents, for every row. A person run observed while
+// `BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED` is shut holds `reconciling` until the gate opens,
+// so the pass would decode the whole parked backlog every tick to reach a gauge. That gauge comes
+// from [`count_reconciling_by_kind`] instead.
const DISCOVER_COMPLETION_ALL: &str = concat!(
"\n SELECT ",
completion_columns!(),
@@ -64,7 +82,10 @@ const DISCOVER_COMPLETION_ALL: &str = concat!(
", ",
reconciling_status!(),
")",
- "\n AND backfill_kind = 'behavioral'",
+ "\n AND backfill_kind = ANY($1)",
+ "\n AND (status = ",
+ seeding_status!(),
+ " OR reconcile_observed_at IS NULL)",
"\n ORDER BY created_at\n"
);
@@ -77,17 +98,43 @@ const DISCOVER_COMPLETION_ONLY: &str = concat!(
", ",
reconciling_status!(),
")",
- "\n AND backfill_kind = 'behavioral'",
+ "\n AND backfill_kind = ANY($2)",
"\n AND team_id = ANY($1)",
+ "\n AND (status = ",
+ seeding_status!(),
+ " OR reconcile_observed_at IS NULL)",
"\n ORDER BY created_at\n"
);
+// Counts rather than rows, and no `reconcile_observed_at` predicate: the point is to report the
+// runs discovery drops as well as the ones it keeps. Driven by `cohort_bfr_reconciling_idx`, whose
+// partial `status = 'reconciling'` predicate and leading `backfill_kind` make this cost the live
+// reconciling set rather than the table's terminal history.
+const COUNT_RECONCILING_ALL: &str = concat!(
+ "\n SELECT backfill_kind, count(*) AS runs",
+ "\n FROM cohort_backfill_runs",
+ "\n WHERE status = ",
+ reconciling_status!(),
+ "\n AND backfill_kind = ANY($1)",
+ "\n GROUP BY backfill_kind\n"
+);
+
+const COUNT_RECONCILING_ONLY: &str = concat!(
+ "\n SELECT backfill_kind, count(*) AS runs",
+ "\n FROM cohort_backfill_runs",
+ "\n WHERE status = ",
+ reconciling_status!(),
+ "\n AND backfill_kind = ANY($2)",
+ "\n AND team_id = ANY($1)",
+ "\n GROUP BY backfill_kind\n"
+);
+
const CAS_RUN_RECONCILING: &str = concat!(
"\n UPDATE cohort_backfill_runs",
"\n SET status = ",
reconciling_status!(),
", updated_at = now()",
- "\n WHERE id = $1 AND backfill_kind = 'behavioral' AND status = ",
+ "\n WHERE id = $1 AND backfill_kind = $2 AND status = ",
seeding_status!(),
" AND chunks_planned_at IS NOT NULL",
"\n AND NOT EXISTS (",
@@ -153,12 +200,13 @@ pub enum CompletionStoreError {
#[source]
source: PartitionBitmapError,
},
- #[error("run {run_id:?} cohort {cohort_id:?} has an invalid pinned behavioral shape hash")]
- InvalidBehavioralShapeHash {
+ #[error("run {run_id:?} cohort {cohort_id:?} has an invalid pinned {kind} shape hash")]
+ InvalidShapeHash {
run_id: RunId,
cohort_id: CohortId,
+ kind: ScopeKind,
#[source]
- source: BehavioralShapeHashError,
+ source: ShapeHashError,
},
}
@@ -173,8 +221,8 @@ pub enum PlanningStampOutcome {
/// ([`cas_run_reconciling`]) or by re-confirming an already-reconciling run ([`confirm_reconciling`]).
/// It is linear: [`ReconcilingClaim::record`] persists the dispatch or [`ReconcilingClaim::revert`]
/// releases it back to `seeding`, and either consumes the claim so a dispatch can never be recorded
-/// twice off one CAS. Both minting queries filter `backfill_kind`, so a claim also proves the run
-/// belongs to this protocol.
+/// twice off one CAS. Both minting queries bind the caller's [`RunKind`], so a claim also proves the
+/// run is of the kind the caller believes it is dispatching.
#[must_use]
#[derive(Debug)]
pub struct ReconcilingClaim {
@@ -269,10 +317,8 @@ impl ReconcilingClaim {
/// Stamp the planning proof (`chunks_planned_at`) exactly once for a seeding run — the durable
/// evidence that chunk planning ran, which distinguishes a legitimately zero-chunk run from one
-/// whose planning has not yet happened. The stamp pair is the one kind-parameterized exception to
-/// this module's hardcoded behavioral filters: person runs earn their planning proof here too,
-/// while every other entry point stays behavioral-only, so a `person_property` run id handed to
-/// the reconcile protocol can never enter it.
+/// whose planning has not yet happened. Kind-bound like every other entry point here: a run id
+/// presented under the wrong kind matches nothing.
pub async fn mark_chunks_planned(
pool: &PgPool,
run_id: RunId,
@@ -323,9 +369,11 @@ pub async fn read_planning_stamp(
pub async fn cas_run_reconciling(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {
let claimed = sqlx::query_as::<_, ClaimRow>(CAS_RUN_RECONCILING)
.bind(run_id)
+ .bind(kind.as_str())
.fetch_optional(pool)
.await?;
Ok(claimed.map(ClaimRow::into_claim))
@@ -337,16 +385,18 @@ pub async fn cas_run_reconciling(
pub async fn confirm_reconciling(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
) -> Result<Option<ReconcilingClaim>, CompletionStoreError> {
let claimed = sqlx::query_as::<_, ClaimRow>(
r#"
UPDATE cohort_backfill_runs
SET updated_at = now()
- WHERE id = $1 AND backfill_kind = 'behavioral' AND status = 'reconciling'
+ WHERE id = $1 AND backfill_kind = $2 AND status = 'reconciling'
RETURNING id, reconcile_dispatched_at
"#,
)
.bind(run_id)
+ .bind(kind.as_str())
.fetch_optional(pool)
.await?;
Ok(claimed.map(ClaimRow::into_claim))
@@ -593,12 +643,13 @@ pub async fn mark_run_observed(
pub async fn mark_run_observed_unreconcilable(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
) -> Result<(), CompletionStoreError> {
let updated = sqlx::query_scalar::<_, RunId>(
r#"
UPDATE cohort_backfill_runs
SET reconcile_observed_at = now(), updated_at = now()
- WHERE id = $1 AND backfill_kind = 'behavioral' AND status = 'reconciling'
+ WHERE id = $1 AND backfill_kind = $2 AND status = 'reconciling'
AND NOT EXISTS (
SELECT 1 FROM cohort_backfill_run_cohorts
WHERE run_id = $1 AND superseded_at IS NULL
@@ -607,6 +658,7 @@ pub async fn mark_run_observed_unreconcilable(
"#,
)
.bind(run_id)
+ .bind(kind.as_str())
.fetch_optional(pool)
.await?;
fence(
@@ -620,7 +672,9 @@ pub async fn mark_run_observed_unreconcilable(
#[derive(Debug, Clone)]
pub struct ObservationParticipation {
pub cohort_id: CohortId,
- pub behavioral_filters_shape_hash: BehavioralShapeHash,
+ /// The fence the run pinned, of the run's own kind. Comparing it against the cohort's current
+ /// shape is what splits a shortfall into retryable and terminal.
+ pub scope: ReconcileScope,
pub bits: PartitionBitmap,
pub reconcile_completed_at: Option<DateTime<Utc>>,
pub superseded_at: Option<DateTime<Utc>>,
@@ -628,15 +682,17 @@ pub struct ObservationParticipation {
}
/// Load every participation's observation state for a run. Superseded rows are included so the
-/// caller can let supersession trump completion.
+/// caller can let supersession trump completion. Only the column matching `kind` is parsed; the
+/// other is `''` for a single-kind run and is never read.
pub async fn load_observation_participations(
pool: &PgPool,
run_id: RunId,
+ kind: RunKind,
) -> Result<Vec<ObservationParticipation>, CompletionStoreError> {
let rows = sqlx::query_as::<_, ObservationParticipationRow>(
r#"
- SELECT cohort_id, behavioral_filters_shape_hash, reconcile_marker_bits,
- reconcile_completed_at, superseded_at, stamped_at
+ SELECT cohort_id, behavioral_filters_shape_hash, person_filters_shape_hash,
+ reconcile_marker_bits, reconcile_completed_at, superseded_at, stamped_at
FROM cohort_backfill_run_cohorts
WHERE run_id = $1
ORDER BY cohort_id
@@ -646,6 +702,7 @@ pub async fn load_observation_participations(
.fetch_all(pool)
.await?;
+ let kind = kind.scope();
let mut participations = Vec::with_capacity(rows.len());
for row in rows {
let cohort_id = CohortId(row.cohort_id);
@@ -656,17 +713,17 @@ pub async fn load_observation_participations(
source,
}
})?;
- let behavioral_filters_shape_hash =
- BehavioralShapeHash::parse(&row.behavioral_filters_shape_hash).map_err(|source| {
- CompletionStoreError::InvalidBehavioralShapeHash {
- run_id,
- cohort_id,
- source,
- }
- })?;
+ let scope = ReconcileScope::parse(kind, row.pinned_hash(kind)).map_err(|source| {
+ CompletionStoreError::InvalidShapeHash {
+ run_id,
+ cohort_id,
+ kind,
+ source,
+ }
+ })?;
participations.push(ObservationParticipation {
cohort_id,
- behavioral_filters_shape_hash,
+ scope,
bits,
reconcile_completed_at: row.reconcile_completed_at,
superseded_at: row.superseded_at,
@@ -676,30 +733,31 @@ pub async fn load_observation_participations(
Ok(participations)
}
-/// The cohort's current behavioral shape, read from `posthog_cohort` to attribute a shortfall. An
-/// absent row is treated as `Deleted`; a NULL or unparseable hash is `Indeterminate` (the caller
-/// treats it as diverged).
+/// The cohort's current shape of one kind, read from `posthog_cohort` to attribute a shortfall. An
+/// absent row is treated as `Deleted`; a NULL, empty, or unparseable hash is `Indeterminate` (the
+/// caller treats it as diverged).
#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum CurrentBehavioralHash {
- Present(BehavioralShapeHash),
+pub enum CurrentShapeHash {
+ Present(ReconcileScope),
Deleted,
Indeterminate,
}
-/// Read the current behavioral shape hash for each requested cohort. Cohorts with no row are absent
-/// from the map, which the caller reads as [`CurrentBehavioralHash::Deleted`].
-pub async fn load_current_behavioral_hashes(
+/// Read each requested cohort's current shape hash of `kind`. Cohorts with no row are absent from
+/// the map, which the caller reads as [`CurrentShapeHash::Deleted`].
+pub async fn load_current_shape_hashes(
pool: &PgPool,
team_id: TeamId,
cohort_ids: &[CohortId],
-) -> Result<HashMap<CohortId, CurrentBehavioralHash>, CompletionStoreError> {
+ kind: RunKind,
+) -> Result<HashMap<CohortId, CurrentShapeHash>, CompletionStoreError> {
if cohort_ids.is_empty() {
return Ok(HashMap::new());
}
let ids: Vec<i32> = cohort_ids.iter().map(|cohort| cohort.0).collect();
let rows = sqlx::query_as::<_, CurrentCohortRow>(
r#"
- SELECT id, behavioral_filters_shape_hash, deleted
+ SELECT id, behavioral_filters_shape_hash, person_filters_shape_hash, deleted
FROM posthog_cohort
WHERE team_id = $1 AND id = ANY($2)
"#,
@@ -709,17 +767,18 @@ pub async fn load_current_behavioral_hashes(
.fetch_all(pool)
.await?;
+ let kind = kind.scope();
let mut current = HashMap::with_capacity(rows.len());
for row in rows {
let state = if row.deleted {
- CurrentBehavioralHash::Deleted
+ CurrentShapeHash::Deleted
} else {
- match row.behavioral_filters_shape_hash {
- Some(hash) => match BehavioralShapeHash::parse(&hash) {
- Ok(hash) => CurrentBehavioralHash::Present(hash),
- Err(_) => CurrentBehavioralHash::Indeterminate,
- },
- None => CurrentBehavioralHash::Indeterminate,
+ match row
+ .current_hash(kind)
+ .map(|hash| ReconcileScope::parse(kind, hash))
+ {
+ Some(Ok(scope)) => CurrentShapeHash::Present(scope),
+ Some(Err(_)) | None => CurrentShapeHash::Indeterminate,
}
};
current.insert(CohortId(row.id), state);
@@ -750,18 +809,24 @@ pub async fn runs_with_all_chunks_confirmed(
pub struct DiscoveredCompletion {
pub run_id: RunId,
pub team_id: TeamId,
+ pub kind: RunKind,
pub phase: CompletionPhase,
}
-/// Discover every seeding/reconciling behavioral run and classify each. Rows whose status is not one
-/// of the two the query selects are skipped defensively.
+/// Discover every seeding run, and every not-yet-observed reconciling run, of an allowed kind, and
+/// classify each. Rows whose status or kind is outside the vocabulary the query already bounds are
+/// skipped defensively. An observed run is the driver's exit condition, so it is filtered in SQL
+/// rather than hydrated and then matched away — [`count_reconciling_by_kind`] still sees it.
pub async fn discover_completions(
pool: &PgPool,
allowlist: &TeamAllowlist,
+ kinds: &[RunKind],
) -> Result<Vec<DiscoveredCompletion>, CompletionStoreError> {
+ let bound_kinds = kinds.iter().map(|kind| kind.as_str()).collect::<Vec<_>>();
let rows = match allowlist {
TeamAllowlist::All => {
sqlx::query_as::<_, CompletionRunRow>(DISCOVER_COMPLETION_ALL)
+ .bind(bound_kinds)
.fetch_all(pool)
.await?
}
@@ -770,6 +835,7 @@ pub async fn discover_completions(
team_ids.sort_unstable();
sqlx::query_as::<_, CompletionRunRow>(DISCOVER_COMPLETION_ONLY)
.bind(team_ids)
+ .bind(bound_kinds)
.fetch_all(pool)
.await?
}
@@ -777,12 +843,49 @@ pub async fn discover_completions(
Ok(rows.into_iter().filter_map(classify_row).collect())
}
+/// How many runs hold `reconciling`, per kind — including the observed ones discovery drops, which
+/// is the whole point: while the person readiness gate is shut, that backlog is the only thing the
+/// `seeder_runs_reconciling` gauge has to report, and it is exactly what the driver cannot act on.
+/// One aggregate, so the gauge costs a count rather than a hydration of every parked row.
+pub async fn count_reconciling_by_kind(
+ pool: &PgPool,
+ allowlist: &TeamAllowlist,
+ kinds: &[RunKind],
+) -> Result<HashMap<RunKind, u64>, CompletionStoreError> {
+ let bound_kinds = kinds.iter().map(|kind| kind.as_str()).collect::<Vec<_>>();
+ let rows = match allowlist {
+ TeamAllowlist::All => {
+ sqlx::query_as::<_, ReconcilingCountRow>(COUNT_RECONCILING_ALL)
+ .bind(bound_kinds)
+ .fetch_all(pool)
+ .await?
+ }
+ TeamAllowlist::Only(team_ids) => {
+ let mut team_ids = team_ids.iter().copied().collect::<Vec<_>>();
+ team_ids.sort_unstable();
+ sqlx::query_as::<_, ReconcilingCountRow>(COUNT_RECONCILING_ONLY)
+ .bind(team_ids)
+ .bind(bound_kinds)
+ .fetch_all(pool)
+ .await?
+ }
+ };
+ Ok(rows
+ .into_iter()
+ .filter_map(|row| {
+ let kind = row.backfill_kind.parse::<RunKind>().ok()?;
+ Some((kind, row.runs.max(0) as u64))
+ })
+ .collect())
+}
+
fn classify_row(row: CompletionRunRow) -> Option<DiscoveredCompletion> {
let status = match row.status.as_str() {
"seeding" => CompletionStatus::Seeding,
"reconciling" => CompletionStatus::Reconciling,
_ => return None,
};
+ let kind = row.backfill_kind.parse::<RunKind>().ok()?;
let phase = CompletionPhase::from_parts(CompletionParts {
status,
chunks_planned_at: row.chunks_planned_at,
@@ -794,6 +897,7 @@ fn classify_row(row: CompletionRunRow) -> Option<DiscoveredCompletion> {
Some(DiscoveredCompletion {
run_id: row.id,
team_id: TeamId(row.team_id),
+ kind,
phase,
})
}
@@ -850,6 +954,7 @@ impl ClaimRow {
struct CompletionRunRow {
id: RunId,
team_id: i32,
+ backfill_kind: String,
status: String,
chunks_planned_at: Option<DateTime<Utc>>,
reconcile_dispatched_at: Option<DateTime<Utc>>,
@@ -858,23 +963,49 @@ struct CompletionRunRow {
marker_watch: Option<Json<Value>>,
}
+#[derive(Debug, FromRow)]
+struct ReconcilingCountRow {
+ backfill_kind: String,
+ runs: i64,
+}
+
#[derive(Debug, FromRow)]
struct ObservationParticipationRow {
cohort_id: i32,
behavioral_filters_shape_hash: String,
+ person_filters_shape_hash: String,
reconcile_marker_bits: i64,
reconcile_completed_at: Option<DateTime<Utc>>,
superseded_at: Option<DateTime<Utc>>,
stamped_at: Option<DateTime<Utc>>,
}
+impl ObservationParticipationRow {
+ fn pinned_hash(&self, kind: ScopeKind) -> &str {
+ match kind {
+ ScopeKind::Behavioral => &self.behavioral_filters_shape_hash,
+ ScopeKind::PersonProperty => &self.person_filters_shape_hash,
+ }
+ }
+}
+
#[derive(Debug, FromRow)]
struct CurrentCohortRow {
id: i32,
behavioral_filters_shape_hash: Option<String>,
+ person_filters_shape_hash: Option<String>,
deleted: bool,
}
+impl CurrentCohortRow {
+ fn current_hash(&self, kind: ScopeKind) -> Option<&str> {
+ match kind {
+ ScopeKind::Behavioral => self.behavioral_filters_shape_hash.as_deref(),
+ ScopeKind::PersonProperty => self.person_filters_shape_hash.as_deref(),
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use crate::domain::ChunkStatus;
@@ -901,5 +1032,7 @@ mod tests {
assert!(CAS_RUN_RECONCILING.contains(confirmed_chunk_status!()));
assert!(RUNS_WITH_ALL_CHUNKS_CONFIRMED.contains(confirmed_chunk_status!()));
assert!(DISCOVER_COMPLETION_ALL.contains(seeding_status!()));
+ assert!(COUNT_RECONCILING_ALL.contains(reconciling_status!()));
+ assert!(COUNT_RECONCILING_ONLY.contains(reconciling_status!()));
}
}
diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rs
index 0d1baa292b31..0a2587589e1e 100644
--- a/rust/cohort-seeder/src/store/runs.rs
+++ b/rust/cohort-seeder/src/store/runs.rs
@@ -11,9 +11,10 @@ use sqlx::types::Json;
use sqlx::{FromRow, PgPool};
use crate::domain::{
- BehavioralShapeHash, BehavioralShapeHashError, PersonPinnedSnapshot, PersonRunValidation,
- PinnedError, PinnedParticipation, PinnedParticipationState, PinnedPersonRun, PinnedRun,
- PinnedRunSnapshot, ReconcileTile, RunId, TriggerKind, UtcMillis, ValidatedPinnedRun,
+ PersonPinnedSnapshot, PersonRunValidation, PinnedError, PinnedParticipation,
+ PinnedParticipationState, PinnedPersonRun, PinnedRun, PinnedRunSnapshot, ReconcileScope,
+ ReconcileTile, RunId, ScopeKind, ShapeHashError, TriggerKind, UnknownScopeKind, UtcMillis,
+ ValidatedPinnedRun,
};
use super::{RenderedError, PERSISTED_ERROR_LIMIT};
@@ -56,8 +57,17 @@ const READ_RUN: &str = concat!(
"\n WHERE id = $1 AND backfill_kind = $2\n"
);
+// The reconcile path derives the kind from the run row rather than asserting one, so this sibling
+// carries no kind predicate.
+const READ_RUN_ANY_KIND: &str = concat!(
+ "\n SELECT ",
+ run_columns!(),
+ "\n FROM cohort_backfill_runs",
+ "\n WHERE id = $1\n"
+);
+
const READ_ACTIVE_RECONCILE_PARTICIPATIONS: &str = r#"
- SELECT team_id, cohort_id, behavioral_filters_shape_hash
+ SELECT team_id, cohort_id, behavioral_filters_shape_hash, person_filters_shape_hash
FROM cohort_backfill_run_cohorts
WHERE run_id = $1 AND superseded_at IS NULL
ORDER BY cohort_id
@@ -161,29 +171,37 @@ pub enum RunKind {
impl RunKind {
pub const fn as_str(self) -> &'static str {
+ self.scope().as_str()
+ }
+
+ /// The definition fingerprint this kind's reconcile is fenced by. The two vocabularies are the
+ /// same strings by construction: the column and the metric label name one concept.
+ pub const fn scope(self) -> ScopeKind {
match self {
- Self::Behavioral => "behavioral",
- Self::PersonProperty => "person_property",
+ Self::Behavioral => ScopeKind::Behavioral,
+ Self::PersonProperty => ScopeKind::PersonProperty,
+ }
+ }
+}
+
+/// Exhaustive on [`ScopeKind`], so adding a scope without a matching run kind fails to compile.
+impl From<ScopeKind> for RunKind {
+ fn from(scope: ScopeKind) -> Self {
+ match scope {
+ ScopeKind::Behavioral => Self::Behavioral,
+ ScopeKind::PersonProperty => Self::PersonProperty,
}
}
}
impl FromStr for RunKind {
- type Err = UnknownRunKind;
+ type Err = UnknownScopeKind;
fn from_str(value: &str) -> Result<Self, Self::Err> {
- match value {
- "behavioral" => Ok(Self::Behavioral),
- "person_property" => Ok(Self::PersonProperty),
- other => Err(UnknownRunKind(other.to_string())),
- }
+ value.parse::<ScopeKind>().map(Self::from)
}
}
-#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
-#[error("unknown backfill kind {0:?}")]
-pub struct UnknownRunKind(pub String);
-
#[derive(Debug, Clone)]
pub struct DiscoveredRun {
pub run_id: RunId,
@@ -295,11 +313,12 @@ impl SeedableRun {
}
}
-/// A behavioral run proven safe to expand into reconcile control tiles. Construction validates
-/// the run state, tenant boundary, active participation set, and every persisted behavioral hash.
+/// A run proven safe to expand into reconcile control tiles. Construction validates the run state,
+/// tenant boundary, active participation set, and every persisted shape hash of the run's own kind.
#[derive(Debug, Clone)]
pub struct ReconcileRun {
run_id: RunId,
+ kind: RunKind,
status: RunStatus,
team_id: TeamId,
participations: Vec<ReconcileParticipation>,
@@ -310,6 +329,10 @@ impl ReconcileRun {
self.run_id
}
+ pub const fn kind(&self) -> RunKind {
+ self.kind
+ }
+
pub const fn status(&self) -> RunStatus {
self.status
}
@@ -323,7 +346,7 @@ impl ReconcileRun {
ReconcileTile::new(
self.team_id,
participation.cohort_id,
- participation.behavioral_filters_shape_hash.clone(),
+ participation.scope.clone(),
self.run_id,
)
})
@@ -333,7 +356,7 @@ impl ReconcileRun {
#[derive(Debug, Clone)]
struct ReconcileParticipation {
cohort_id: CohortId,
- behavioral_filters_shape_hash: BehavioralShapeHash,
+ scope: ReconcileScope,
}
#[derive(Debug, thiserror::Error)]
@@ -346,12 +369,13 @@ pub enum ReconcileRunError {
Status { run_id: RunId, status: RunStatus },
#[error("run {0:?} has no active cohort participations to reconcile")]
NoActiveParticipations(RunId),
- #[error("run {run_id:?} cohort {cohort_id:?} has an invalid behavioral shape hash")]
- InvalidBehavioralShapeHash {
+ #[error("run {run_id:?} cohort {cohort_id:?} has an invalid pinned {kind} shape hash")]
+ InvalidShapeHash {
run_id: RunId,
cohort_id: CohortId,
+ kind: ScopeKind,
#[source]
- source: BehavioralShapeHashError,
+ source: ShapeHashError,
},
#[error(
"run {run_id:?} team {expected_team_id} has cohort {cohort_id:?} stored under team {actual_team_id}"
@@ -539,6 +563,16 @@ struct ReconcileParticipationRow {
team_id: i32,
cohort_id: i32,
behavioral_filters_shape_hash: String,
+ person_filters_shape_hash: String,
+}
+
+impl ReconcileParticipationRow {
+ fn pinned_hash(&self, kind: ScopeKind) -> &str {
+ match kind {
+ ScopeKind::Behavioral => &self.behavioral_filters_shape_hash,
+ ScopeKind::PersonProperty => &self.person_filters_shape_hash,
+ }
+ }
}
#[derive(Debug, FromRow)]
@@ -575,12 +609,14 @@ pub async fn discover_runs(
rows.into_iter().map(DiscoveredRun::try_from).collect()
}
+/// Load a run's active participations as reconcile tiles. The kind comes from the run row, so a
+/// person run's fence is its person hash and a behavioral run's is its behavioral one; the other
+/// column is expected to be `''` and is never read.
pub async fn load_reconcile_run(
pool: &PgPool,
run_id: RunId,
) -> Result<ReconcileRun, ReconcileRunError> {
- // Reconcile stays behavioral-only: a person run id can never enter this protocol.
- let run = read_run(pool, run_id, RunKind::Behavioral).await?;
+ let run = read_run_any_kind(pool, run_id).await?;
if !matches!(run.status, RunStatus::Seeding | RunStatus::Reconciling) {
return Err(ReconcileRunError::Status {
run_id,
@@ -597,6 +633,7 @@ pub async fn load_reconcile_run(
return Err(ReconcileRunError::NoActiveParticipations(run_id));
}
+ let kind = run.kind.scope();
let mut participations = Vec::with_capacity(rows.len());
for row in rows {
let cohort_id = CohortId(row.cohort_id);
@@ -608,22 +645,20 @@ pub async fn load_reconcile_run(
actual_team_id: row.team_id,
});
}
- let behavioral_filters_shape_hash =
- BehavioralShapeHash::parse(&row.behavioral_filters_shape_hash).map_err(|source| {
- ReconcileRunError::InvalidBehavioralShapeHash {
- run_id,
- cohort_id,
- source,
- }
- })?;
- participations.push(ReconcileParticipation {
- cohort_id,
- behavioral_filters_shape_hash,
- });
+ let scope = ReconcileScope::parse(kind, row.pinned_hash(kind)).map_err(|source| {
+ ReconcileRunError::InvalidShapeHash {
+ run_id,
+ cohort_id,
+ kind,
+ source,
+ }
+ })?;
+ participations.push(ReconcileParticipation { cohort_id, scope });
}
Ok(ReconcileRun {
run_id,
+ kind: run.kind,
status: run.status,
team_id: run.team_id,
participations,
@@ -755,3 +790,12 @@ async fn read_run(pool: &PgPool, run_id: RunId, kind: RunKind) -> Result<Discove
.ok_or(RunError::NotFound(run_id))?;
row.try_into()
}
+
+async fn read_run_any_kind(pool: &PgPool, run_id: RunId) -> Result<DiscoveredRun, RunError> {
+ let row = sqlx::query_as::<_, RunRow>(READ_RUN_ANY_KIND)
+ .bind(run_id)
+ .fetch_optional(pool)
+ .await?
+ .ok_or(RunError::NotFound(run_id))?;
+ row.try_into()
+}
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index 13e0617aa57f..f726603ec364 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -17,7 +17,7 @@ use cohort_seeder::app::reconcile_dispatch::{
RegisterBackfillConfirmation,
};
use cohort_seeder::domain::{
- tile_ranges, ClaimEpoch, PersonRunValidation, PinnedWarning, ProduceHwms,
+ tile_ranges, ClaimEpoch, PersonRunValidation, PinnedWarning, ProduceHwms, ScopeKind,
};
use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome};
use cohort_seeder::store::lease::LeaseFailure;
@@ -373,7 +373,8 @@ async fn reconcile_run_load_is_fail_closed_and_behavioral_hash_scoped() -> Resul
.context("missing active cohort tile")?;
ensure!(tile.team_id() == TeamId(20));
ensure!(tile.cohort_id() == CohortId(201));
- ensure!(tile.filters_hash().as_str() == "behavioral-shape");
+ ensure!(tile.scope().hash_str() == "behavioral-shape");
+ ensure!(tile.scope().kind() == ScopeKind::Behavioral);
ensure!(tile.run_id() == run_id);
sqlx::query("UPDATE cohort_backfill_runs SET status = 'reconciling' WHERE id = $1")
@@ -415,8 +416,8 @@ async fn reconcile_run_load_is_fail_closed_and_behavioral_hash_scoped() -> Resul
.await?;
ensure!(matches!(
load_reconcile_run(&pool, run_id).await,
- Err(ReconcileRunError::InvalidBehavioralShapeHash { cohort_id, .. })
- if cohort_id == CohortId(201)
+ Err(ReconcileRunError::InvalidShapeHash { cohort_id, kind, .. })
+ if cohort_id == CohortId(201) && kind == ScopeKind::Behavioral
));
sqlx::query(
diff --git a/rust/cohort-seeder/tests/pg_completion.rs b/rust/cohort-seeder/tests/pg_completion.rs
index 669549915828..05592a49dfd4 100644
--- a/rust/cohort-seeder/tests/pg_completion.rs
+++ b/rust/cohort-seeder/tests/pg_completion.rs
@@ -17,19 +17,19 @@ use cohort_core::filters::{CohortId, TeamId};
use cohort_core::partitioner::COHORT_PARTITION_COUNT;
use cohort_seeder::domain::{
CompletionPhase, DispatchEpoch, MarkerPartition, MarkerWatch, MembershipPartition, NextOffset,
- ObservationEnds, PartitionBitmap, ProducedOffset, ReconcileHwms, RunId, SeedPartition,
- UndispatchedReason, WatchPositions,
+ ObservationEnds, PartitionBitmap, PersonShapeHash, ProducedOffset, ReconcileHwms,
+ ReconcileScope, RunId, SeedPartition, UndispatchedReason, WatchPositions,
};
use cohort_seeder::store::chunks::PgChunkStore;
use cohort_seeder::store::completion::{
- cas_run_reconciling, confirm_reconciling, discover_completions, load_current_behavioral_hashes,
- load_observation_participations, mark_chunks_planned, mark_participation_completed,
- mark_run_observed, mark_run_observed_unreconcilable, persist_marker_observations,
- persist_observation_ends, read_planning_stamp, record_participation_partial,
- record_participation_shortfall, runs_with_all_chunks_confirmed, CompletionStoreError,
- CurrentBehavioralHash, PlanningStampOutcome,
+ cas_run_reconciling, confirm_reconciling, count_reconciling_by_kind, discover_completions,
+ load_current_shape_hashes, load_observation_participations, mark_chunks_planned,
+ mark_participation_completed, mark_run_observed, mark_run_observed_unreconcilable,
+ persist_marker_observations, persist_observation_ends, read_planning_stamp,
+ record_participation_partial, record_participation_shortfall, runs_with_all_chunks_confirmed,
+ CompletionStoreError, CurrentShapeHash, PlanningStampOutcome,
};
-use cohort_seeder::store::runs::RunKind;
+use cohort_seeder::store::runs::{load_reconcile_run, RunKind};
use cohort_seeder::store::RenderedError;
use cohort_seeder::test_support;
use common_types::cohort::TeamAllowlist;
@@ -38,11 +38,14 @@ use sqlx::PgPool;
mod support;
use support::{
- empty_pinned, ensure_fence_lost, insert_cohort, insert_participation, insert_person_run,
- insert_reconciling_run, insert_run, person_pinned, set_marker_bits, with_db,
+ empty_pinned, ensure_fence_lost, insert_cohort, insert_participation,
+ insert_person_participation, insert_person_run, insert_reconciling_run, insert_run,
+ person_pinned, set_marker_bits, with_db,
};
const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;
+/// What discovery binds once `SEEDER_PERSON_SEEDS_ENABLED` is on.
+const BOTH_KINDS: &[RunKind] = &[RunKind::Behavioral, RunKind::PersonProperty];
fn full_hwms() -> ReconcileHwms {
let offsets: BTreeMap<SeedPartition, ProducedOffset> =
@@ -99,28 +102,42 @@ async fn planning_stamp_is_idempotent_and_refuses_non_seeding() -> Result<()> {
.await
}
-/// The person-kind inertness contract: `discover_completions` never surfaces a person run — the
-/// reconcile protocol stays behavioral-only by design — while the kind-parameterized stamp pair
-/// lets a person run earn its planning proof and refuses the wrong kind.
+/// Discovery is gated by the caller's allowed kinds — the dark proof: with the person gate off a
+/// person run is invisible, and with it on the same run surfaces carrying its kind.
#[tokio::test]
-async fn completion_discovery_excludes_person_runs_but_the_stamp_is_kind_aware() -> Result<()> {
+async fn completion_discovery_is_gated_by_the_allowed_kinds() -> Result<()> {
with_db(|pool| async move {
let person_run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
- ensure!(discover_completions(&pool, &TeamAllowlist::All)
- .await?
+ let dark = discover_completions(&pool, &TeamAllowlist::All, &[RunKind::Behavioral]).await?;
+ ensure!(dark
.iter()
.all(|completion| completion.run_id != person_run));
+ let lit = discover_completions(&pool, &TeamAllowlist::All, BOTH_KINDS).await?;
+ let discovered = lit
+ .iter()
+ .find(|completion| completion.run_id == person_run)
+ .context("the person run surfaces once its kind is allowed")?;
+ ensure!(discovered.kind == RunKind::PersonProperty);
+ Ok(())
+ })
+ .await
+}
+
+/// Every kind-bound entry point refuses a run id presented under the other kind, so the two
+/// protocols can never write each other's rows.
+#[tokio::test]
+async fn kind_bound_entry_points_refuse_the_other_kind() -> Result<()> {
+ with_db(|pool| async move {
+ let person_run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
+ let behavioral_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+
ensure!(matches!(
mark_chunks_planned(&pool, person_run, RunKind::Behavioral).await?,
PlanningStampOutcome::Skipped
));
- ensure!(
- read_planning_stamp(&pool, person_run, RunKind::PersonProperty)
- .await?
- .is_none()
- );
ensure!(matches!(
mark_chunks_planned(&pool, person_run, RunKind::PersonProperty).await?,
PlanningStampOutcome::Stamped
@@ -130,10 +147,79 @@ async fn completion_discovery_excludes_person_runs_but_the_stamp_is_kind_aware()
.await?
.is_some()
);
- // The behavioral-filtered read still refuses to see it.
ensure!(read_planning_stamp(&pool, person_run, RunKind::Behavioral)
.await?
.is_none());
+ mark_chunks_planned(&pool, behavioral_run, RunKind::Behavioral).await?;
+
+ // The CAS out of `seeding` is the gate into the reconcile protocol; each kind holds only
+ // its own runs.
+ ensure!(cas_run_reconciling(&pool, person_run, RunKind::Behavioral)
+ .await?
+ .is_none());
+ ensure!(
+ cas_run_reconciling(&pool, behavioral_run, RunKind::PersonProperty)
+ .await?
+ .is_none()
+ );
+ ensure!(
+ cas_run_reconciling(&pool, person_run, RunKind::PersonProperty)
+ .await?
+ .is_some()
+ );
+
+ // And once reconciling, the re-dispatch claim is bound the same way.
+ ensure!(confirm_reconciling(&pool, person_run, RunKind::Behavioral)
+ .await?
+ .is_none());
+ ensure!(
+ confirm_reconciling(&pool, person_run, RunKind::PersonProperty)
+ .await?
+ .is_some()
+ );
+ Ok(())
+ })
+ .await
+}
+
+/// A person run's fence is its person hash: `load_reconcile_run` and the observation load both read
+/// the kind-matching column and ignore the `''` sibling that would otherwise fail closed.
+#[tokio::test]
+async fn person_run_loads_pin_the_person_hash_and_ignore_the_empty_behavioral_column() -> Result<()>
+{
+ with_db(|pool| async move {
+ let run_id = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;
+ insert_person_participation(&pool, run_id, 2, 301, "person-shape").await?;
+
+ let run = load_reconcile_run(&pool, run_id).await?;
+ ensure!(run.kind() == RunKind::PersonProperty);
+ let scopes: Vec<ReconcileScope> = run.tiles().map(|tile| tile.scope().clone()).collect();
+ ensure!(
+ scopes
+ == vec![ReconcileScope::PersonProperty(PersonShapeHash::parse(
+ "person-shape"
+ )?)]
+ );
+
+ let participations =
+ load_observation_participations(&pool, run_id, RunKind::PersonProperty).await?;
+ ensure!(participations.len() == 1);
+ ensure!(participations[0].scope == scopes[0]);
+
+ // Read under the wrong kind and the sibling column's `''` fails closed rather than
+ // silently pinning nothing. Symmetric: a behavioral run read as person does the same.
+ let behavioral_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ insert_participation(&pool, behavioral_run, 2, 302, false, empty_pinned()).await?;
+ for (run, kind) in [
+ (run_id, RunKind::Behavioral),
+ (behavioral_run, RunKind::PersonProperty),
+ ] {
+ ensure!(matches!(
+ load_observation_participations(&pool, run, kind).await,
+ Err(CompletionStoreError::InvalidShapeHash { .. })
+ ));
+ }
Ok(())
})
.await
@@ -149,8 +235,8 @@ async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -
insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
mark_chunks_planned(&pool, ready, RunKind::Behavioral).await?;
let (left, right) = tokio::join!(
- cas_run_reconciling(&pool, ready),
- cas_run_reconciling(&pool, ready)
+ cas_run_reconciling(&pool, ready, RunKind::Behavioral),
+ cas_run_reconciling(&pool, ready, RunKind::Behavioral)
);
let winners = [left?, right?].into_iter().filter(Option::is_some).count();
ensure!(
@@ -161,7 +247,9 @@ async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -
// Unplanned seeding run: CAS refused.
let unplanned =
insert_run(&pool, 3, "team_enablement", "seeding", true, empty_pinned()).await?;
- ensure!(cas_run_reconciling(&pool, unplanned).await?.is_none());
+ ensure!(cas_run_reconciling(&pool, unplanned, RunKind::Behavioral)
+ .await?
+ .is_none());
// Planned but with an unconfirmed chunk: CAS refused.
let pending =
@@ -170,7 +258,9 @@ async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -
PgChunkStore::new(pool.clone())
.plan_chunks(pending, [100], ONE_BAND)
.await?;
- ensure!(cas_run_reconciling(&pool, pending).await?.is_none());
+ ensure!(cas_run_reconciling(&pool, pending, RunKind::Behavioral)
+ .await?
+ .is_none());
Ok(())
})
.await
@@ -193,7 +283,7 @@ async fn record_dispatch_resets_participations_and_mints_fresh_epoch() -> Result
.execute(&pool)
.await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable for dispatch")?;
let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -220,7 +310,7 @@ async fn record_dispatch_resets_participations_and_mints_fresh_epoch() -> Result
// Re-dispatch: a fresh claim records a new fence at or after the first.
set_marker_bits(&pool, run_id, 301, 5).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("re-dispatch should be claimable")?;
let next_epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -246,12 +336,12 @@ async fn revert_clears_the_dispatch_record_and_returns_to_seeding() -> Result<()
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
let _ = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be re-claimable")?;
claim.revert(&pool).await?;
@@ -266,7 +356,7 @@ async fn revert_clears_the_dispatch_record_and_returns_to_seeding() -> Result<()
.await?;
ensure!(status == "seeding" && cleared);
- let discovered = discover_completions(&pool, &TeamAllowlist::All).await?;
+ let discovered = discover_completions(&pool, &TeamAllowlist::All, BOTH_KINDS).await?;
let phase = discovered
.iter()
.find(|completion| completion.run_id == run_id)
@@ -284,10 +374,10 @@ async fn revert_is_fenced_against_a_dispatch_recorded_after_the_claim() -> Resul
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;
- let stale = confirm_reconciling(&pool, run_id)
+ let stale = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
- let winner = confirm_reconciling(&pool, run_id)
+ let winner = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable twice")?;
let epoch = winner.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -316,10 +406,10 @@ async fn record_is_fenced_against_a_dispatch_recorded_after_the_claim() -> Resul
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;
- let stale = confirm_reconciling(&pool, run_id)
+ let stale = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
- let winner = confirm_reconciling(&pool, run_id)
+ let winner = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable twice")?;
let epoch = winner.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -405,7 +495,7 @@ async fn recording_a_partial_preserves_an_existing_supersession_reason() -> Resu
.bind(run_id)
.execute(&pool)
.await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -441,7 +531,7 @@ async fn fenced_writes_reject_stale_epoch_and_wrong_status() -> Result<()> {
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -498,7 +588,7 @@ async fn fenced_participation_writes_lose_an_epoch_superseded_mid_statement() ->
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
let _initial = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -593,7 +683,7 @@ async fn capturing_ends_leaves_the_watcher_positions_alone() -> Result<()> {
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 301, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -630,18 +720,29 @@ async fn unreconcilable_runs_are_marked_observed_for_django() -> Result<()> {
with_db(|pool| async move {
let stranded = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, stranded, 2, 301, true, empty_pinned()).await?;
- mark_run_observed_unreconcilable(&pool, stranded).await?;
+ mark_run_observed_unreconcilable(&pool, stranded, RunKind::Behavioral).await?;
- let discovered = discover_completions(&pool, &TeamAllowlist::All).await?;
- let phase = discovered
+ let observed_stamp: Option<DateTime<Utc>> = sqlx::query_scalar(
+ "SELECT reconcile_observed_at FROM cohort_backfill_runs WHERE id = $1",
+ )
+ .bind(stranded)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(observed_stamp.is_some());
+ // Observing it is what removes it from the driver's working set: everything left is
+ // Django's, and the gauge reads it from the aggregate instead.
+ let discovered = discover_completions(&pool, &TeamAllowlist::All, BOTH_KINDS).await?;
+ ensure!(!discovered
.iter()
- .find(|completion| completion.run_id == stranded)
- .map(|completion| completion.phase.clone());
- ensure!(phase == Some(CompletionPhase::Observed));
+ .any(|completion| completion.run_id == stranded));
+ let counts = count_reconciling_by_kind(&pool, &TeamAllowlist::All, BOTH_KINDS).await?;
+ ensure!(counts.get(&RunKind::Behavioral) == Some(&1));
let live = insert_reconciling_run(&pool, 3).await?;
insert_participation(&pool, live, 3, 401, false, empty_pinned()).await?;
- ensure_fence_lost(mark_run_observed_unreconcilable(&pool, live).await)?;
+ ensure_fence_lost(
+ mark_run_observed_unreconcilable(&pool, live, RunKind::Behavioral).await,
+ )?;
let observed: Option<DateTime<Utc>> = sqlx::query_scalar(
"SELECT reconcile_observed_at FROM cohort_backfill_runs WHERE id = $1",
)
@@ -661,7 +762,7 @@ async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()
with_db(|pool| async move {
let run_id = insert_reconciling_run(&pool, 2).await?;
insert_participation(&pool, run_id, 2, 401, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, run_id)
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
.await?
.context("run should be claimable")?;
let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -697,7 +798,8 @@ async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()
.await?;
ensure!(stored < 0, "bit 63 must store as a negative BIGINT");
- let participations = load_observation_participations(&pool, run_id).await?;
+ let participations =
+ load_observation_participations(&pool, run_id, RunKind::Behavioral).await?;
let bits = participations
.iter()
.find(|participation| participation.cohort_id == CohortId(401))
@@ -713,9 +815,10 @@ async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()
}
/// Discovery classifies each completion phase, including a reconciling run whose completion
-/// columns are all NULL.
+/// columns are all NULL — and drops the observed run, whose remaining work is Django's, while the
+/// reconciling-run count still reports it.
#[tokio::test]
-async fn discovery_classifies_each_phase_including_undispatched_rows() -> Result<()> {
+async fn discovery_classifies_each_phase_and_drops_observed_runs() -> Result<()> {
with_db(|pool| async move {
let unplanned =
insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
@@ -726,7 +829,7 @@ async fn discovery_classifies_each_phase_including_undispatched_rows() -> Result
let dispatched = insert_reconciling_run(&pool, 4).await?;
insert_participation(&pool, dispatched, 4, 401, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, dispatched)
+ let claim = confirm_reconciling(&pool, dispatched, RunKind::Behavioral)
.await?
.context("dispatched run should be claimable")?;
let _ = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
@@ -744,13 +847,13 @@ async fn discovery_classifies_each_phase_including_undispatched_rows() -> Result
let observed = insert_reconciling_run(&pool, 6).await?;
insert_participation(&pool, observed, 6, 601, false, empty_pinned()).await?;
- let claim = confirm_reconciling(&pool, observed)
+ let claim = confirm_reconciling(&pool, observed, RunKind::Behavioral)
.await?
.context("observed run should be claimable")?;
let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
mark_run_observed(&pool, observed, epoch).await?;
- let discovered = discover_completions(&pool, &TeamAllowlist::All).await?;
+ let discovered = discover_completions(&pool, &TeamAllowlist::All, BOTH_KINDS).await?;
let phase = |run| {
discovered
.iter()
@@ -769,35 +872,62 @@ async fn discovery_classifies_each_phase_including_undispatched_rows() -> Result
UndispatchedReason::NeverDispatched
))
);
- ensure!(phase(observed) == Some(CompletionPhase::Observed));
+ // Dropped from discovery rather than hydrated and matched away: a run parked here behind
+ // Django's readiness gate would otherwise cost two per-partition JSONB decodes every tick.
+ ensure!(phase(observed).is_none());
+
+ // The three reconciling runs, observed or not, all still reach the gauge.
+ let counts = count_reconciling_by_kind(&pool, &TeamAllowlist::All, BOTH_KINDS).await?;
+ ensure!(counts.get(&RunKind::Behavioral) == Some(&3));
+ ensure!(!counts.contains_key(&RunKind::PersonProperty));
+
+ // Both statements have a team-scoped variant, and dev — where this rollout lands first —
+ // is the environment that runs allowlisted.
+ let allowlisted = TeamAllowlist::Only([4, 6].into_iter().collect());
+ let scoped = discover_completions(&pool, &allowlisted, BOTH_KINDS).await?;
+ ensure!(scoped.iter().map(|row| row.run_id).eq([dispatched]));
+ let scoped_counts = count_reconciling_by_kind(&pool, &allowlisted, BOTH_KINDS).await?;
+ ensure!(scoped_counts.get(&RunKind::Behavioral) == Some(&2));
Ok(())
})
.await
}
-/// The current-hash read distinguishes present, deleted, absent, and NULL/unparseable cohorts.
+/// The current-shape read distinguishes present, deleted, absent, and NULL/unparseable cohorts, and
+/// reads each kind out of its own column.
#[tokio::test]
-async fn current_behavioral_hashes_read_present_deleted_absent_and_null() -> Result<()> {
+async fn current_shape_hashes_read_present_deleted_absent_and_null_per_kind() -> Result<()> {
with_db(|pool| async move {
- insert_cohort(&pool, 501, 2, Some("shape-a"), false).await?;
- insert_cohort(&pool, 502, 2, Some("shape-b"), true).await?;
- insert_cohort(&pool, 503, 2, None, false).await?;
+ // Distinct per column, so reading the wrong one is a mismatch rather than a coincidence.
+ insert_cohort(&pool, 501, 2, Some("behavioral-a"), Some("person-a"), false).await?;
+ insert_cohort(&pool, 502, 2, Some("behavioral-b"), Some("person-b"), true).await?;
+ insert_cohort(&pool, 503, 2, None, None, false).await?;
// 504 intentionally absent.
- let hashes = load_current_behavioral_hashes(
- &pool,
- TeamId(2),
- &[CohortId(501), CohortId(502), CohortId(503), CohortId(504)],
- )
- .await?;
+ for (kind, expected) in [
+ (RunKind::Behavioral, "behavioral-a"),
+ (RunKind::PersonProperty, "person-a"),
+ ] {
+ let hashes = load_current_shape_hashes(
+ &pool,
+ TeamId(2),
+ &[CohortId(501), CohortId(502), CohortId(503), CohortId(504)],
+ kind,
+ )
+ .await?;
- ensure!(matches!(
- hashes.get(&CohortId(501)),
- Some(CurrentBehavioralHash::Present(hash)) if hash.as_str() == "shape-a"
- ));
- ensure!(hashes.get(&CohortId(502)) == Some(&CurrentBehavioralHash::Deleted));
- ensure!(hashes.get(&CohortId(503)) == Some(&CurrentBehavioralHash::Indeterminate));
- ensure!(!hashes.contains_key(&CohortId(504)));
+ ensure!(
+ hashes.get(&CohortId(501))
+ == Some(&CurrentShapeHash::Present(ReconcileScope::parse(
+ kind.scope(),
+ expected
+ )?)),
+ "{kind:?} reads its own column",
+ );
+ ensure!(hashes.get(&CohortId(502)) == Some(&CurrentShapeHash::Deleted));
+ ensure!(hashes.get(&CohortId(503)) == Some(&CurrentShapeHash::Indeterminate));
+ ensure!(!hashes.contains_key(&CohortId(504)));
+ }
Ok(())
})
.await
diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rs
index b24f3e1daf82..a095232594e1 100644
--- a/rust/cohort-seeder/tests/support/mod.rs
+++ b/rust/cohort-seeder/tests/support/mod.rs
@@ -152,21 +152,25 @@ pub async fn set_marker_bits(
Ok(())
}
-/// Insert a row into the schema-local `posthog_cohort` projection for `load_current_behavioral_hashes`.
+/// Insert a row into the schema-local `posthog_cohort` projection for `load_current_shape_hashes`.
+/// The two guard columns are set independently so a read of the wrong one cannot pass unnoticed.
pub async fn insert_cohort(
pool: &PgPool,
id: i32,
team_id: i32,
behavioral_hash: Option<&str>,
+ person_hash: Option<&str>,
deleted: bool,
) -> Result<()> {
sqlx::query(
- "INSERT INTO posthog_cohort (id, team_id, behavioral_filters_shape_hash, deleted) \
- VALUES ($1, $2, $3, $4)",
+ "INSERT INTO posthog_cohort \
+ (id, team_id, behavioral_filters_shape_hash, person_filters_shape_hash, deleted) \
+ VALUES ($1, $2, $3, $4, $5)",
)
.bind(id)
.bind(team_id)
.bind(behavioral_hash)
+ .bind(person_hash)
.bind(deleted)
.execute(pool)
.await?;
@@ -240,6 +244,33 @@ pub async fn insert_participation(
Ok(())
}
+/// A person run's participation: the person hash is pinned and the behavioral column stays `''`,
+/// exactly as `create_person_backfill_run_for_cohort` writes it.
+pub async fn insert_person_participation(
+ pool: &PgPool,
+ run_id: RunId,
+ team_id: i32,
+ cohort_id: i32,
+ person_hash: &str,
+) -> Result<()> {
+ sqlx::query(
+ r#"
+ INSERT INTO cohort_backfill_run_cohorts
+ (id, run_id, team_id, cohort_id, filters_shape_hash,
+ behavioral_filters_shape_hash, person_filters_shape_hash, pinned_filters)
+ VALUES ($1, $2, $3, $4, 'full-shape', '', $5, '{}'::jsonb)
+ "#,
+ )
+ .bind(Uuid::now_v7())
+ .bind(run_id)
+ .bind(team_id)
+ .bind(cohort_id)
+ .bind(person_hash)
+ .execute(pool)
+ .await?;
+ Ok(())
+}
+
/// Insert a `person_property` run with a pinned `person_scan_since` 30 days back.
pub async fn insert_person_run(
pool: &PgPool,
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index 1b3eca2c550b..bec68c15de9e 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -1489,7 +1489,7 @@ mod tests {
use tempfile::TempDir;
use uuid::Uuid;
- use cohort_core::seed::{BehavioralShapeHash, ReconcileTile, RunId};
+ use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
use crate::consumers::seeds::SeedWork;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder, TeamId};
@@ -2634,7 +2634,7 @@ mod tests {
let tile = ReconcileTile::new(
TeamId(TEAM),
CohortId(1),
- BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::from_u128(1)),
);
let held = dispatcher.dispatch_seeds(vec![ConsumedSeed {
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index 42ae19f7287d..c56f2deb5e32 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -869,8 +869,8 @@ mod tests {
use std::num::NonZeroU32;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, ReconcileTile, RunId, SChunkMs,
- ScannedAtMs,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, ReconcileScope, ReconcileTile,
+ RunId, SChunkMs, ScannedAtMs,
};
use uuid::Uuid;
@@ -1271,10 +1271,12 @@ mod tests {
let reconcile = ReconcileTile::new(
TeamId(2),
CohortId(42),
- BehavioralShapeHash::parse(
- "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- )
- .unwrap(),
+ ReconcileScope::Behavioral(
+ BehavioralShapeHash::parse(
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ )
+ .unwrap(),
+ ),
RunId(Uuid::nil()),
);
let bytes = serde_json::to_vec(&reconcile).unwrap();
@@ -1329,7 +1331,7 @@ mod tests {
let reconcile = ReconcileTile::new(
TeamId(2),
CohortId(42),
- BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::nil()),
);
let consumed = ConsumedSeed {
@@ -1352,7 +1354,7 @@ mod tests {
let reconcile = ReconcileTile::new(
TeamId(2),
CohortId(42),
- BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::nil()),
);
let reconcile_seed = |offset| ConsumedSeed {
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index d8aa40ab1ef5..6a890e729108 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -220,6 +220,7 @@ mod tests {
team_id,
filters: serde_json::Value::Null,
behavioral_filters_shape_hash: None,
+ person_filters_shape_hash: None,
timezone: "UTC".to_string(),
}
}
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 23acb5b463e3..b7a3fe07ab94 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -534,13 +534,17 @@ pub const SEED_IDLE_PROBE_DURATION_SECONDS: &str = "cohort_seed_idle_probe_durat
/// staleness** — quiet partitions' fences and the live-lag gate both stall when the probe stops.
pub const SEED_IDLE_PROBE_LAST_PASS_TIMESTAMP_SECONDS: &str =
"cohort_seed_idle_probe_last_pass_timestamp_seconds";
-/// Reconcile jobs admitted to partition-local queues (counter).
+/// Reconcile jobs admitted to partition-local queues, labelled by `kind` — the tile's shape-hash
+/// kind, `behavioral` or `person_property` (counter).
pub const RECONCILE_JOBS_ENQUEUED_TOTAL: &str = "cohort_reconcile_jobs_enqueued_total";
-/// Reconcile jobs that emitted their completion marker and released their seed floor (counter).
+/// Reconcile jobs that emitted their completion marker and released their seed floor, labelled by
+/// `kind` (counter). Balances against the enqueued/discarded/superseded series per kind, which is
+/// how a run left short a marker becomes visible.
pub const RECONCILE_JOBS_COMPLETED_TOTAL: &str = "cohort_reconcile_jobs_completed_total";
-/// Queued jobs replaced by a higher Kafka offset for the same team and cohort (counter).
+/// Queued jobs replaced by a higher Kafka offset for the same team, cohort, and `kind` (counter).
pub const RECONCILE_JOBS_SUPERSEDED_TOTAL: &str = "cohort_reconcile_jobs_superseded_total";
-/// Reconcile jobs invalidated by a drain-time guard, labelled by bounded `reason` (counter).
+/// Reconcile jobs invalidated by a drain-time guard, labelled by bounded `reason` and `kind`
+/// (counter).
pub const RECONCILE_JOBS_DISCARDED_TOTAL: &str = "cohort_reconcile_jobs_discarded_total";
/// Stage 2 rows read by reconcile and durably settled, counted once per committed page (counter). A
/// page that fails its produce or commit and retries is not double-counted.
@@ -550,7 +554,7 @@ pub const RECONCILE_ROWS_SCANNED_TOTAL: &str = "cohort_reconcile_rows_scanned_to
pub const RECONCILE_ROWS_EMITTED_TOTAL: &str = "cohort_reconcile_rows_emitted_total";
/// Stale Stage 2 bits durably fixed, labelled by `direction` (counter).
pub const RECONCILE_BITS_FIXED_TOTAL: &str = "cohort_reconcile_bits_fixed_total";
-/// Reconcile completion markers acknowledged by Kafka (counter).
+/// Reconcile completion markers acknowledged by Kafka, labelled by `kind` (counter).
pub const RECONCILE_MARKERS_EMITTED_TOTAL: &str = "cohort_reconcile_markers_emitted_total";
/// Partition-local reconcile queue depth, labelled by `partition` (gauge).
pub const RECONCILE_QUEUE_DEPTH: &str = "cohort_reconcile_queue_depth";
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
index a5ec274a7ac7..b8452167e33d 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -6,7 +6,9 @@
#![allow(clippy::disallowed_methods)]
use std::cell::Cell;
-use std::collections::HashSet;
+use std::collections::hash_map::Entry;
+use std::collections::HashMap;
+use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
@@ -188,10 +190,15 @@ pub type RawKv = (Vec<u8>, Vec<u8>);
#[derive(Debug, Default)]
struct Stage2DirtyTracking {
- /// The set of cohort prefixes with a reconcile drain currently capturing dirty rows. At most one
- /// job per prefix ever holds a lease (admission supersedes same `(partition, team, cohort)`, and
- /// the partition worker is serial), so a set — not a refcount — models the real invariant.
- active: RwLock<HashSet<Stage2CohortPrefix>>,
+ /// Cohort prefixes with a reconcile drain currently capturing dirty rows, refcounted by lease.
+ ///
+ /// No path holds two leases on one prefix today: the prefix carries `partition_id`, there is one
+ /// `ReconcileQueue` per partition worker, and only that queue's head is ever leased — kind-scoped
+ /// supersession puts a mixed cohort's two runs in the same queue, not in the same lease. Counting
+ /// rather than setting is what keeps this correct if that ever stops holding: the last release
+ /// wins instead of the first, so capture stays on for the surviving job rather than silently
+ /// dropping every concurrent mutation from its snapshot.
+ active: RwLock<HashMap<Stage2CohortPrefix, NonZeroUsize>>,
active_count: AtomicUsize,
}
@@ -201,11 +208,10 @@ impl Stage2DirtyTracking {
.active
.write()
.expect("Stage 2 dirty-tracking lock is not held across fallible work");
- let inserted = active.insert(prefix);
- debug_assert!(
- inserted,
- "a cohort prefix cannot hold two dirty-tracking leases"
- );
+ active
+ .entry(prefix)
+ .and_modify(|leases| *leases = leases.saturating_add(1))
+ .or_insert(NonZeroUsize::MIN);
self.active_count.fetch_add(1, Ordering::Release);
Stage2DirtyTrackingGuard {
tracking: self.clone(),
@@ -226,7 +232,7 @@ impl Stage2DirtyTracking {
self.active
.read()
.expect("Stage 2 dirty-tracking lock is not held across fallible work")
- .contains(&prefix)
+ .contains_key(&prefix)
}
/// The dirty marker to stage for a `cf_stage2` write, or `None` when no drain tracks its cohort.
@@ -239,12 +245,20 @@ impl Stage2DirtyTracking {
}
fn release(&self, prefix: Stage2CohortPrefix) {
- let removed = self
+ let mut active = self
.active
.write()
- .expect("Stage 2 dirty-tracking lock is not held across fallible work")
- .remove(&prefix);
- debug_assert!(removed, "every dirty-tracking guard owns one active lease");
+ .expect("Stage 2 dirty-tracking lock is not held across fallible work");
+ match active.entry(prefix) {
+ Entry::Occupied(mut entry) => match NonZeroUsize::new(entry.get().get() - 1) {
+ Some(remaining) => *entry.get_mut() = remaining,
+ None => {
+ entry.remove();
+ }
+ },
+ Entry::Vacant(_) => debug_assert!(false, "every guard owns one active lease"),
+ }
+ drop(active);
let previous = self.active_count.fetch_sub(1, Ordering::Release);
debug_assert!(previous > 0, "dirty-tracking reference count underflow");
}
@@ -1884,6 +1898,53 @@ mod tests {
);
}
+ #[test]
+ fn stage2_dirty_capture_survives_until_the_last_lease_releases() {
+ let dir = TempDir::new().unwrap();
+ let store = CohortStore::open(&StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ let key = Stage2Key {
+ partition_id: 3,
+ team_id: 7,
+ cohort_id: 100,
+ person_id: Uuid::from_u128(1),
+ };
+ let prefix = key.cohort_prefix();
+
+ // No production path holds two leases on one prefix today, but the refcount is what keeps
+ // capture on for a surviving lease if that ever changes — the last release must win, not
+ // the first.
+ let first = store.track_stage2_dirty(prefix);
+ let second = store.track_stage2_dirty(prefix);
+ drop(first);
+ store
+ .write_batch(|batch| batch.put_stage2(&key, b"during"))
+ .unwrap();
+ assert_eq!(
+ store.scan_stage2_dirty(prefix, None, 10).unwrap().len(),
+ 1,
+ "capture stays on while any lease is held",
+ );
+
+ drop(second);
+ store
+ .write_batch(|batch| {
+ batch.delete_stage2_dirty(&Stage2DirtyKey::new(key));
+ batch.put_stage2(&key, b"after");
+ })
+ .unwrap();
+ assert!(
+ store
+ .scan_stage2_dirty(prefix, None, 10)
+ .unwrap()
+ .is_empty(),
+ "the last release disables capture",
+ );
+ }
+
#[test]
fn scan_stage2_dirty_is_bounded_and_resumable() {
let dir = TempDir::new().unwrap();
diff --git a/rust/cohort-stream-processor/src/sweep/reconcile.rs b/rust/cohort-stream-processor/src/sweep/reconcile.rs
index 34f23d6cf872..090411a9cd75 100644
--- a/rust/cohort-stream-processor/src/sweep/reconcile.rs
+++ b/rust/cohort-stream-processor/src/sweep/reconcile.rs
@@ -43,7 +43,7 @@ mod tests {
use uuid::Uuid;
use cohort_core::filters::{CohortId, TeamId};
- use cohort_core::seed::{BehavioralShapeHash, ReconcileTile, RunId};
+ use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
use crate::filters::{CatalogHandle, FilterCatalog};
use crate::partitions::{OffsetTracker, PartitionRouter};
@@ -97,7 +97,7 @@ mod tests {
ReconcileTile::new(
TeamId(7),
CohortId(1),
- BehavioralShapeHash::parse("shape-v1").unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse("shape-v1").unwrap()),
RunId(Uuid::nil()),
),
tracker.defer(0, 5),
diff --git a/rust/cohort-stream-processor/src/workers/reconcile.rs b/rust/cohort-stream-processor/src/workers/reconcile.rs
index e1d403115886..3c6ac5d196dd 100644
--- a/rust/cohort-stream-processor/src/workers/reconcile.rs
+++ b/rust/cohort-stream-processor/src/workers/reconcile.rs
@@ -13,9 +13,9 @@ use tracing::{debug, info, warn};
use cohort_core::clickhouse_timestamp_to_millis;
use cohort_core::filters::{CohortId, TeamId};
-use cohort_core::seed::ReconcileTile;
#[cfg(test)]
use cohort_core::seed::RunId;
+use cohort_core::seed::{ReconcileScope, ReconcileTile, ScopeKind};
use crate::filters::manager::CatalogHandle;
use crate::filters::reverse_index::TeamFilters;
@@ -182,17 +182,22 @@ impl ReconcileQueue {
/// Replace a queued job only when the incoming Kafka offset is newer. A follower rewind may
/// replay an older job while a newer run is still queued; that replay must never evict the newer
/// snapshot.
+ ///
+ /// Scoped by kind as well as cohort: a mixed cohort can be reconciled by a behavioral and a
+ /// person-property run at once, and those two snapshots answer different fences — evicting one
+ /// for the other would leave its run permanently short a marker.
pub(crate) fn supersede_if_newer(
&mut self,
team_id: TeamId,
cohort_id: CohortId,
+ scope: ScopeKind,
incoming_offset: i64,
) -> SupersedeOutcome {
- let Some(position) = self
- .jobs
- .iter()
- .position(|job| job.tile.team_id() == team_id && job.tile.cohort_id() == cohort_id)
- else {
+ let Some(position) = self.jobs.iter().position(|job| {
+ job.tile.team_id() == team_id
+ && job.tile.cohort_id() == cohort_id
+ && job.tile.scope().kind() == scope
+ }) else {
return SupersedeOutcome::NoQueuedJob;
};
if incoming_offset <= self.jobs[position].offset.offset() {
@@ -298,16 +303,25 @@ fn evaluate_guard(
if !eligibility.registers_membership() {
return ReconcileGuard::Discard(ReconcileDiscardReason::NotEmitting);
}
- // An absent hash means the cohort has no behavioral leaves (the loader omits person-only
- // cohorts, which the person-property backfill heals separately) or the run was superseded. Either
- // way this is the intended fail-closed skip, observable via the `hash_unknown` discard counter.
- let Some(actual_hash) = filters.behavioral_shape_hashes.get(&tile.cohort_id()) else {
- return ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown);
+ // The tile's scope picks the guard map, so a person hash is never checked against a behavioral
+ // one. An absent entry means the cohort has no leaves of that kind (the loader omits the column
+ // when it is empty) or the run was superseded; either way this is the intended fail-closed skip,
+ // observable via the `hash_unknown` discard counter.
+ let matches = match tile.scope() {
+ ReconcileScope::Behavioral(pinned) => filters
+ .behavioral_shape_hashes
+ .get(&tile.cohort_id())
+ .map(|current| current == pinned),
+ ReconcileScope::PersonProperty(pinned) => filters
+ .person_shape_hashes
+ .get(&tile.cohort_id())
+ .map(|current| current == pinned),
};
- if actual_hash != tile.filters_hash() {
- return ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch);
+ match matches {
+ None => ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
+ Some(false) => ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch),
+ Some(true) => ReconcileGuard::Proceed,
}
- ReconcileGuard::Proceed
}
/// Advance at most one scan page for the queue head. Guard-discarded jobs are drained in the same
@@ -357,11 +371,17 @@ pub(crate) async fn handle_reconcile_drain(
discarded.offset,
"discarded reconcile",
);
- counter!(RECONCILE_JOBS_DISCARDED_TOTAL, "reason" => reason.as_str()).increment(1);
+ counter!(
+ RECONCILE_JOBS_DISCARDED_TOTAL,
+ "reason" => reason.as_str(),
+ "kind" => tile.scope().kind().as_str(),
+ )
+ .increment(1);
warn_job!(
tile,
partition_id,
reason = reason.as_str(),
+ kind = tile.scope().kind().as_str(),
"discarding reconcile job without a completion marker",
);
continue;
@@ -744,7 +764,8 @@ async fn drain_marker(
return DrainStep::Yield;
}
- counter!(RECONCILE_MARKERS_EMITTED_TOTAL).increment(1);
+ let kind = tile.scope().kind().as_str();
+ counter!(RECONCILE_MARKERS_EMITTED_TOTAL, "kind" => kind).increment(1);
let completed = queue
.finish_front()
.expect("the marker-producing queue head is still present");
@@ -754,7 +775,7 @@ async fn drain_marker(
completed.offset,
"completed reconcile",
);
- counter!(RECONCILE_JOBS_COMPLETED_TOTAL).increment(1);
+ counter!(RECONCILE_JOBS_COMPLETED_TOTAL, "kind" => kind).increment(1);
info!(
partition_id,
team_id = tile.team_id().0,
@@ -956,7 +977,7 @@ mod tests {
use tempfile::TempDir;
use uuid::Uuid;
- use cohort_core::seed::BehavioralShapeHash;
+ use cohort_core::seed::{BehavioralShapeHash, PersonShapeHash};
use cohort_core::{CohortEligibility, ExcludedReason, FilterCatalog, LeafStateKey};
use crate::filters::tree::{CohortTree, FilterNode};
@@ -1034,14 +1055,39 @@ mod tests {
CohortId(COHORT),
BehavioralShapeHash::parse(SHAPE_HASH).unwrap(),
);
+ if !single_leaf {
+ // A mixed cohort carries both guards, so either kind of run can reconcile it.
+ builder.set_person_shape_hash(
+ CohortId(COHORT),
+ PersonShapeHash::parse(SHAPE_HASH).unwrap(),
+ );
+ }
let filters = builder.freeze(UTC);
let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
+ (handle_for(filters), lsk)
+ }
+
+ /// A person-only cohort: no behavioral leaf, so only the person guard fences its reconcile.
+ fn person_catalog() -> (CatalogHandle, LeafStateKey) {
+ let cohort = json!({ "properties": { "type": "AND", "values": [person_leaf()] } });
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(CohortId(COHORT), TeamId(TEAM), &cohort)
+ .unwrap();
+ builder.set_person_shape_hash(
+ CohortId(COHORT),
+ PersonShapeHash::parse(SHAPE_HASH).unwrap(),
+ );
(
- CatalogHandle::from_catalog(FilterCatalog::from_teams([(TeamId(TEAM), filters)])),
- lsk,
+ handle_for(builder.freeze(UTC)),
+ LeafStateKey::for_person_property(&PERSON_HASH),
)
}
+ fn handle_for(filters: TeamFilters) -> CatalogHandle {
+ CatalogHandle::from_catalog(FilterCatalog::from_teams([(TeamId(TEAM), filters)]))
+ }
+
struct DrainShell {
_dir: TempDir,
store: CohortStore,
@@ -1059,10 +1105,26 @@ mod tests {
sink: Arc<dyn MembershipSink>,
cascade_sink: CaptureCascadeSink,
scan_page: usize,
+ ) -> Self {
+ Self::over(catalog(single_leaf), sink, cascade_sink, scan_page)
+ }
+
+ fn person_only(
+ sink: Arc<dyn MembershipSink>,
+ cascade_sink: CaptureCascadeSink,
+ scan_page: usize,
+ ) -> Self {
+ Self::over(person_catalog(), sink, cascade_sink, scan_page)
+ }
+
+ fn over(
+ (catalog, lsk): (CatalogHandle, LeafStateKey),
+ sink: Arc<dyn MembershipSink>,
+ cascade_sink: CaptureCascadeSink,
+ scan_page: usize,
) -> Self {
let (_dir, store) = temp_store();
let handle = store_handle(&store);
- let (catalog, lsk) = catalog(single_leaf);
let mut deps = Arc::try_unwrap(MergeWorkerDeps::capture())
.unwrap_or_else(|_| panic!("test owns the only dependency Arc"));
deps.reconcile.enabled = true;
@@ -1153,10 +1215,12 @@ mod tests {
self.deps
.seed_tracker
.mark_dispatched(PARTITION as i32, offset + 1);
- let SupersedeOutcome::Replaced(superseded) =
- self.queue
- .supersede_if_newer(tile.team_id(), tile.cohort_id(), offset)
- else {
+ let SupersedeOutcome::Replaced(superseded) = self.queue.supersede_if_newer(
+ tile.team_id(),
+ tile.cohort_id(),
+ tile.scope().kind(),
+ offset,
+ ) else {
panic!("a newer run must supersede the queued job");
};
let (replacement, _) = self
@@ -1190,10 +1254,14 @@ mod tests {
}
fn tile(team_id: i32, cohort_id: i32, run_id: u128) -> ReconcileTile {
+ scoped_tile(team_id, cohort_id, run_id, ScopeKind::Behavioral)
+ }
+
+ fn scoped_tile(team_id: i32, cohort_id: i32, run_id: u128, guard: ScopeKind) -> ReconcileTile {
ReconcileTile::new(
TeamId(team_id),
CohortId(cohort_id),
- BehavioralShapeHash::parse(SHAPE_HASH).unwrap(),
+ ReconcileScope::parse(guard, SHAPE_HASH).unwrap(),
RunId(Uuid::from_u128(run_id)),
)
}
@@ -1301,7 +1369,7 @@ mod tests {
queue.enqueue(tile(2, 7, 3), tracker.defer(3, 12));
let SupersedeOutcome::Replaced(superseded) =
- queue.supersede_if_newer(TeamId(1), CohortId(7), 13)
+ queue.supersede_if_newer(TeamId(1), CohortId(7), ScopeKind::Behavioral, 13)
else {
panic!("the newer run should supersede team 1 cohort 7");
};
@@ -1314,11 +1382,60 @@ mod tests {
Some(crate::partitions::offset_tracker::MarkOutcome::WithinDispatch),
);
assert!(matches!(
- queue.supersede_if_newer(TeamId(2), CohortId(7), 12),
+ queue.supersede_if_newer(TeamId(2), CohortId(7), ScopeKind::Behavioral, 12),
SupersedeOutcome::RetainedNewerOrEqual,
));
}
+ #[test]
+ fn a_mixed_cohorts_two_guards_queue_side_by_side_and_supersede_only_their_own() {
+ let (_dir, store) = temp_store();
+ let tracker = OffsetTracker::new();
+ let backlog = Arc::new(ReconcileBacklog::default());
+ tracker.mark_dispatched(3, 20);
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store));
+ queue.enqueue(
+ scoped_tile(TEAM, COHORT, 1, ScopeKind::Behavioral),
+ tracker.defer(3, 10),
+ );
+ queue.enqueue(
+ scoped_tile(TEAM, COHORT, 2, ScopeKind::PersonProperty),
+ tracker.defer(3, 11),
+ );
+
+ // A newer person run evicts only the queued person job; the behavioral snapshot is a
+ // different fence and still owes its own marker.
+ let SupersedeOutcome::Replaced(superseded) = queue.supersede_if_newer(
+ TeamId(TEAM),
+ CohortId(COHORT),
+ ScopeKind::PersonProperty,
+ 12,
+ ) else {
+ panic!("the newer person run should supersede the queued person job");
+ };
+ assert_eq!(queue.len(), 1);
+ assert_eq!(queue.front_run_id(), Some(RunId(Uuid::from_u128(1))));
+ tracker.complete_deferred(superseded);
+ assert_eq!(
+ tracker.committable_offsets().get(&3),
+ Some(&10),
+ "the surviving behavioral job still pins the partition's floor at its own offset",
+ );
+
+ assert!(
+ matches!(
+ queue.supersede_if_newer(
+ TeamId(TEAM),
+ CohortId(COHORT),
+ ScopeKind::PersonProperty,
+ 13,
+ ),
+ SupersedeOutcome::NoQueuedJob,
+ ),
+ "the surviving behavioral job is invisible to a person-kind supersession",
+ );
+ }
+
#[test]
fn older_or_duplicate_replay_never_evicts_the_queued_run() {
let (_dir, store) = temp_store();
@@ -1330,7 +1447,12 @@ mod tests {
for replayed_offset in [10, 15] {
assert!(matches!(
- queue.supersede_if_newer(TeamId(1), CohortId(7), replayed_offset),
+ queue.supersede_if_newer(
+ TeamId(1),
+ CohortId(7),
+ ScopeKind::Behavioral,
+ replayed_offset,
+ ),
SupersedeOutcome::RetainedNewerOrEqual,
));
assert_eq!(queue.front_run_id(), Some(RunId(Uuid::from_u128(2))));
@@ -1408,7 +1530,10 @@ mod tests {
);
}
- fn guard_filters(eligibility: Option<CohortEligibility>, hash: Option<&str>) -> TeamFilters {
+ fn guard_filters(
+ eligibility: Option<CohortEligibility>,
+ guards: &[(ScopeKind, &str)],
+ ) -> TeamFilters {
let mut filters = TeamFilters::default();
filters.cohorts.insert(
CohortId(COHORT),
@@ -1424,10 +1549,19 @@ mod tests {
if let Some(eligibility) = eligibility {
filters.eligibility.insert(CohortId(COHORT), eligibility);
}
- if let Some(hash) = hash {
- filters
- .behavioral_shape_hashes
- .insert(CohortId(COHORT), BehavioralShapeHash::parse(hash).unwrap());
+ for &(kind, hash) in guards {
+ match kind {
+ ScopeKind::Behavioral => {
+ filters
+ .behavioral_shape_hashes
+ .insert(CohortId(COHORT), BehavioralShapeHash::parse(hash).unwrap());
+ }
+ ScopeKind::PersonProperty => {
+ filters
+ .person_shape_hashes
+ .insert(CohortId(COHORT), PersonShapeHash::parse(hash).unwrap());
+ }
+ }
}
filters
}
@@ -1449,37 +1583,27 @@ mod tests {
ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent),
);
- let missing_eligibility = guard_filters(None, Some(SHAPE_HASH));
+ let behavioral_guard = &[(ScopeKind::Behavioral, SHAPE_HASH)];
+ let missing_eligibility = guard_filters(None, behavioral_guard);
assert_eq!(
evaluate_guard(true, Some(&missing_eligibility), &reconcile),
ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent),
);
let excluded = guard_filters(
Some(CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf)),
- Some(SHAPE_HASH),
+ behavioral_guard,
);
assert_eq!(
evaluate_guard(true, Some(&excluded), &reconcile),
ReconcileGuard::Discard(ReconcileDiscardReason::NotEmitting),
);
- let hash_unknown = guard_filters(Some(CohortEligibility::Stage2Composable), None);
- assert_eq!(
- evaluate_guard(true, Some(&hash_unknown), &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
- );
- let hash_mismatch =
- guard_filters(Some(CohortEligibility::Stage2Composable), Some("shape-v2"));
- assert_eq!(
- evaluate_guard(true, Some(&hash_mismatch), &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch),
- );
for eligibility in [
CohortEligibility::SingleLeaf(LeafStateKey(BEHAVIORAL_HASH)),
CohortEligibility::Stage2Composable,
CohortEligibility::Stage2ComposableRef,
] {
- let filters = guard_filters(Some(eligibility), Some(SHAPE_HASH));
+ let filters = guard_filters(Some(eligibility), behavioral_guard);
assert_eq!(
evaluate_guard(true, Some(&filters), &reconcile),
ReconcileGuard::Proceed,
@@ -1488,6 +1612,50 @@ mod tests {
}
}
+ #[test]
+ fn each_guard_kind_consults_only_its_own_map() {
+ let emitting = Some(CohortEligibility::Stage2Composable);
+ for (guard, other) in [
+ (ScopeKind::Behavioral, ScopeKind::PersonProperty),
+ (ScopeKind::PersonProperty, ScopeKind::Behavioral),
+ ] {
+ let reconcile = scoped_tile(TEAM, COHORT, 1, guard);
+ assert_eq!(
+ evaluate_guard(
+ true,
+ Some(&guard_filters(emitting, &[(guard, SHAPE_HASH)])),
+ &reconcile,
+ ),
+ ReconcileGuard::Proceed,
+ "{guard} matches its own map",
+ );
+ assert_eq!(
+ evaluate_guard(
+ true,
+ Some(&guard_filters(emitting, &[(guard, "shape-v2")])),
+ &reconcile,
+ ),
+ ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch),
+ "{guard} diverged",
+ );
+ assert_eq!(
+ evaluate_guard(true, Some(&guard_filters(emitting, &[])), &reconcile),
+ ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
+ "{guard} has no persisted hash",
+ );
+ // The catalog carries only the *other* kind's hash, at the very value the tile pins.
+ assert_eq!(
+ evaluate_guard(
+ true,
+ Some(&guard_filters(emitting, &[(other, SHAPE_HASH)])),
+ &reconcile,
+ ),
+ ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
+ "{guard} must not be satisfied by the {other} map",
+ );
+ }
+ }
+
#[tokio::test]
async fn drain_emits_the_full_snapshot_fixes_only_flips_and_paginates() {
let sink = CaptureSink::new();
@@ -1548,6 +1716,66 @@ mod tests {
assert_eq!(shell.committable(), Some(6));
}
+ #[tokio::test]
+ async fn one_cohorts_two_guarded_jobs_each_drain_to_their_own_marker() {
+ let sink = CaptureSink::new();
+ let mut shell =
+ DrainShell::new(false, Arc::new(sink.clone()), CaptureCascadeSink::new(), 8);
+ shell.write_current(Uuid::from_u128(1), true, true, false);
+ shell.enqueue(scoped_tile(TEAM, COHORT, 31, ScopeKind::Behavioral), 5);
+ shell.enqueue(scoped_tile(TEAM, COHORT, 32, ScopeKind::PersonProperty), 6);
+
+ for _ in 0..8 {
+ if shell.queue.front().is_none() {
+ break;
+ }
+ shell.tick().await;
+ }
+
+ // Both jobs lease the same Stage 2 prefix in turn; neither may release the other's capture.
+ assert_eq!(
+ sink.markers()
+ .iter()
+ .map(ReconcileCompleteMarker::run_id)
+ .collect::<Vec<_>>(),
+ vec![RunId(Uuid::from_u128(31)), RunId(Uuid::from_u128(32))],
+ );
+ assert!(shell.deps.reconcile.backlog.is_empty());
+ assert_eq!(shell.committable(), Some(7));
+ }
+
+ #[tokio::test]
+ async fn a_person_only_cohort_drains_under_its_person_guard_and_marks_complete() {
+ let sink = CaptureSink::new();
+ let mut shell =
+ DrainShell::person_only(Arc::new(sink.clone()), CaptureCascadeSink::new(), 8);
+ let matching = Uuid::from_u128(1);
+ let left = Uuid::from_u128(2);
+ shell.write_current(matching, false, true, false);
+ shell.write_current(left, false, false, true);
+ shell.enqueue(scoped_tile(TEAM, COHORT, 21, ScopeKind::PersonProperty), 5);
+
+ shell.tick().await;
+ shell.tick().await;
+
+ let statuses: Vec<_> = sink
+ .changes()
+ .iter()
+ .map(|change| (change.person_id.clone(), change.status))
+ .collect();
+ assert_eq!(
+ statuses,
+ vec![
+ (matching.to_string(), MembershipStatus::Entered),
+ (left.to_string(), MembershipStatus::Left),
+ ],
+ "the snapshot is computed from person state, not a behavioral leaf",
+ );
+ assert_eq!(sink.markers().len(), 1);
+ assert_eq!(sink.markers()[0].run_id(), RunId(Uuid::from_u128(21)));
+ assert!(shell.queue.front().is_none());
+ }
+
#[tokio::test]
async fn noop_reconcile_claims_a_transferred_fallback() {
let sink = CaptureSink::new();
diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rs
index b8a9a1af8543..7ea25b9a07b3 100644
--- a/rust/cohort-stream-processor/src/workers/seed_path.rs
+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs
@@ -766,7 +766,8 @@ fn admit_reconcile(
return;
}
- let deferred = match queue.supersede_if_newer(tile.team_id(), tile.cohort_id(), offset) {
+ let kind = tile.scope().kind();
+ let deferred = match queue.supersede_if_newer(tile.team_id(), tile.cohort_id(), kind, offset) {
SupersedeOutcome::NoQueuedJob => merge.seed_tracker.defer(partition_id as i32, offset),
SupersedeOutcome::Replaced(superseded) => {
let (replacement, outcome) = merge
@@ -783,7 +784,7 @@ fn admit_reconcile(
);
}
}
- counter!(RECONCILE_JOBS_SUPERSEDED_TOTAL).increment(1);
+ counter!(RECONCILE_JOBS_SUPERSEDED_TOTAL, "kind" => kind.as_str()).increment(1);
replacement
}
SupersedeOutcome::RetainedNewerOrEqual => {
@@ -802,7 +803,7 @@ fn admit_reconcile(
};
queue.enqueue(tile.clone(), deferred);
- counter!(RECONCILE_JOBS_ENQUEUED_TOTAL).increment(1);
+ counter!(RECONCILE_JOBS_ENQUEUED_TOTAL, "kind" => kind.as_str()).increment(1);
}
/// What one tile staged across its referencing leaves.
@@ -975,7 +976,8 @@ mod tests {
use tempfile::TempDir;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, SChunkMs, SeedTile,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, ReconcileTile, SChunkMs,
+ SeedTile,
};
use crate::consumers::seeds::SeedSkipReason;
@@ -1781,7 +1783,7 @@ mod tests {
ReconcileTile::new(
TEAM,
CohortId(cohort_id),
- BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::from_u128(run_id)),
)
}
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index 65ea8a8c1152..1cc08ff965b4 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -1072,7 +1072,7 @@ mod tombstone_redirect_tests {
use tempfile::TempDir;
use tokio::sync::mpsc;
- use cohort_core::seed::{BehavioralShapeHash, ReconcileTile, RunId};
+ use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
use crate::consumers::seeds::SeedWork;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};
@@ -1312,7 +1312,7 @@ mod tombstone_redirect_tests {
let tile = ReconcileTile::new(
TeamId(TEAM),
CohortId(1),
- BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::from_u128(1)),
);
@@ -1350,7 +1350,7 @@ mod tombstone_redirect_tests {
let tile = ReconcileTile::new(
TeamId(TEAM),
CohortId(1),
- BehavioralShapeHash::parse(FILTERS_HASH).unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
RunId(Uuid::from_u128(7)),
);
diff --git a/rust/cohort-stream-processor/tests/filter_catalog.rs b/rust/cohort-stream-processor/tests/filter_catalog.rs
index 135344d243e2..93e8b45322a7 100644
--- a/rust/cohort-stream-processor/tests/filter_catalog.rs
+++ b/rust/cohort-stream-processor/tests/filter_catalog.rs
@@ -20,6 +20,7 @@ fn row(id: i32, team_id: i32, filters: Value) -> CohortRow {
team_id,
filters,
behavioral_filters_shape_hash: None,
+ person_filters_shape_hash: None,
timezone: "UTC".to_string(),
}
}
diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rs
index a2a4f1b94c4c..d8ba82f973f3 100644
--- a/rust/cohort-stream-processor/tests/seed_consumer.rs
+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs
@@ -21,7 +21,8 @@ use std::time::{Duration, Instant};
use chrono_tz::UTC;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileTile, RunId, SChunkMs, SeedTile,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, ReconcileTile, RunId, SChunkMs,
+ SeedTile,
};
use cohort_stream_processor::consumers::{
CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,
@@ -910,7 +911,7 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
let reconcile = ReconcileTile::new(
TeamId(TEAM),
CohortId(COHORT),
- BehavioralShapeHash::parse(FILTERS_HASH).unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
run_id,
);
let producer = murmur2_producer();
@@ -1159,7 +1160,7 @@ async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point()
let reconcile = ReconcileTile::new(
TeamId(TEAM),
CohortId(COHORT),
- BehavioralShapeHash::parse(FILTERS_HASH).unwrap(),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
run_id,
);
assert_eq!(