: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cohorts): seed the backfill boundary day once it has ended (#106413)
Matheus Batistae1f73ce44acf
diff --git a/products/cohorts/backend/backfill/finalize.py b/products/cohorts/backend/backfill/finalize.pyindex 60429eae1603..135a8351b7c5 100644--- a/products/cohorts/backend/backfill/finalize.py+++ b/products/cohorts/backend/backfill/finalize.py@@ -12,6 +12,10 @@ The seeder writes a definitive per-participation outcome (``reconcile_completed_``superseded_at`` / retryable ``error``) before it sets ``run.reconcile_observed_at`` as its lastwrite. This finalizer trusts those columns — never Kafka — and CASes the run out of``reconciling`` once every participation has a terminal outcome.++A run that stamped readiness with trailing chunks still unconfirmed moves to ``trailing`` rather+than ``completed``. The seeder scans those days only after they end, and it completes the run when+they confirm."""from collections.abc import Callable@@ -31,6 +35,9 @@ from posthog.tasks.utils import CeleryQueuefrom products.cohorts.backend.backfill.allowlist import parse_run_allowlistfrom products.cohorts.backend.backfill.readiness import stamp_events_readiness, stamp_person_properties_readinessfrom products.cohorts.backend.models.backfill import (+ READINESS_CHUNKS,+ CohortBackfillChunk,+ CohortBackfillChunkStatus,CohortBackfillKind,CohortBackfillRun,CohortBackfillRunCohort,@@ -58,7 +65,7 @@ READINESS_STAMPS_COUNTER = Counter(RUNS_FINALIZED_COUNTER = Counter("posthog_cohort_backfill_runs_finalized_total","Backfill runs terminalized by the finalizer, by terminal status and backfill kind",- ["status", "kind"], # status: "completed", "superseded"; kind: the CohortBackfillKind+ ["status", "kind"], # status: "completed", "trailing", "superseded"; kind: the CohortBackfillKind)# Split by reason: a shortfall is routine backpressure, an error is a crashed pass, and a gated run@@ -85,6 +92,7 @@ HELD_RUNS_GAUGE = Gauge(class FinalizerPass:runs_scanned: int = 0completed: int = 0+ trailing: int = 0superseded: int = 0held: int = 0errored: int = 0@@ -298,7 +306,17 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> boolresult.held += 1return invalidate_team- terminal_status = CohortBackfillRunStatus.COMPLETED if stamped >= 1 else CohortBackfillRunStatus.SUPERSEDED+ if stamped == 0:+ terminal_status = CohortBackfillRunStatus.SUPERSEDED+ elif (+ CohortBackfillChunk.objects.for_team(team_id)+ .filter(~READINESS_CHUNKS, run_id=run.id)+ .exclude(status=CohortBackfillChunkStatus.CONFIRMED)+ .exists()+ ):+ terminal_status = CohortBackfillRunStatus.TRAILING+ else:+ terminal_status = CohortBackfillRunStatus.COMPLETEDtransitioned = (CohortBackfillRun.objects.for_team(team_id).filter(id=run.id, status=CohortBackfillRunStatus.RECONCILING)@@ -307,10 +325,11 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> boolif transitioned:if terminal_status == CohortBackfillRunStatus.COMPLETED:result.completed += 1- RUNS_FINALIZED_COUNTER.labels(status="completed", kind=run.backfill_kind).inc()+ elif terminal_status == CohortBackfillRunStatus.TRAILING:+ result.trailing += 1else:result.superseded += 1- RUNS_FINALIZED_COUNTER.labels(status="superseded", kind=run.backfill_kind).inc()+ RUNS_FINALIZED_COUNTER.labels(status=terminal_status.value, kind=run.backfill_kind).inc()else:# We hold the run row's FOR UPDATE lock, so a missed CAS can only mean our own# readiness stamp superseded a cohort-scoped run inside this transaction —@@ -324,7 +343,7 @@ def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool# a crash between that pass's commit and its post-commit invalidation. (A crash after this# terminal transition commits leaves any staleness bounded by the flags-cache verifier task# and the behavioral-ids cache TTL, in the fail-closed direction.)- if terminal_status == CohortBackfillRunStatus.COMPLETED and stamped >= 1:+ if stamped >= 1:invalidate_team = Truereturn invalidate_teamdiff --git a/products/cohorts/backend/backfill/inventory.py b/products/cohorts/backend/backfill/inventory.pyindex 55773b17d82c..562c26079e60 100644--- a/products/cohorts/backend/backfill/inventory.py+++ b/products/cohorts/backend/backfill/inventory.py@@ -26,6 +26,7 @@ from posthog.dataclasses import frozenfrom products.cohorts.backend.backfill.allowlist import parse_run_allowlistfrom products.cohorts.backend.models.backfill import (ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ READINESS_CHUNKS,CohortBackfillChunk,CohortBackfillChunkStatus,CohortBackfillKind,@@ -249,9 +250,11 @@ def collect_run_inventory(# One relation per query, so each aggregate stays linear in the chunk count. Keyed by run id and# merged back below; runs with no chunks are simply absent and fall back to `_EMPTY_CHUNK_TALLY`.+ # Trailing chunks are left out: no active run waits for them, so counting them would read a run+ # whose readiness chunks are all done as stalled.chunk_tallies = (CohortBackfillChunk.objects.unscoped()- .filter(run_id__in=[run.id for run in runs])+ .filter(READINESS_CHUNKS, run_id__in=[run.id for run in runs]).values("run_id").annotate(chunks_total=Count("id"),diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.pyindex 35f682719005..3d39024f26bb 100644--- a/products/cohorts/backend/backfill/test/test_finalize.py+++ b/products/cohorts/backend/backfill/test/test_finalize.py@@ -17,6 +17,8 @@ from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runsfrom products.cohorts.backend.backfill.finalize import _STAMP_BY_KIND, FLAGS_CACHE_TASK, finalize_backfill_runsfrom products.cohorts.backend.backfill.readiness import ensure_filters_shape_hashfrom products.cohorts.backend.models.backfill import (+ CohortBackfillChunk,+ CohortBackfillChunkStatus,CohortBackfillKind,CohortBackfillRun,CohortBackfillRunCohort,@@ -183,6 +185,33 @@ class TestBackfillFinalizer(BaseTest):self.assertIsNone(cohort.last_backfill_events_at)self.assertIsNone(participation.stamped_at)+ @parameterized.expand(+ [+ ("trailing_day_pending", CohortBackfillChunkStatus.PENDING, CohortBackfillRunStatus.TRAILING),+ ("trailing_day_confirmed", CohortBackfillChunkStatus.CONFIRMED, CohortBackfillRunStatus.COMPLETED),+ ]+ )+ def test_run_stamps_readiness_and_trails_while_a_trailing_day_is_unconfirmed(+ self, _name: str, trailing_status: str, expected_status: str+ ) -> None:+ run, cohorts = self._make_run(["completed"])+ CohortBackfillChunk.objects.for_team(self.team.id).create(+ run=run,+ team_id=self.team.id,+ day=timezone.now().date(),+ status=trailing_status,+ claimable_after=timezone.now() + timedelta(hours=1),+ )++ result = finalize_backfill_runs()++ run.refresh_from_db()+ cohorts[0].refresh_from_db()+ self.assertEqual(run.status, expected_status)+ self.assertEqual(result.completed, int(expected_status == CohortBackfillRunStatus.COMPLETED))+ self.assertEqual(result.trailing, int(expected_status == CohortBackfillRunStatus.TRAILING))+ self.assertIsNotNone(cohorts[0].last_backfill_events_at)+def test_unobserved_run_is_untouched(self) -> None:run, cohorts = self._make_run(["completed"], observed=False)diff --git a/products/cohorts/backend/backfill/test/test_inventory.py b/products/cohorts/backend/backfill/test/test_inventory.pyindex 08b9a1ba6111..efacfce975d1 100644--- a/products/cohorts/backend/backfill/test/test_inventory.py+++ b/products/cohorts/backend/backfill/test/test_inventory.py@@ -257,6 +257,22 @@ class TestCollectRunInventory(BaseTest):self.assertEqual(row.classification, "seeding-stalled")self.assertEqual(row.chunks_failed_exhausted, 1)+ def test_a_held_trailing_chunk_does_not_read_as_a_stall(self) -> None:+ run = self._run()+ long_ago = timezone.now() - timedelta(days=2)+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(chunks_planned_at=long_ago)+ for day, status, claimable_after in [+ (date(2026, 1, 1), CohortBackfillChunkStatus.CONFIRMED, None),+ (date(2026, 1, 2), CohortBackfillChunkStatus.PENDING, timezone.now() + timedelta(hours=1)),+ ]:+ CohortBackfillChunk.objects.for_team(self.team.id).create(+ run=run, team_id=self.team.id, day=day, status=status, claimable_after=claimable_after+ )+ CohortBackfillChunk.objects.for_team(self.team.id).filter(run_id=run.id).update(updated_at=long_ago)++ [row] = collect_run_inventory(stalled_after=STALLED_AFTER)+ self.assertEqual(row.classification, "seeding-healthy")+@override_settings(BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=False)def test_person_runs_held_by_the_readiness_gate_are_kept_off_the_allowlist_line(self) -> None:behavioral = self._run(status=CohortBackfillRunStatus.RECONCILING, observed=True)diff --git a/products/cohorts/backend/management/commands/compare_cohort_membership.py b/products/cohorts/backend/management/commands/compare_cohort_membership.pyindex 9e82b8822c81..25d9db356a85 100644--- a/products/cohorts/backend/management/commands/compare_cohort_membership.py+++ b/products/cohorts/backend/management/commands/compare_cohort_membership.py@@ -138,7 +138,8 @@ RECOMPUTE_CAVEATS = ("over-count (false_members) is the hard gate; the sweep-lag share — still a member one day-slide back, or entered within --grace-minutes — is reported but not gated","under-count segmentation needs a single supported leaf, a monotone op (gte/gt), a backfill run, and a grace window opening after that run's boundary; without them the cohort reports SKIP (parity not established), never PASS","past the per-person read cap the two sides fail differently: over-count keeps scoring every false member hard (FAIL), since over-inclusion is the hard invariant, while under-count drops to unsegmented (SKIP); a cap-driven FAIL is called out in the cohort notes and is not on its own evidence of over-inclusion",- "missing_boundary_day is the expected decaying gap; missing_seed_domain, missing_unseeded_day and missing_post_boundary gate FAIL — raise --grace-minutes to absorb known live-path lag",+ "missing_boundary_day is expected until the run's trailing boundary-day chunk confirms, shortly after the next midnight in the team's timezone, and then those persons count as missing_seed_domain; missing_seed_domain, missing_unseeded_day and missing_post_boundary gate FAIL — raise --grace-minutes to absorb known live-path lag",+ "a confirmed chunk is the seeder's Kafka acknowledgement, and the processor applies its tile only once the live watermark passes the scan instant plus its seed fence margin (10 minutes by default); a comparison in the minutes after the trailing boundary-day chunk confirms reads missing_seed_domain FAILs that a re-run clears","day boundaries use the current team tz, the only tz the processor uses; a run pinned to a different tz SKIPs rather than mis-attributing seed days","the oracle counts only events ingested by --at (the seeder's inserted_at cutoff), so a longer ingestion lag reads as neither over- nor under-count","override/merge drift (fold ids resolved at processing time vs the oracle's current overrides) can pair a false_member with a missing person; a bounded per-class person-id sample ships in the JSON for triage",diff --git a/products/cohorts/backend/migrations/0015_cohortbackfillchunk_claimable_after_and_more.py b/products/cohorts/backend/migrations/0015_cohortbackfillchunk_claimable_after_and_more.pynew file mode 100644index 000000000000..2e31e46225fd--- /dev/null+++ b/products/cohorts/backend/migrations/0015_cohortbackfillchunk_claimable_after_and_more.py@@ -0,0 +1,40 @@+# Generated by Django 5.2.17 on 2026-09-24 23:29++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cohorts", "0014_alter_cohort_created_by_alter_cohort_people_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="cohortbackfillchunk",+ name="claimable_after",+ field=models.DateTimeField(+ blank=True,+ help_text="Set only on a trailing chunk: the run's boundary day, or a later day the live path may have missed the start of. The instant that day ends in the run's timezone, plus a grace period. The Rust seeder never claims the chunk earlier, and the run's readiness does not wait for it. Null means a day before the boundary, claimable now.",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="cohortbackfillrun",+ name="status",+ field=models.CharField(+ choices=[+ ("awaiting_boundary", "Awaiting boundary"),+ ("blocked", "Blocked"),+ ("seeding", "Seeding"),+ ("reconciling", "Reconciling"),+ ("trailing", "Trailing"),+ ("completed", "Completed"),+ ("superseded", "Superseded"),+ ("cancelled", "Cancelled"),+ ("failed", "Failed"),+ ],+ default="awaiting_boundary",+ max_length=32,+ ),+ ),+ ]diff --git a/products/cohorts/backend/migrations/max_migration.txt b/products/cohorts/backend/migrations/max_migration.txtindex 2609fd5433ba..81453f684e1b 100644--- a/products/cohorts/backend/migrations/max_migration.txt+++ b/products/cohorts/backend/migrations/max_migration.txt@@ -1 +1 @@-0014_alter_cohort_created_by_alter_cohort_people_and_more+0015_cohortbackfillchunk_claimable_after_and_morediff --git a/products/cohorts/backend/models/backfill.py b/products/cohorts/backend/models/backfill.pyindex 943fb189b0b1..646bdf70fb78 100644--- a/products/cohorts/backend/models/backfill.py+++ b/products/cohorts/backend/models/backfill.py@@ -28,12 +28,20 @@ class CohortBackfillRunStatus(models.TextChoices):BLOCKED = "blocked", "Blocked"SEEDING = "seeding", "Seeding"RECONCILING = "reconciling", "Reconciling"+ TRAILING = "trailing", "Trailing"COMPLETED = "completed", "Completed"SUPERSEDED = "superseded", "Superseded"CANCELLED = "cancelled", "Cancelled"FAILED = "failed", "Failed"+# `trailing` is not active. Such a run has already stamped readiness and owes only its trailing days,+# which the seeder scans after they end. Their tiles merge with `max`, so a newer run for the same+# cohort cannot conflict with them, and the run holds no uniqueness slot. It also stays out of the+# active-run age gauge, which would otherwise read every wait until the team's midnight as a stall.+# It therefore lands in the derived terminal tuple below: `finished_at` is set when readiness stamps+# and again when the seeder completes the run, so `runs_recent` counts each transition under its+# own status.ACTIVE_COHORT_BACKFILL_RUN_STATUSES = (CohortBackfillRunStatus.AWAITING_BOUNDARY,CohortBackfillRunStatus.BLOCKED,@@ -178,6 +186,16 @@ class CohortBackfillChunk(TeamScopedRootMixin, UUIDModel):"by its retry backoff. Null means claimable now; every claim clears it."),)+ claimable_after = models.DateTimeField(+ null=True,+ blank=True,+ help_text=(+ "Set only on a trailing chunk: the run's boundary day, or a later day the live path may "+ "have missed the start of. The instant that day ends in the run's timezone, plus a grace "+ "period. The Rust seeder never claims the chunk earlier, and the run's readiness does not "+ "wait for it. Null means a day before the boundary, claimable now."+ ),+ )last_error = models.TextField(blank=True, default="")tiles_produced = models.BigIntegerField(default=0)# db_default, not only default: the Rust seeder raw-INSERTs an explicit column list, so a@@ -205,3 +223,9 @@ class CohortBackfillChunk(TeamScopedRootMixin, UUIDModel):constraints = [models.UniqueConstraint(fields=["run", "day", "band"], name="cohort_bfc_run_day_band_uq"),]+++# The chunks a run's readiness waits for. A trailing chunk carries a claim hold, and the seeder scans+# it after readiness stamps, so every readiness query leaves it out. The seeder names the same rule+# `readiness_chunk!()` in `store/completion.rs`.+READINESS_CHUNKS = Q(claimable_after__isnull=True)diff --git a/products/cohorts/backend/parity/oracle.py b/products/cohorts/backend/parity/oracle.pyindex d4b57c5cb4c2..78d0cd79a2e5 100644--- a/products/cohorts/backend/parity/oracle.py+++ b/products/cohorts/backend/parity/oracle.py@@ -31,6 +31,7 @@ from posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.schema_enums import ProductKeyfrom products.cohorts.backend.models.backfill import (+ READINESS_CHUNKS,CohortBackfillChunk,CohortBackfillChunkStatus,CohortBackfillRun,@@ -293,7 +294,10 @@ def load_run_context(team_id: int, cohort_id: int, run_id: Optional[str] = None)confirmed_days = frozenset(day for day, statuses in day_statuses.items() if statuses == {CohortBackfillChunkStatus.CONFIRMED})- non_confirmed = chunks.exclude(status=CohortBackfillChunkStatus.CONFIRMED).count()+ # Only the readiness chunks can leave the seed domain partial: a held trailing chunk is scanned+ # after readiness stamps, and the boundary day it covers is classified as pending until then.+ non_confirmed = chunks.filter(READINESS_CHUNKS).exclude(status=CohortBackfillChunkStatus.CONFIRMED).count()+ trailing_day_planned = chunks.filter(~READINESS_CHUNKS).exists()run_tz = resolve_zoneinfo(run.timezone)return RunContext(@@ -305,4 +309,5 @@ def load_run_context(team_id: int, cohort_id: int, run_id: Optional[str] = None)confirmed_days=confirmed_days,non_confirmed_chunks=non_confirmed,shape_hash_drift=participation_hash != current_hash,+ trailing_day_planned=trailing_day_planned,)diff --git a/products/cohorts/backend/parity/recompute.py b/products/cohorts/backend/parity/recompute.pyindex 8070b0b9d8eb..9084dbe2b061 100644--- a/products/cohorts/backend/parity/recompute.py+++ b/products/cohorts/backend/parity/recompute.py@@ -350,6 +350,7 @@ class RunContext:confirmed_days: frozenset[date] # days whose seed chunks are all CONFIRMED (fully seeded)non_confirmed_chunks: intshape_hash_drift: bool # run's pinned behavioral shape hash != current cohort's+ trailing_day_planned: bool # a held chunk covers the boundary day, so its misses fill instead of decaying@dataclass(frozen=True)@@ -406,12 +407,12 @@ class RecomputeComparison:missing: int = 0 # oracle - members(fold) (under-count)missing_grace: int = 0missing_seed_domain: int = 0 # qualified by confirmed seed days alone — gates FAIL- missing_boundary_day: int = 0 # needs boundary-day pre-boundary events — the decaying gap+ missing_boundary_day: int = 0 # needs boundary-day pre-boundary events — pending the trailing chunkmissing_unseeded_day: int = 0 # needs a pre-boundary window day with no confirmed chunk — FAILmissing_post_boundary: int = 0 # needs post-boundary events the live path owns — gates FAILmissing_unsegmented: int = 0 # shape or grace window admits no segmentation — not adjudicatedmissing_unattributed: int = 0 # in the member set but absent from the day read — reads disagree- expires_by_day: Mapping[str, int] = field(default_factory=dict) # boundary-class decay prediction+ expires_by_day: Mapping[str, int] = field(default_factory=dict) # boundary-class decay, no trailing chunksamples: Mapping[str, tuple[str, ...]] = field(default_factory=dict) # bounded person ids per classrun_id: Optional[str] = Nonerun_status: Optional[str] = None@@ -471,9 +472,9 @@ def _domain_counts() -> DomainCounts:"""Per-domain in-window match counts for one person.- ``seed`` / ``boundary`` / ``unseeded`` partition the pre-boundary window days: boundary-day first- (the seed/live handoff day, even if a chunk exists for it), then confirmed-seed days, then the- rest (window days with no confirmed chunk). The scan and the window share one tz and one range,+ ``seed`` / ``boundary`` / ``unseeded`` partition the pre-boundary window days: confirmed-seed days+ first, including the boundary day once its trailing chunk has confirmed, then the boundary day+ while that chunk is still unconfirmed, then the rest (window days with no confirmed chunk). The scan and the window share one tz and one range,so the out-of-window skip is defensive only — a dropped in-window match would understate thetotal and misfile the person as lag noise."""@@ -485,10 +486,10 @@ def _domain_counts(grace += countelif bucket == _POST_BOUNDARY:post += count- elif day == ctx.boundary_day:- boundary += countelif day in ctx.confirmed_days:seed += count+ elif day == ctx.boundary_day:+ boundary += countelse:unseeded += countreturn DomainCounts(grace=grace, seed=seed, boundary=boundary, unseeded=unseeded, post=post)@@ -517,7 +518,7 @@ def _classify_missing_person(if counts.seed >= min_count:return "missing_seed_domain" # confirmed seed days alone qualify — unexpected, gates FAILif counts.seed + counts.boundary >= min_count:- return "missing_boundary_day" # needs boundary-day pre-boundary events — decaying gap+ return "missing_boundary_day" # needs boundary-day pre-boundary events — pending the trailing chunkif counts.seed + counts.boundary + counts.unseeded >= min_count:return "missing_unseeded_day" # needs an unseeded pre-boundary window day — gates FAILreturn "missing_post_boundary" # needs post-boundary events the live path owns — gates FAIL@@ -648,7 +649,7 @@ def classify_recompute(bucket = _classify_missing_person(matches, window=window, ctx=ctx, min_count=min_count)counts[bucket] += 1per_class[bucket].append(person)- if bucket == "missing_boundary_day":+ if bucket == "missing_boundary_day" and not ctx.trailing_day_planned:day = _expiry_date(matches, window=window, window_days=leaf.window_days, min_count=min_count)if day is not None:expires_by_day[day.isoformat()] += 1diff --git a/products/cohorts/backend/parity/test/test_command_warnings.py b/products/cohorts/backend/parity/test/test_command_warnings.pyindex 4a87c9f41a76..d656c5b6a691 100644--- a/products/cohorts/backend/parity/test/test_command_warnings.py+++ b/products/cohorts/backend/parity/test/test_command_warnings.py@@ -143,6 +143,7 @@ def _ctx(**overrides: Any) -> RunContext:"confirmed_days": frozenset(),"non_confirmed_chunks": 0,"shape_hash_drift": False,+ "trailing_day_planned": False,}defaults.update(overrides)return RunContext(**defaults)diff --git a/products/cohorts/backend/parity/test/test_oracle_run_context.py b/products/cohorts/backend/parity/test/test_oracle_run_context.pyindex 331730127eb7..31e7821257ae 100644--- a/products/cohorts/backend/parity/test/test_oracle_run_context.py+++ b/products/cohorts/backend/parity/test/test_oracle_run_context.py@@ -74,9 +74,11 @@ class TestLoadRunContext(BaseTest):pinned_filters=cohort.filters,)- def _chunk(self, run: CohortBackfillRun, day: date, band: int, status: str) -> None:+ def _chunk(+ self, run: CohortBackfillRun, day: date, band: int, status: str, claimable_after: datetime | None = None+ ) -> None:CohortBackfillChunk.objects.for_team(self.team.id).create(- run=run, team_id=self.team.id, day=day, band=band, status=status+ run=run, team_id=self.team.id, day=day, band=band, status=status, claimable_after=claimable_after)def test_loads_seeding_run_and_confirms_only_fully_seeded_days(self) -> None:@@ -91,6 +93,8 @@ class TestLoadRunContext(BaseTest):self._chunk(run, date(2026, 7, 19), 1, _CONFIRMED)self._chunk(run, date(2026, 7, 20), 0, _CONFIRMED)self._chunk(run, date(2026, 7, 20), 1, _PENDING) # day 20 only partially seeded+ # The boundary day's held trailing chunk: readiness never waits for it, so it is not partial seeding.+ self._chunk(run, date(2026, 7, 21), 0, _PENDING, claimable_after=datetime(2026, 7, 22, 0, 30, tzinfo=UTC))ctx = load_run_context(self.team.id, cohort.id, None)@@ -100,6 +104,7 @@ class TestLoadRunContext(BaseTest):self.assertEqual(ctx.boundary_day, date(2026, 7, 21))self.assertEqual(ctx.confirmed_days, frozenset({date(2026, 7, 19)}))self.assertEqual(ctx.non_confirmed_chunks, 1)+ self.assertTrue(ctx.trailing_day_planned)self.assertFalse(ctx.shape_hash_drift)def test_boundary_day_uses_run_timezone(self) -> None:@@ -113,6 +118,7 @@ class TestLoadRunContext(BaseTest):assert ctx is not Noneself.assertEqual(ctx.run_timezone, "US/Pacific")self.assertEqual(ctx.boundary_day, date(2026, 7, 20))+ self.assertFalse(ctx.trailing_day_planned)def test_shape_hash_drift_when_pinned_hash_differs_from_current(self) -> None:cohort = self._cohort()diff --git a/products/cohorts/backend/parity/test/test_recompute.py b/products/cohorts/backend/parity/test/test_recompute.pyindex 346f9d53dba4..4555c60395ec 100644--- a/products/cohorts/backend/parity/test/test_recompute.py+++ b/products/cohorts/backend/parity/test/test_recompute.py@@ -307,6 +307,7 @@ def _ctx(**overrides: Any) -> RunContext:"confirmed_days": frozenset({date(2026, 7, 17), date(2026, 7, 18)}),"non_confirmed_chunks": 0,"shape_hash_drift": False,+ "trailing_day_planned": False,}defaults.update(overrides)return RunContext(**defaults)@@ -344,7 +345,7 @@ class TestMissingSegmentation(SimpleTestCase):("grace", [_dm(date(2026, 7, 24), "grace")], "missing_grace", "PASS"),# 2026-07-18 is a confirmed seed day -> should have been seeded (gates FAIL).("seed_domain", [_dm(date(2026, 7, 18), "pre_boundary")], "missing_seed_domain", "FAIL"),- # 2026-07-20 is the boundary day, pre-boundary -> the decaying gap.+ # 2026-07-20 is the boundary day, pre-boundary, before its trailing chunk confirms.("boundary_day", [_dm(date(2026, 7, 20), "pre_boundary")], "missing_boundary_day", "PASS"),# 2026-07-19 is a pre-boundary window day with no confirmed chunk (gates FAIL).("unseeded_day", [_dm(date(2026, 7, 19), "pre_boundary")], "missing_unseeded_day", "FAIL"),@@ -365,6 +366,15 @@ class TestMissingSegmentation(SimpleTestCase):self.assertEqual(row.verdict, verdict, name)self.assertEqual(row.samples[expected_field], ("p",))+ def test_a_boundary_day_seeded_by_its_trailing_chunk_gates_like_any_seed_day(self) -> None:+ row = _classify(+ oracle_members={"p"},+ day_counts={"p": [_dm(date(2026, 7, 20), "pre_boundary")]},+ ctx=_ctx(confirmed_days=frozenset({date(2026, 7, 17), date(2026, 7, 18), date(2026, 7, 20)})),+ )+ self.assertEqual(row.missing_seed_domain, 1)+ self.assertEqual(row.verdict, "FAIL")+def test_seed_domain_precedence_over_boundary(self) -> None:# A person qualifying via both a confirmed seed day and the boundary day is a seed-domain miss:# the seeder already covered them, so it gates FAIL rather than being written off as the gap.@@ -463,7 +473,15 @@ class TestExpiryCurve(SimpleTestCase):self.assertEqual(row.missing_boundary_day, 1)self.assertEqual(row.expires_by_day, {"2026-07-26": 1}) # 2026-07-18 + 7 + 1- def test_expiry_counts_group_by_date(self) -> None:+ @parameterized.expand(+ [+ ("decays_with_no_trailing_chunk", False, {"2026-07-28": 2}), # 2026-07-20 + 7 + 1+ ("fills_after_midnight_with_a_trailing_chunk", True, {}),+ ]+ )+ def test_expiry_counts_group_by_date(+ self, _name: str, trailing_day_planned: bool, expected: dict[str, int]+ ) -> None:row = _classify(spec=_spec(window_days=7),oracle_members={"p1", "p2"},@@ -471,8 +489,10 @@ class TestExpiryCurve(SimpleTestCase):"p1": [_dm(date(2026, 7, 20), "pre_boundary")],"p2": [_dm(date(2026, 7, 20), "pre_boundary")],},+ ctx=_ctx(trailing_day_planned=trailing_day_planned),)- self.assertEqual(row.expires_by_day, {"2026-07-28": 2}) # 2026-07-20 + 7 + 1+ self.assertEqual(row.missing_boundary_day, 2)+ self.assertEqual(row.expires_by_day, expected)class TestOpWhitelistParity(SimpleTestCase):diff --git a/products/cohorts/backend/realtime_state.py b/products/cohorts/backend/realtime_state.pyindex bb63843ec314..8fec2e0693da 100644--- a/products/cohorts/backend/realtime_state.py+++ b/products/cohorts/backend/realtime_state.py@@ -32,6 +32,7 @@ from posthog.redis import get_client as get_redis_clientfrom products.cohorts.backend.models.backfill import (ACTIVE_COHORT_BACKFILL_RUN_STATUSES,+ READINESS_CHUNKS,CohortBackfillChunk,CohortBackfillChunkStatus,CohortBackfillRun,@@ -234,7 +235,7 @@ def _chunk_tallies(team_id: int, run_ids: Sequence[UUID]) -> dict[UUID, dict[strreturn {}tallies = (CohortBackfillChunk.objects.for_team(team_id, canonical=True)- .filter(run_id__in=run_ids)+ .filter(READINESS_CHUNKS, run_id__in=run_ids).values("run_id").annotate(chunks_total=Count("id"),diff --git a/products/cohorts/backend/test/test_realtime_state.py b/products/cohorts/backend/test/test_realtime_state.pyindex 7ff54360d4e8..617487add72d 100644--- a/products/cohorts/backend/test/test_realtime_state.py+++ b/products/cohorts/backend/test/test_realtime_state.py@@ -301,6 +301,13 @@ class TestRealtimeReadiness(BaseTest):run = self._run(cohort=cohort)self._participate(run, cohort)self._chunks(run, total=4, confirmed=1)+ # Readiness does not wait for a held trailing day, so it is no part of the scan's progress.+ CohortBackfillChunk.objects.for_team(self.team.id).create(+ run=run,+ team_id=self.team.id,+ day=timezone.now().date() + timedelta(days=1),+ claimable_after=timezone.now() + timedelta(hours=1),+ )build = resolve_realtime_readiness([cohort])[cohort.id].buildassert build is not Nonediff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rsindex 40f5dd509571..6c04c242dd6a 100644--- a/rust/cohort-seeder/src/app/mod.rs+++ b/rust/cohort-seeder/src/app/mod.rs@@ -27,6 +27,32 @@ pub use prime::prime_zero_series;pub use settings::{OrchestratorSettings, PersonSettings};pub use watch::{MarkerWatchTask, PgMarkerFlush, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE};+/// Discover and prepare every run the poll arm would work on, and report the claim-eligible ids.+///+/// A test that calls `discover_runs` and `establish_boundary` directly proves nothing about+/// `prepare`, which is private to this module and is where a resumed run can silently drop out of+/// the claim loop.+#[cfg(feature = "pg-test-support")]+#[doc(hidden)]+pub async fn eligible_run_ids(+ pool: &sqlx::PgPool,+ store: &crate::store::chunks::PgChunkStore,+ allowlist: &common_types::cohort::TeamAllowlist,+ kinds: &[crate::store::runs::RunKind],+) -> Vec<crate::domain::RunId> {+ let mut reported_runs = std::collections::HashSet::new();+ let outcome = prepare::refresh_runs(+ pool,+ store,+ allowlist,+ kinds,+ crate::domain::PlanCaps::default(),+ &mut reported_runs,+ )+ .await;+ outcome.eligible.keys().cloned().collect()+}+/// Fail a claimed chunk through the executor's recovery path, and report the wait it drew.////// The store's `fail` takes the delay as an argument, so a test that calls it directly pins nothingdiff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rsindex 47fe5e576646..3eb73fbc8678 100644--- a/rust/cohort-seeder/src/app/orchestrator.rs+++ b/rust/cohort-seeder/src/app/orchestrator.rs@@ -23,7 +23,7 @@ use crate::observability::metrics::{CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLAIMED, RUNS_FAILED_EXHAUSTED_CHUNKS,};use crate::store::chunks::{Claim, PgChunkStore};-use crate::store::runs::{fail_run, RunError, RunKind};+use crate::store::runs::{complete_trailing_runs, fail_run, RunError, RunKind};use crate::store::{Claimant, MaxAttempts, RenderedError};use super::completion::CompletionDriver;@@ -191,6 +191,7 @@ impl SeederOrchestrator {// and before the completion driver's tick, so a run can never be failed and// CAS'd to `reconciling` in the same pass.self.fail_exhausted_runs(&eligible_runs).await;+ self.complete_trailing_runs(&eligible_runs).await;self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown).await;if let Some(driver) = &self.completion_driver {@@ -289,14 +290,15 @@ impl SeederOrchestrator {/// Terminalize runs holding a chunk that exhausted its retry budget, one kind at a time.///- /// Such a chunk is never reclaimed again, and the completion CAS demands every chunk+ /// Such a chunk is never reclaimed again, and the completion CAS demands every readiness chunk/// `confirmed`, so without this the run sits in `seeding` forever and holds its cohort's/// uniqueness slot — no future run for that cohort can ever be created. Failing it frees the- /// slot (Django does not count `failed` as active) and puts the reason in `runs.error`.+ /// slot (Django does not count `failed` as active) and puts the reason in `runs.error`. A+ /// `trailing` run's exhausted chunk fails it the same way, so the run does not trail forever.////// Nothing has to be unwound for chunks still mid-scan: their heartbeat and the claim predicate- /// both join `runs.status = 'seeding'`, so they lose their lease on the next beat and halt- /// cleanly — the same mechanism a Django-side supersede already relies on.+ /// both join a `seeding` or `trailing` run status, so they lose their lease on the next beat+ /// and halt cleanly — the same mechanism a Django-side supersede already relies on.async fn fail_exhausted_runs(&self, eligible_runs: &HashMap<RunId, PreparedRun>) {for kind in [RunKind::Behavioral, RunKind::PersonProperty] {let run_ids = run_ids_of_kind(eligible_runs, kind);@@ -314,6 +316,17 @@ impl SeederOrchestrator {}}+ /// Complete the trailing runs whose trailing days have all confirmed. Only behavioral runs plan+ /// trailing days.+ async fn complete_trailing_runs(&self, eligible_runs: &HashMap<RunId, PreparedRun>) {+ let run_ids = run_ids_of_kind(eligible_runs, RunKind::Behavioral);+ match complete_trailing_runs(&self.pool, &run_ids).await {+ Ok(0) => {}+ Ok(completed) => info!(completed, "completed trailing runs"),+ Err(error) => warn!(error = %error, "completing trailing runs failed"),+ }+ }+/// Claim work for whichever kind still has slot capacity. The claimable run-id set is/// recomputed per claim from the remaining capacity, so a person chunk can never occupy a/// behavioral slot (or vice versa) — the two budgets are independent by construction.diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rsindex eb20c9bb013b..159e9c6ee2ed 100644--- a/rust/cohort-seeder/src/app/prepare.rs+++ b/rust/cohort-seeder/src/app/prepare.rs@@ -31,7 +31,7 @@ use crate::store::chunks::{PgChunkStore, PlanOutcome};use crate::store::completion::{mark_chunks_planned, read_planning_stamp, PlanningStampOutcome};use crate::store::runs::{discover_runs, establish_boundary, fail_run, record_run_warning, BoundaryOutcome,- DiscoveredRun, RunError, RunKind, RunStatus, RunWarningNote, SeedableRun,+ DiscoveredRun, RunError, RunKind, RunStatus, RunWarningNote, SeedPhase, SeedableRun,};use crate::store::RenderedError;@@ -202,6 +202,7 @@ async fn prepare_behavioral(boundary: SeedableRun,) -> PrepareOutcome {let run_id = boundary.run_id;+ let phase = boundary.phase;let validated = match boundary.load_pinned(pool).await {Ok(validated) => validated,Err(error) => {@@ -218,6 +219,11 @@ async fn prepare_behavioral(counter!(LOOKBACK_TRUNCATED).increment(1);}}+ match phase {+ SeedPhase::Seeding => {}+ // Every day was planned while the run was seeding, and its readiness is already stamped.+ SeedPhase::Trailing => return eligible_behavioral(validated.run, analyses),+ }if validated.warnings.iter()@@ -240,8 +246,14 @@ async fn prepare_behavioral(stamp_planning(pool, run_id, RunKind::Behavioral).await;return PrepareOutcome::NoChunks;}+ let planned = days.into_iter().map(|day| {+ validated+ .run+ .boundary+ .schedule(day, plan_caps.trailing_day_grace)+ });match store- .plan_chunks(validated.run.run_id, days, plan_caps.bands_per_day)+ .plan_chunks(validated.run.run_id, planned, plan_caps.bands_per_day).await{Ok(PlanOutcome::Planned { inserted }) => {@@ -263,8 +275,12 @@ async fn prepare_behavioral(return PrepareOutcome::Skipped;}}+ eligible_behavioral(validated.run, analyses)+}++fn eligible_behavioral(run: PinnedRun, analyses: ConditionAnalyses) -> PrepareOutcome {PrepareOutcome::Eligible(PreparedRun::Behavioral(Arc::new(PreparedBehavioral {- run: validated.run,+ run,analyses,})))}diff --git a/rust/cohort-seeder/src/app/settings.rs b/rust/cohort-seeder/src/app/settings.rsindex f34933603f23..9ce9afd364c0 100644--- a/rust/cohort-seeder/src/app/settings.rs+++ b/rust/cohort-seeder/src/app/settings.rs@@ -77,6 +77,8 @@ impl OrchestratorSettings {retry_backoff: RetryBackoffPolicy,max_lookback_days: u32,bands_per_day: u16,+ live_tracking_lag: Duration,+ trailing_day_grace: Duration,producer: ProducerSettings,person: Option<PersonSettings>,) -> Result<Self, OrchestratorSettingsError> {@@ -110,6 +112,8 @@ impl OrchestratorSettings {plan_caps: PlanCaps {max_lookback_days,bands_per_day,+ live_tracking_lag,+ trailing_day_grace,},producer,person,@@ -183,6 +187,8 @@ impl TryFrom<&Config> for OrchestratorSettings {retry_backoff,config.seeder_max_lookback_days,config.seeder_bands_per_day,+ Duration::from_secs(config.seeder_live_tracking_lag_secs),+ Duration::from_secs(config.seeder_trailing_day_grace_secs),producer,person,)?)@@ -315,6 +321,8 @@ mod tests {backoff(),400,1,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -329,6 +337,8 @@ mod tests {backoff(),400,1,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -343,6 +353,8 @@ mod tests {backoff(),400,1,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -357,6 +369,8 @@ mod tests {backoff(),400,1,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -371,6 +385,8 @@ mod tests {backoff(),400,1,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -385,6 +401,8 @@ mod tests {backoff(),400,0,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -399,6 +417,8 @@ mod tests {backoff(),400,u16::MAX,+ Duration::ZERO,+ Duration::ZERO,producer_settings(),None,),@@ -511,6 +531,14 @@ mod tests {let settings = OrchestratorSettings::try_from(&config).unwrap();assert_eq!(settings.retry_backoff.base(), Duration::from_secs(30));assert_eq!(settings.retry_backoff.cap(), Duration::from_secs(1800));+ assert_eq!(+ settings.plan_caps.live_tracking_lag,+ Duration::from_secs(420)+ );+ assert_eq!(+ settings.plan_caps.trailing_day_grace,+ Duration::from_secs(1800)+ );let mut zero_base = config.clone();zero_base.seeder_retry_backoff_base_secs = 0;diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rsindex c6d326e0ab0e..7d39578cb363 100644--- a/rust/cohort-seeder/src/clickhouse/scanner.rs+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs@@ -657,13 +657,7 @@ mod tests {const HASH: &str = "aaaaaaaaaaaaaaaa";fn domain() -> SeedDomain {- SeedDomain::new(- 1,- Boundary::new(UtcMillis::new(2 * 86_400_000), UTC),- UTC,- SChunkMs(200_000_000),- )- .unwrap()+ SeedDomain::new(1, UTC, SChunkMs(200_000_000)).unwrap()}fn filters() -> TeamFilters {@@ -1004,11 +998,12 @@ mod tests {}/// Disaster-recovery shape: the boundary is a past instant, so the scan runs days after the- /// plan was anchored. Every pre-boundary day still inside the wall-clock window must stay- /// admitted (those days feed membership the live replay cannot reconstruct); days that slid- /// out of every window are skipped, matching the consumer's drop-below-window apply rule.+ /// plan was anchored. Every planned day still inside the wall-clock window must stay admitted+ /// (the days before the boundary feed membership the live replay cannot reconstruct, and the+ /// boundary day holds events from before the replay resumed); days that slid out of every+ /// window are skipped, matching the consumer's drop-below-window apply rule.#[test]- fn dr_scan_admits_every_pre_boundary_day_still_inside_the_window() {+ fn dr_scan_admits_every_planned_day_still_inside_the_window() {let hash = ConditionHash::parse(HASH).unwrap();let conditions = [PinnedCondition {cohort_id: CohortId(1),@@ -1018,7 +1013,7 @@ mod tests {}];let boundary = Boundary::new(UtcMillis::new(100 * 86_400_000), UTC);let planned = plan_days(&conditions, boundary, &PlanCaps::default());- assert_eq!(planned, BTreeSet::from_iter(93..=99));+ assert_eq!(planned, BTreeSet::from_iter(93..=100));let admitted_at = |now_day: i64| {planned@@ -1031,12 +1026,12 @@ mod tests {.collect::<Vec<_>>()};// Scanned the boundary day (enablement shape): every planned day is admitted.- assert_eq!(admitted_at(100), (93..=99).collect::<Vec<_>>());+ assert_eq!(admitted_at(100), (93..=100).collect::<Vec<_>>());// Scanned three days later (DR shape): the window is [96, 103]; days 93-95 can no longer- // affect any evaluation and are skipped, days 96-99 are still scanned.- assert_eq!(admitted_at(103), (96..=99).collect::<Vec<_>>());- // Boundary older than the window: live replay from the boundary covers the whole window,- // so the seed correctly has nothing left to contribute.- assert_eq!(admitted_at(107), Vec::<DayIdx>::new());+ // affect any evaluation and are skipped, days 96-100 are still scanned.+ assert_eq!(admitted_at(103), (96..=100).collect::<Vec<_>>());+ // Boundary day older than the window: live replay from the boundary covers the whole+ // window, so the seed correctly has nothing left to contribute.+ assert_eq!(admitted_at(108), Vec::<DayIdx>::new());}}diff --git a/rust/cohort-seeder/src/clickhouse/sql.rs b/rust/cohort-seeder/src/clickhouse/sql.rsindex 0556a8bcf205..b7f235c57c2a 100644--- a/rust/cohort-seeder/src/clickhouse/sql.rs+++ b/rust/cohort-seeder/src/clickhouse/sql.rs@@ -215,7 +215,7 @@ mod tests {use chrono_tz::UTC;use super::*;- use crate::domain::{Boundary, SChunkMs, SeedDomain, UtcMillis};+ use crate::domain::{SChunkMs, SeedDomain};/// The rendered scan for a spec, wide.fn full_sql(spec: &ScanSpec) -> String {@@ -247,13 +247,7 @@ mod tests {}fn domain() -> SeedDomain {- SeedDomain::new(- 1,- Boundary::new(UtcMillis::new(2 * 86_400_000), UTC),- UTC,- SChunkMs(200_000_000),- )- .unwrap()+ SeedDomain::new(1, UTC, SChunkMs(200_000_000)).unwrap()}fn spec(event_names: Vec<String>, band: BandSpec) -> ScanSpec {diff --git a/rust/cohort-seeder/src/config.rs b/rust/cohort-seeder/src/config.rsindex f153136783ce..ee9bb6d31980 100644--- a/rust/cohort-seeder/src/config.rs+++ b/rust/cohort-seeder/src/config.rs@@ -208,6 +208,19 @@ pub struct Config {#[envconfig(default = "1")]pub seeder_bands_per_day: u16,+ /// How long after a run's boundary the stream processor may take to start counting a new cohort+ /// leaf. Keep it at least the processor's `FILTER_CATALOG_REFRESH_SECS` plus+ /// `FILTER_CATALOG_REFRESH_JITTER_SECS`. The seeder plans every day this reaches as a trailing+ /// day, so a boundary set just before midnight also seeds the minutes the live path missed of+ /// the next day.+ #[envconfig(default = "420")]+ pub seeder_live_tracking_lag_secs: u64,++ /// How long the seeder waits after a trailing day ends, in the run's timezone, before it scans+ /// that day. An event ingested for the day after the scan is missing from its tile.+ #[envconfig(default = "1800")]+ pub seeder_trailing_day_grace_secs: u64,+/// Enable the person-property seed path: discovery widens to `person_property` runs and the/// planning/scan/emission pipeline arms. Default off — the processor's decode arm and/// `COHORT_SEED_PERSON_APPLY_ENABLED` must be deployed everywhere first, or an old processordiff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rsindex c18b26536f30..110cb5b2a061 100644--- a/rust/cohort-seeder/src/domain/aggregate.rs+++ b/rust/cohort-seeder/src/domain/aggregate.rs@@ -276,7 +276,7 @@ mod tests {use serde_json::json;use super::*;- use crate::domain::{Boundary, SChunkMs, UtcMillis};+ use crate::domain::SChunkMs;const HASH_A: &str = "aaaaaaaaaaaaaaaa";const HASH_B: &str = "bbbbbbbbbbbbbbbb";@@ -373,8 +373,7 @@ mod tests {}fn domain() -> SeedDomain {- let boundary = Boundary::new(UtcMillis::new(20 * 86_400_000), UTC);- SeedDomain::new(19, boundary, UTC, SChunkMs(boundary.at_ms().as_i64())).unwrap()+ SeedDomain::new(19, UTC, SChunkMs(20 * 86_400_000)).unwrap()}#[test]diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rsindex eb82e757edbc..a193a180fd25 100644--- a/rust/cohort-seeder/src/domain/mod.rs+++ b/rust/cohort-seeder/src/domain/mod.rs@@ -73,4 +73,4 @@ pub use pinned::{};pub use plan::{bands_for_day, conditions_active_on, plan_days, ActiveConditions};pub use projection::{BlobSource, ChunkProjection, ColumnPlan, ProjectedKeys, ScalarColumn};-pub use window::{Boundary, DomainError, PlanCaps, SeedDomain};+pub use window::{Boundary, DaySchedule, DomainError, PlanCaps, PlannedDay, SeedDomain};diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rsindex fcb93d488940..b1e57c5e165f 100644--- a/rust/cohort-seeder/src/domain/pinned.rs+++ b/rust/cohort-seeder/src/domain/pinned.rs@@ -77,9 +77,9 @@ pub struct ValidatedPinnedRun {pub warnings: Vec<PinnedWarning>,}-/// A run proven `seeding` with an established boundary, ready for pinned-payload validation. The-/// `trigger`/`boundary_at_ms` are already typed and present — the store performs the sole-/// `Option`→value narrowing before building this.+/// A run proven `seeding` or `trailing` with an established boundary, ready for pinned-payload+/// validation. The `trigger`/`boundary_at_ms` are already typed and present — the store performs+/// the sole `Option`→value narrowing before building this.#[derive(Debug)]pub struct PinnedRunSnapshot {pub run_id: RunId,@@ -396,12 +396,7 @@ impl PinnedRun {pinned_team_id: self.team_id.0,});}- Ok(SeedDomain::new(- spec.day,- self.boundary,- self.tz,- spec.s_chunk,- )?)+ Ok(SeedDomain::new(spec.day, self.tz, spec.s_chunk)?)}}diff --git a/rust/cohort-seeder/src/domain/plan.rs b/rust/cohort-seeder/src/domain/plan.rsindex a03c7208b326..d671708ee7d0 100644--- a/rust/cohort-seeder/src/domain/plan.rs+++ b/rust/cohort-seeder/src/domain/plan.rs@@ -35,6 +35,8 @@ impl ActiveConditions {}}+/// Every day the run seeds, through the last day the live path may have missed the start of.+/// [`Boundary::schedule`] decides when each one may be scanned.pub fn plan_days(conditions: &[PinnedCondition],boundary: Boundary,@@ -44,6 +46,7 @@ pub fn plan_days(let Some(last_historical_day) = boundary.day().checked_sub(1) else {return days;};+ let last_seedable_day = boundary.last_seedable_day(caps.live_tracking_lag);let capped_start = window_start_for_now(boundary.day(), caps.max_lookback_days);for condition in conditions {@@ -55,9 +58,10 @@ pub fn plan_days(}(window_start_for_now(boundary.day(), effective_days),- last_historical_day,+ last_seedable_day,)}+ // The processor discards sub-day tiles, and a sub-day gap closes within a day anyway.Lookback::SubDay => {if caps.max_lookback_days == 0 {continue;@@ -68,9 +72,7 @@ pub fn plan_days(// in the past would otherwise plan one chunk per day since that date, unbounded.Lookback::FixedRange { from_day, to_day } => (from_day.unwrap_or(capped_start).max(capped_start),- to_day- .unwrap_or(last_historical_day)- .min(last_historical_day),+ to_day.unwrap_or(last_seedable_day).min(last_seedable_day),),};if start > end {@@ -111,6 +113,8 @@ pub fn bands_for_day(_day: DayIdx, bands_per_day: NonZeroU16) -> Vec<Band> {#[cfg(test)]mod tests {+ use std::time::Duration;+use chrono_tz::UTC;use cohort_core::filters::CohortId;use proptest::prelude::*;@@ -170,6 +174,40 @@ mod tests {assert_eq!(plan_days(&conditions, boundary, &caps), expected);}+ #[test]+ fn open_ended_lookbacks_plan_through_the_last_day_the_live_path_may_have_missed() {+ let caps = PlanCaps {+ live_tracking_lag: Duration::from_secs(420),+ ..PlanCaps::default()+ };+ let boundary_at = |seconds_into_day_100: i64| {+ Boundary::new(+ UtcMillis::new((100 * 86_400 + seconds_into_day_100) * 1000),+ UTC,+ )+ };+ for lookback in [+ Lookback::SlidingDays(2),+ Lookback::FixedRange {+ from_day: Some(98),+ to_day: None,+ },+ ] {+ let conditions = [condition("condition0000000", lookback)];+ assert_eq!(+ plan_days(&conditions, boundary_at(12 * 3_600), &caps),+ BTreeSet::from([98, 99, 100]),+ "{lookback:?} at noon"+ );+ // The live path may start counting after midnight, so the next day is trailing too.+ assert_eq!(+ plan_days(&conditions, boundary_at(86_400 - 300), &caps),+ BTreeSet::from([98, 99, 100, 101]),+ "{lookback:?} five minutes before midnight"+ );+ }+ }+#[test]fn bands_fan_out_zero_indexed() {assert_eq!(bands_for_day(0, NonZeroU16::MIN), vec![Band(0)]);@@ -204,6 +242,7 @@ mod tests {fn planned_days_are_deterministic_and_stay_inside_the_capped_history(boundary_day in -20_000i32..20_000,cap in 0u16..500,+ live_lag_secs in 0u64..200_000,windows in prop::collection::vec(0u16..1_000, 0..20),ranges in prop::collection::vec((prop::option::of(-30_000i32..30_000), prop::option::of(-30_000i32..30_000)),@@ -222,12 +261,17 @@ mod tests {.enumerate().map(|(index, lookback)| condition(&format!("{index:016}"), lookback)).collect::<Vec<_>>();- let caps = PlanCaps { max_lookback_days: u32::from(cap), ..PlanCaps::default() };+ let caps = PlanCaps {+ max_lookback_days: u32::from(cap),+ live_tracking_lag: Duration::from_secs(live_lag_secs),+ ..PlanCaps::default()+ };let first = plan_days(&conditions, boundary, &caps);let second = plan_days(&conditions, boundary, &caps);prop_assert_eq!(&first, &second);let lower = window_start_for_now(boundary.day(), u32::from(cap));- prop_assert!(first.iter().all(|day| lower <= *day && *day < boundary.day()));+ let upper = boundary.last_seedable_day(caps.live_tracking_lag);+ prop_assert!(first.iter().all(|day| lower <= *day && *day <= upper));}}}diff --git a/rust/cohort-seeder/src/domain/window.rs b/rust/cohort-seeder/src/domain/window.rsindex f4f28365016a..dc627b962dde 100644--- a/rust/cohort-seeder/src/domain/window.rs+++ b/rust/cohort-seeder/src/domain/window.rs@@ -2,6 +2,7 @@//! with validity proven in the constructors. Depends on `ids` and `cohort-core`'s tz math.use std::num::NonZeroU16;+use std::time::Duration;use chrono_tz::Tz;use cohort_core::{day_idx_in_tz, start_of_day_ms_in_tz};@@ -11,6 +12,7 @@ use super::ids::{DayIdx, SChunkMs, UtcMillis, UtcMsRange, UtcRangeError};#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct Boundary {at_ms: UtcMillis,+ tz: Tz,day: DayIdx,}@@ -18,6 +20,7 @@ impl Boundary {pub fn new(at_ms: UtcMillis, tz: Tz) -> Self {Self {at_ms,+ tz,day: day_idx_in_tz(at_ms.as_i64(), tz),}}@@ -29,6 +32,51 @@ impl Boundary {pub const fn day(self) -> DayIdx {self.day}++ /// The last day the live path may have missed the start of. The processor starts counting a new+ /// leaf when its catalog next loads, up to `live_lag` after the boundary, and that instant can+ /// fall past the team's midnight.+ pub fn last_seedable_day(self, live_lag: Duration) -> DayIdx {+ day_idx_in_tz(+ self.at_ms.as_i64().saturating_add(millis(live_lag)),+ self.tz,+ )+ }++ /// When the seeder may scan `day`. A day from the boundary day on is scanned only after it ends,+ /// because a tile is the day's absolute count only once nothing more can land in it.+ pub fn schedule(self, day: DayIdx, grace: Duration) -> PlannedDay {+ let schedule = if day < self.day {+ DaySchedule::Historical+ } else {+ DaySchedule::Trailing {+ claimable_after: UtcMillis::new(+ start_of_day_ms_in_tz(day + 1, self.tz).saturating_add(millis(grace)),+ ),+ }+ };+ PlannedDay { day, schedule }+ }+}++/// A day a run seeds, with when the seeder may scan it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PlannedDay {+ pub day: DayIdx,+ pub schedule: DaySchedule,+}++/// When the seeder may scan a planned day, which also decides whether the run's readiness waits for+/// it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DaySchedule {+ /// A day before the boundary day. It has ended by the time the boundary is set, so it is+ /// claimable at once, and readiness waits for it.+ Historical,+ /// The boundary day, or a later day the live path may have missed the start of. The seeder+ /// claims it only after `claimable_after`, and readiness does not wait for it: the run stamps+ /// readiness first and seeds these days afterwards.+ Trailing { claimable_after: UtcMillis },}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -37,6 +85,12 @@ pub struct PlanCaps {/// Bands each planned day is split into: the scan hashes persons via `cityHash64 % bands`, so/// one chunk's in-memory aggregate holds roughly `uniq(person, condition) / bands` entries.pub bands_per_day: NonZeroU16,+ /// How long after the boundary the live path may start counting a new leaf. Every day it can+ /// reach is planned as a trailing day.+ pub live_tracking_lag: Duration,+ /// How long after a trailing day ends the seeder waits before it scans the day, so that events+ /// ingested late for that day are in the tile.+ pub trailing_day_grace: Duration,}impl Default for PlanCaps {@@ -44,6 +98,8 @@ impl Default for PlanCaps {Self {max_lookback_days: 400,bands_per_day: NonZeroU16::MIN,+ live_tracking_lag: Duration::ZERO,+ trailing_day_grace: Duration::ZERO,}}}@@ -57,23 +113,17 @@ pub struct SeedDomain {}impl SeedDomain {- pub fn new(- day: DayIdx,- boundary: Boundary,- tz: Tz,- s_chunk: SChunkMs,- ) -> Result<Self, DomainError> {- if day >= boundary.day {- return Err(DomainError::AtOrAfterBoundary {- day,- boundary_day: boundary.day,- });- }+ /// Refuses a day that has not ended at `s_chunk`. Its tile would be a partial count, and a+ /// confirmed chunk is never scanned again, so the day would stay short for the whole window.+ pub fn new(day: DayIdx, tz: Tz, s_chunk: SChunkMs) -> Result<Self, DomainError> {let next_day = day.checked_add(1).ok_or(DomainError::DayOverflow(day))?;let range = UtcMsRange::new(UtcMillis::new(start_of_day_ms_in_tz(day, tz)),UtcMillis::new(start_of_day_ms_in_tz(next_day, tz)),)?;+ if range.end().as_i64() > s_chunk.0 {+ return Err(DomainError::NotElapsed { day, s_chunk });+ }Ok(Self {day,tz,@@ -105,14 +155,18 @@ impl SeedDomain {#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]pub enum DomainError {- #[error("seed day {day} is not before boundary day {boundary_day}")]- AtOrAfterBoundary { day: DayIdx, boundary_day: DayIdx },+ #[error("seed day {day} has not ended at the chunk's scan instant {s_chunk:?}")]+ NotElapsed { day: DayIdx, s_chunk: SChunkMs },#[error("seed day {0} has no representable successor")]DayOverflow(DayIdx),#[error(transparent)]InvalidUtcRange(#[from] UtcRangeError),}+fn millis(duration: Duration) -> i64 {+ i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)+}+#[cfg(test)]mod tests {use chrono::{NaiveDate, TimeZone, Utc};@@ -123,35 +177,25 @@ mod tests {use super::*;- #[test]- fn seed_domain_excludes_the_boundary_day_and_uses_dst_exact_half_open_ranges() {- let spring_day = day_idx_in_tz(+ fn new_york_spring_forward_day() -> DayIdx {+ day_idx_in_tz(Utc.with_ymd_and_hms(2026, 3, 8, 12, 0, 0).unwrap().timestamp_millis(),New_York,- );- let boundary = Boundary::new(- UtcMillis::new(start_of_day_ms_in_tz(spring_day + 1, New_York)),- New_York,- );+ )+ }++ #[test]+ fn seed_domain_admits_a_day_only_once_it_has_ended_and_uses_dst_exact_half_open_ranges() {+ let spring_day = new_york_spring_forward_day();+ let end = start_of_day_ms_in_tz(spring_day + 1, New_York);assert!(matches!(- SeedDomain::new(- boundary.day(),- boundary,- New_York,- SChunkMs(boundary.at_ms().as_i64())- ),- Err(DomainError::AtOrAfterBoundary { .. })+ SeedDomain::new(spring_day, New_York, SChunkMs(end - 1)),+ Err(DomainError::NotElapsed { .. })));- let domain = SeedDomain::new(- spring_day,- boundary,- New_York,- SChunkMs(boundary.at_ms().as_i64()),- )- .unwrap();+ let domain = SeedDomain::new(spring_day, New_York, SChunkMs(end)).unwrap();let range = domain.utc_range();let (start, end) = (range.start().as_i64(), range.end().as_i64());assert_eq!(end - start, 23 * 3_600_000);@@ -160,6 +204,41 @@ mod tests {assert!(!domain.contains(UtcMillis::new(end)));}+ #[test]+ fn schedule_holds_days_from_the_boundary_day_until_their_local_midnight_plus_grace() {+ let spring_day = new_york_spring_forward_day();+ let boundary = Boundary::new(+ UtcMillis::new(+ Utc.with_ymd_and_hms(2026, 3, 8, 17, 8, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ New_York,+ );+ let grace = Duration::from_secs(30 * 60);++ assert_eq!(+ boundary.schedule(spring_day - 1, grace).schedule,+ DaySchedule::Historical+ );+ // New York is on EDT after the spring-forward, so its next midnight is 04:00 UTC.+ let after_midnight = |day, hour| DaySchedule::Trailing {+ claimable_after: UtcMillis::new(+ Utc.with_ymd_and_hms(2026, 3, day, hour, 30, 0)+ .unwrap()+ .timestamp_millis(),+ ),+ };+ assert_eq!(+ boundary.schedule(spring_day, grace).schedule,+ after_midnight(9, 4)+ );+ assert_eq!(+ boundary.schedule(spring_day + 1, grace).schedule,+ after_midnight(10, 4)+ );+ }+#[test]fn skipped_civil_day_is_vacuous_without_truncating_its_neighbors() {let day = |year, month, day| {@@ -168,17 +247,12 @@ mod tests {let preceding = day(2011, 12, 29);let skipped = day(2011, 12, 30);let following = day(2011, 12, 31);- let boundary = Boundary::new(- UtcMillis::new(- Utc.with_ymd_and_hms(2012, 1, 2, 0, 0, 0)- .unwrap()- .timestamp_millis(),- ),- Apia,+ let s_chunk = SChunkMs(+ Utc.with_ymd_and_hms(2012, 1, 2, 0, 0, 0)+ .unwrap()+ .timestamp_millis(),);- let domain = |day| {- SeedDomain::new(day, boundary, Apia, SChunkMs(boundary.at_ms().as_i64())).unwrap()- };+ let domain = |day| SeedDomain::new(day, Apia, s_chunk).unwrap();let preceding_domain = domain(preceding);let skipped_domain = domain(skipped);@@ -235,11 +309,8 @@ mod tests {Utc.with_ymd_and_hms(2026, 3, 8, 7, 0, 0).unwrap().timestamp_millis()};let day = day_idx_in_tz(center, New_York);- let boundary = Boundary::new(- UtcMillis::new(start_of_day_ms_in_tz(day + 2, New_York)),- New_York,- );- let domain = SeedDomain::new(day, boundary, New_York, SChunkMs(center)).unwrap();+ let s_chunk = SChunkMs(start_of_day_ms_in_tz(day + 2, New_York));+ let domain = SeedDomain::new(day, New_York, s_chunk).unwrap();let timestamp = center + delta_minutes * 60_000;prop_assert_eq!(domain.contains(UtcMillis::new(timestamp)), day_idx_in_tz(timestamp, New_York) == day);}diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rsindex d48656ade587..300ae905394a 100644--- a/rust/cohort-seeder/src/store/chunks.rs+++ b/rust/cohort-seeder/src/store/chunks.rs@@ -1,8 +1,8 @@//! The day-chunk claim/CAS ledger in PostgreSQL: the sole owner of the `cohort_backfill_chunks` SQL.//!-//! Written chunk statuses bind [`ChunkStatus::as_str`] as a parameter; the one multi-status `IN`-//! predicate is hoisted into [`ACTIVE_STATUSES_SQL`], scanned by a unit test through-//! [`ChunkStatus::from_str`] so the SQL vocabulary can never drift from the enum.+//! Written chunk statuses bind [`ChunkStatus::as_str`] as a parameter; the multi-status `IN`+//! predicates are hoisted into [`ACTIVE_STATUSES_SQL`] and [`SEEDABLE_RUN_STATUSES_SQL`], each+//! scanned by a unit test through the enum's `from_str` so the SQL vocabulary can never drift.//! Every claim charges an attempt (saturating at the cap) and bumps the fencing `claim_epoch`;//! expired `produced` leases are reclaimable without an attempt cap (their tiles are already in//! Kafka and must reach `confirmed`), while expired `scanning` leases are capped and dead-lettered@@ -11,7 +11,7 @@//! [`PgChunkStore::fail`] stamped, which is the only claim arm that reads `next_attempt_at`.//! Depends on `domain` (the pure chunk states it mints and the typed ids) and nothing above.-use chrono::NaiveDate;+use chrono::{DateTime, NaiveDate, Utc};use cohort_core::filters::TeamId;use cohort_core::{day_idx_of_naive_date, DayIdx};use sqlx::types::Json;@@ -23,9 +23,9 @@ use uuid::Uuid;use crate::domain::{bands_for_day, person_chunk_sentinel_day, AttemptCount, Band, BandSpec, BandSpecError, ChunkId,- ChunkLease, ChunkSpec, ChunkStatus, ClaimEpoch, ClaimKind, ClaimedChunk, EnqueuedChunk, Halted,- PersonRange, PersonRangeError, ProduceHwms, ProducedChunk, RunId, SChunkMs, ScanVolume,- ScannedChunk, StreamedChunk,+ ChunkLease, ChunkSpec, ChunkStatus, ClaimEpoch, ClaimKind, ClaimedChunk, DaySchedule,+ EnqueuedChunk, Halted, PersonRange, PersonRangeError, PlannedDay, ProduceHwms, ProducedChunk,+ RunId, SChunkMs, ScanVolume, ScannedChunk, StreamedChunk, UtcMillis,};use super::lease::LeaseHandle;@@ -34,6 +34,10 @@ use super::{Claimant, LeaseDuration, MaxAttempts, RenderedError, PERSISTED_ERROR/// Chunk statuses holding a live lease — the targets of the fenced heartbeat/fail/confirm writes.const ACTIVE_STATUSES_SQL: &str = "('scanning', 'produced')";+/// Run statuses whose chunks the seeder claims and heartbeats: the SQL twin of+/// [`super::runs::RunStatus::seed_phase`].+const SEEDABLE_RUN_STATUSES_SQL: &str = "('seeding', 'trailing')";+#[derive(Debug, Clone)]pub struct PgChunkStore {pool: PgPool,@@ -47,18 +51,27 @@ impl PgChunkStore {pub async fn plan_chunks(&self,run_id: RunId,- days: impl IntoIterator<Item = DayIdx>,+ days: impl IntoIterator<Item = PlannedDay>,bands_per_day: NonZeroU16,) -> Result<PlanOutcome, ChunkStoreError> {let mut ids = Vec::new();let mut dates = Vec::new();let mut bands = Vec::new();- for day in days {+ let mut holds = Vec::new();+ for PlannedDay { day, schedule } in days {let date = date_for_day(day).ok_or(ChunkStoreError::InvalidDay(day))?;+ let hold = match schedule {+ DaySchedule::Historical => None,+ DaySchedule::Trailing { claimable_after } => Some(+ DateTime::<Utc>::from_timestamp_millis(claimable_after.as_i64())+ .ok_or(ChunkStoreError::InvalidClaimableAfter(claimable_after))?,+ ),+ };for band in bands_for_day(day, bands_per_day) {ids.push(Uuid::now_v7());dates.push(date);bands.push(band.0);+ holds.push(hold);}}if ids.is_empty() {@@ -76,13 +89,14 @@ impl PgChunkStore {WHERE id = $1 AND status = 'seeding'FOR UPDATE), input AS (- SELECT * FROM unnest($2::uuid[], $3::date[], $4::smallint[]) AS u(id, day, band)+ SELECT * FROM unnest($2::uuid[], $3::date[], $4::smallint[], $6::timestamptz[])+ AS u(id, day, band, claimable_after)), inserted AS (INSERT INTO cohort_backfill_chunks(id, run_id, team_id, day, band, status, claim_epoch, claimed_by, attempts,- last_error, tiles_produced, created_at, updated_at)+ last_error, tiles_produced, claimable_after, created_at, updated_at)SELECT u.id, r.id, r.team_id, u.day, u.band, $5, 0, '', 0, '', 0,- now(), now()+ u.claimable_after, now(), now()FROM input u CROSS JOIN target_run rON CONFLICT (run_id, day, band) DO NOTHINGRETURNING id@@ -97,6 +111,7 @@ impl PgChunkStore {.bind(dates).bind(bands).bind(ChunkStatus::Pending.as_str())+ .bind(holds).fetch_one(&self.pool).await?;if !result.run_seeding {@@ -239,7 +254,12 @@ impl PgChunkStore {SELECT c.id, c.status IN {active} AS was_reclaimFROM cohort_backfill_chunks cJOIN cohort_backfill_runs r ON r.id = c.run_id- WHERE c.run_id = ANY($1) AND r.status = 'seeding'+ WHERE c.run_id = ANY($1) AND r.status IN {seedable}+ -- A trailing day is scanned only once it has ended and its run is `trailing`.+ -- Claimed while the run still seeds, it would lose its lease when the+ -- reconciling CAS fires, because the heartbeat joins the same run statuses.+ AND (c.claimable_after IS NULL+ OR (c.claimable_after <= now() AND r.status = 'trailing'))AND ((c.status = $7 AND c.attempts < $4)-- Only the failed→claim transition is gated on the backoff stamp. A chunk-- that never ran (`pending`) and an expired lease reclaim both stay@@ -271,6 +291,7 @@ impl PgChunkStore {next_chunk.was_reclaim"#,active = ACTIVE_STATUSES_SQL,+ seedable = SEEDABLE_RUN_STATUSES_SQL,);let row = sqlx::query_as::<_, ClaimedRow>(&sql).bind(run_ids)@@ -328,8 +349,9 @@ impl PgChunkStore {/// The `attempts >= max_attempts` half is the whole point: a `failed` chunk still under the cap/// is reclaimable by [`Self::claim_next`] and will retry, while a capped one never will. Only/// the capped ones are terminal, and only they wedge the run — the completion CAS demands every- /// chunk `confirmed`, so a run carrying one sits in `seeding` forever and holds its cohort's- /// uniqueness slot against every future run.+ /// readiness chunk `confirmed`, so a run carrying one sits in `seeding` forever and holds its+ /// cohort's uniqueness slot against every future run, and a `trailing` run carrying one never+ /// completes.pub async fn runs_with_exhausted_chunks(&self,run_ids: &[RunId],@@ -341,14 +363,18 @@ impl PgChunkStore {let run_ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();let rows = sqlx::query_as::<_, ExhaustedRunRow>(r#"- SELECT DISTINCT ON (run_id)- run_id,- count(*) OVER (PARTITION BY run_id) AS exhausted,- id::text AS chunk_id,- last_error- FROM cohort_backfill_chunks- WHERE run_id = ANY($1) AND status = $2 AND attempts >= $3- ORDER BY run_id, id+ SELECT DISTINCT ON (c.run_id)+ c.run_id,+ count(*) OVER (PARTITION BY c.run_id) AS exhausted,+ c.id::text AS chunk_id,+ c.last_error+ FROM cohort_backfill_chunks c+ JOIN cohort_backfill_runs r ON r.id = c.run_id+ WHERE c.run_id = ANY($1) AND c.status = $2 AND c.attempts >= $3+ -- Readiness does not wait for a trailing chunk, so its failure fails the run only+ -- once the run has stamped readiness and is `trailing`.+ AND (c.claimable_after IS NULL OR r.status = 'trailing')+ ORDER BY c.run_id, c.id"#,).bind(run_ids)@@ -466,6 +492,7 @@ impl PgChunkStore {fenced(updated, lease, ChunkOperation::Unclaim)}+ /// Unconfirmed chunks the runs' readiness still waits for, which leaves out trailing chunks.pub async fn remaining_chunks(&self, run_ids: &[RunId]) -> Result<u64, ChunkStoreError> {if run_ids.is_empty() {return Ok(0);@@ -475,7 +502,7 @@ impl PgChunkStore {r#"SELECT count(*)::bigintFROM cohort_backfill_chunks- WHERE run_id = ANY($1) AND status <> $2+ WHERE run_id = ANY($1) AND status <> $2 AND claimable_after IS NULL"#,).bind(run_ids)@@ -485,13 +512,14 @@ impl PgChunkStore {u64::try_from(count).map_err(|_| ChunkStoreError::InvalidRemainingCount(count))}+ /// Progress over the chunks the run's readiness waits for, which leaves out its trailing chunks.pub async fn chunk_progress(&self, run_id: RunId) -> Result<ChunkProgress, ChunkStoreError> {let row = sqlx::query_as::<_, ChunkProgressRow>(r#"SELECT count(*)::bigint AS total,count(*) FILTER (WHERE status <> $2)::bigint AS remainingFROM cohort_backfill_chunks- WHERE run_id = $1+ WHERE run_id = $1 AND claimable_after IS NULL"#,).bind(run_id)@@ -524,10 +552,11 @@ impl PgChunkStore {FROM cohort_backfill_runs rWHERE c.id = $1 AND c.claim_epoch = $2 AND c.claimed_by = $4AND c.status IN {active}- AND r.id = c.run_id AND r.status = 'seeding'+ AND r.id = c.run_id AND r.status IN {seedable}RETURNING c.id"#,active = ACTIVE_STATUSES_SQL,+ seedable = SEEDABLE_RUN_STATUSES_SQL,)).bind(lease.chunk_id()).bind(lease.epoch())@@ -710,6 +739,8 @@ pub enum ChunkStoreError {ScanBytesOutOfRange(u64),#[error("day index {0} is outside chrono's date range")]InvalidDay(DayIdx),+ #[error("claim hold {0:?} is outside chrono's timestamp range")]+ InvalidClaimableAfter(UtcMillis),#[error(transparent)]Band(#[from] BandSpecError),#[error(transparent)]@@ -832,14 +863,33 @@ fn date_for_day(day: DayIdx) -> Option<NaiveDate> {#[cfg(test)]mod tests {use super::*;+ use crate::store::runs::RunStatus;- #[test]- fn hoisted_status_fragments_only_name_live_chunk_statuses() {- let statuses = ACTIVE_STATUSES_SQL+ fn sql_fragment_names(fragment: &str) -> impl Iterator<Item = &str> {+ fragment.trim_matches(|c| c == '(' || c == ')').split(',')- .map(|token| token.trim().trim_matches('\''));- for status in statuses {+ .map(|token| token.trim().trim_matches('\''))+ }++ #[test]+ fn seedable_run_statuses_sql_names_exactly_the_seed_phase_statuses() {+ let named = sql_fragment_names(SEEDABLE_RUN_STATUSES_SQL)+ .map(|status| status.parse::<RunStatus>())+ .collect::<Result<Vec<_>, _>>()+ .expect("SQL fragment names a non-vocabulary run status");+ for status in RunStatus::ALL {+ assert_eq!(+ named.contains(&status),+ status.seed_phase().is_some(),+ "{status:?} disagrees between the SQL fragment and seed_phase()"+ );+ }+ }++ #[test]+ fn hoisted_status_fragments_only_name_live_chunk_statuses() {+ for status in sql_fragment_names(ACTIVE_STATUSES_SQL) {assert!(status.parse::<ChunkStatus>().is_ok(),"SQL fragment names non-vocabulary status {status:?}"diff --git a/rust/cohort-seeder/src/store/completion.rs b/rust/cohort-seeder/src/store/completion.rsindex cfbd27b8c84a..a35bd26deaa4 100644--- a/rust/cohort-seeder/src/store/completion.rs+++ b/rust/cohort-seeder/src/store/completion.rs@@ -63,6 +63,13 @@ macro_rules! confirmed_chunk_status {"'confirmed'"};}+// Readiness waits only for the days before the boundary. A trailing chunk, the only kind that+// carries a claim hold, is scanned after the run stamps readiness.+macro_rules! readiness_chunk {+ () => {+ "claimable_after IS NULL"+ };+}// 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.@@ -141,6 +148,8 @@ const CAS_RUN_RECONCILING: &str = concat!("\n SELECT 1 FROM cohort_backfill_chunks","\n WHERE run_id = $1 AND status <> ",confirmed_chunk_status!(),+ " AND ",+ readiness_chunk!(),"\n )","\n RETURNING id, reconcile_dispatched_at\n");@@ -152,6 +161,8 @@ const RUNS_WITH_ALL_CHUNKS_CONFIRMED: &str = concat!("\n SELECT 1 FROM cohort_backfill_chunks","\n WHERE run_id = candidate.run_id AND status <> ",confirmed_chunk_status!(),+ " AND ",+ readiness_chunk!(),"\n )\n");@@ -363,9 +374,10 @@ pub async fn read_planning_stamp(}/// CAS a seeding run into `reconciling`. Admits the transition only once planning is proven and every-/// chunk has confirmed, freezing the chunk ledger (`claim_next`/`heartbeat`/`plan_chunks` all require-/// `seeding`). `None` means the CAS was lost — another dispatcher won, chunks reappeared, or the run-/// left `seeding`.+/// chunk readiness waits for has confirmed, freezing the chunk ledger while the run reconciles:+/// `plan_chunks` requires `seeding`, and `claim_next`/`heartbeat` require `seeding` or `trailing`,+/// with a held chunk claimable only under `trailing`. `None` means the CAS was lost — another+/// dispatcher won, chunks reappeared, or the run left `seeding`.pub async fn cas_run_reconciling(pool: &PgPool,run_id: RunId,@@ -798,7 +810,8 @@ pub async fn load_current_shape_hashes(Ok(current)}-/// Which of the candidate runs have a fully confirmed chunk ledger, in one round trip. The driver+/// Which of the candidate runs have confirmed every chunk their readiness waits for, in one round+/// trip. The driver/// ticks inside the orchestrator's poll arm ahead of its liveness heartbeat, so a per-run round trip/// would scale one tick's cost with the seeding backlog.pub async fn runs_with_all_chunks_confirmed(diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rsindex 075217404b1f..d57942c72ac5 100644--- a/rust/cohort-seeder/src/store/runs.rs+++ b/rust/cohort-seeder/src/store/runs.rs@@ -29,13 +29,28 @@ macro_rules! run_columns {};}+// A trailing run is discovered only once one of its holds has lapsed: before that nothing of it+// can be claimed, and every discovery re-validates its pinned payload. The test is "any hold+// lapsed", not "an unconfirmed chunk's hold lapsed", so a run whose last chunk confirmed stays+// visible to `complete_trailing_runs`.+macro_rules! discoverable_run {+ () => {+ "status IN ('awaiting_boundary', 'seeding')+ OR (status = 'trailing' AND EXISTS (+ SELECT 1 FROM cohort_backfill_chunks c+ WHERE c.run_id = cohort_backfill_runs.id AND c.claimable_after <= now()))"+ };+}+// The kind predicate binds the caller's allowed-kind set: with the person gate off, discovery// binds `['behavioral']`, which keeps the person path inert without a second query text.const DISCOVER_ALL: &str = concat!("\n SELECT ",run_columns!(),"\n FROM cohort_backfill_runs",- "\n WHERE status IN ('awaiting_boundary', 'seeding')",+ "\n WHERE (",+ discoverable_run!(),+ ")","\n AND backfill_kind = ANY($1)","\n ORDER BY created_at\n");@@ -44,7 +59,9 @@ const DISCOVER_ONLY: &str = concat!("\n SELECT ",run_columns!(),"\n FROM cohort_backfill_runs",- "\n WHERE status IN ('awaiting_boundary', 'seeding')",+ "\n WHERE (",+ discoverable_run!(),+ ")","\n AND backfill_kind = ANY($2)","\n AND team_id = ANY($1)","\n ORDER BY created_at\n"@@ -96,6 +113,7 @@ pub enum RunStatus {Blocked,Seeding,Reconciling,+ Trailing,Completed,Superseded,Cancelled,@@ -103,18 +121,56 @@ pub enum RunStatus {}impl RunStatus {+ pub const ALL: [Self; 9] = [+ Self::AwaitingBoundary,+ Self::Blocked,+ Self::Seeding,+ Self::Reconciling,+ Self::Trailing,+ Self::Completed,+ Self::Superseded,+ Self::Cancelled,+ Self::Failed,+ ];+pub const fn as_str(self) -> &'static str {match self {Self::AwaitingBoundary => "awaiting_boundary",Self::Blocked => "blocked",Self::Seeding => "seeding",Self::Reconciling => "reconciling",+ Self::Trailing => "trailing",Self::Completed => "completed",Self::Superseded => "superseded",Self::Cancelled => "cancelled",Self::Failed => "failed",}}++ /// The phase in which the seeder scans this run's chunks, or `None` when it scans none.+ pub const fn seed_phase(self) -> Option<SeedPhase> {+ match self {+ Self::Seeding => Some(SeedPhase::Seeding),+ Self::Trailing => Some(SeedPhase::Trailing),+ Self::AwaitingBoundary+ | Self::Blocked+ | Self::Reconciling+ | Self::Completed+ | Self::Superseded+ | Self::Cancelled+ | Self::Failed => None,+ }+ }+}++/// What a run with an established boundary still owes the seeder.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SeedPhase {+ /// Planning and scanning every day. Readiness waits for the days before the boundary day.+ Seeding,+ /// Readiness is stamped, and the run's days were all planned while it was seeding. Only its+ /// trailing days are left to scan.+ Trailing,}impl FromStr for RunStatus {@@ -126,6 +182,7 @@ impl FromStr for RunStatus {"blocked" => Ok(Self::Blocked),"seeding" => Ok(Self::Seeding),"reconciling" => Ok(Self::Reconciling),+ "trailing" => Ok(Self::Trailing),"completed" => Ok(Self::Completed),"superseded" => Ok(Self::Superseded),"cancelled" => Ok(Self::Cancelled),@@ -219,14 +276,15 @@ pub struct DiscoveredRun {pub pinned: Value,}-/// A run proven `seeding` with an established boundary — the only place the boundary `Option`-/// narrows to a value and the trigger stays typed all the way into [`PinnedRunSnapshot`]. Minted-/// only by [`establish_boundary`].+/// A run proven `seeding` or `trailing` with an established boundary — the only place the boundary+/// `Option` narrows to a value and the trigger stays typed all the way into [`PinnedRunSnapshot`].+/// Minted only by [`establish_boundary`].#[derive(Debug, Clone)]pub struct SeedableRun {pub run_id: RunId,pub team_id: TeamId,pub kind: RunKind,+ pub phase: SeedPhase,pub trigger: TriggerKind,pub timezone: String,pub boundary_at: UtcMillis,@@ -235,11 +293,12 @@ pub struct SeedableRun {}impl SeedableRun {- fn promote(run: DiscoveredRun, boundary_at: DateTime<Utc>) -> Self {+ fn promote(run: DiscoveredRun, boundary_at: DateTime<Utc>, phase: SeedPhase) -> Self {Self {run_id: run.run_id,team_id: run.team_id,kind: run.kind,+ phase,trigger: run.trigger,timezone: run.timezone,boundary_at: UtcMillis::new(boundary_at.timestamp_millis()),@@ -672,11 +731,12 @@ pub async fn establish_boundary(run: DiscoveredRun,) -> Result<BoundaryOutcome, RunError> {let kind = run.kind;- if run.status == RunStatus::Seeding {+ if let Some(phase) = run.status.seed_phase() {return match run.boundary_at {Some(boundary_at) => Ok(BoundaryOutcome::AlreadyEstablished(SeedableRun::promote(run,boundary_at,+ phase,))),None => Err(RunError::SeedingBoundaryMissing(run.run_id)),};@@ -721,15 +781,17 @@ pub async fn establish_boundary(return Ok(BoundaryOutcome::Established(SeedableRun::promote(run,boundary.boundary_at,+ SeedPhase::Seeding,)));}let current = read_run(pool, run.run_id, kind).await?;- if current.status == RunStatus::Seeding {+ if let Some(phase) = current.status.seed_phase() {match current.boundary_at {Some(boundary_at) => Ok(BoundaryOutcome::AlreadyEstablished(SeedableRun::promote(current,boundary_at,+ phase,))),None => Err(RunError::SeedingBoundaryMissing(current.run_id)),}@@ -746,7 +808,7 @@ pub async fn fail_run(pool: &PgPool, run_id: RunId, error: &RenderedError) -> Rer#"UPDATE cohort_backfill_runsSET status = 'failed', error = left($2, $3), finished_at = now(), updated_at = now()- WHERE id = $1 AND status IN ('awaiting_boundary', 'seeding')+ WHERE id = $1 AND status IN ('awaiting_boundary', 'seeding', 'trailing')RETURNING id"#,)@@ -758,6 +820,30 @@ pub async fn fail_run(pool: &PgPool, run_id: RunId, error: &RenderedError) -> Refailed.map(|_| ()).ok_or(RunError::NotActive(run_id))}+/// Complete every trailing run among `run_ids` whose chunks have all confirmed. Returns how many it+/// completed.+pub async fn complete_trailing_runs(pool: &PgPool, run_ids: &[RunId]) -> Result<u64, RunError> {+ if run_ids.is_empty() {+ return Ok(0);+ }+ let run_ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();+ let completed = sqlx::query(+ r#"+ UPDATE cohort_backfill_runs r+ SET status = 'completed', finished_at = now(), updated_at = now()+ WHERE r.id = ANY($1) AND r.status = 'trailing'+ AND NOT EXISTS (+ SELECT 1 FROM cohort_backfill_chunks c+ WHERE c.run_id = r.id AND c.status <> 'confirmed'+ )+ "#,+ )+ .bind(run_ids)+ .execute(pool)+ .await?;+ Ok(completed.rows_affected())+}+pub async fn record_run_warning(pool: &PgPool,run_id: RunId,diff --git a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0012.sql b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0015.sqlsimilarity index 94%rename from rust/cohort-seeder/tests/fixtures/cohort_backfill_0012.sqlrename to rust/cohort-seeder/tests/fixtures/cohort_backfill_0015.sqlindex a008141397fd..04ae85ba2438 100644--- a/rust/cohort-seeder/tests/fixtures/cohort_backfill_0012.sql+++ b/rust/cohort-seeder/tests/fixtures/cohort_backfill_0015.sql@@ -1,7 +1,8 @@-- Snapshot pinned to--- products/cohorts/backend/migrations/0012_cohortbackfillchunk_next_attempt_at_and_more.py, the last+-- products/cohorts/backend/migrations/0015_cohortbackfillchunk_claimable_after_and_more.py, the last-- migration that changed this DDL. 0010 alters only `marker_watch`'s help_text, which emits no SQL,--- and 0011 touches posthog_cohort columns this projection does not carry.+-- 0011 touches posthog_cohort columns this projection does not carry, and 0013 and 0014 emit none+-- for these tables.-- External Team/Cohort foreign keys are omitted so the contract test stays schema-local.---- Nothing enforces this snapshot against Django. No test diffs it with `sqlmigrate`, and the@@ -69,6 +70,8 @@ CREATE TABLE cohort_backfill_chunks (person_range_hi uuid,attempts integer NOT NULL DEFAULT 0,next_attempt_at timestamptz,+ -- 0015 trailing-day claim hold.+ claimable_after timestamptz,last_error text NOT NULL DEFAULT '',tiles_produced bigint NOT NULL DEFAULT 0,-- 0012 scan-volume columns. The DEFAULT is the contract `plan_chunks` leans on: it inserts andiff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rsindex 21c7eb300a45..fe29578b3ba2 100644--- a/rust/cohort-seeder/tests/pg_chunks.rs+++ b/rust/cohort-seeder/tests/pg_chunks.rs@@ -11,12 +11,13 @@ use std::num::NonZeroU16;use std::time::Duration;use anyhow::{bail, ensure, Context, Result};+use chrono::{DateTime, Utc};use cohort_core::filters::{CohortId, TeamId};-use cohort_seeder::app::fail_exhausted_runs_of_kind;use cohort_seeder::app::reconcile_dispatch::{prepare_reconcile_dispatch, CompletionRequirement, PrepareReconcileDispatchError,RegisterBackfillConfirmation,};+use cohort_seeder::app::{eligible_run_ids, fail_exhausted_runs_of_kind};use cohort_seeder::domain::{tile_ranges, AttemptCount, ClaimEpoch, PersonRunValidation, PinnedWarning, ProduceHwms,RetryBackoffPolicy, ScanVolume, ScopeKind,@@ -24,8 +25,9 @@ use cohort_seeder::domain::{use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome, NO_ERROR_RECORDED};use cohort_seeder::store::lease::LeaseFailure;use cohort_seeder::store::runs::{- discover_runs, establish_boundary, fail_run, load_reconcile_run, record_run_warning,- BoundaryOutcome, ReconcileRunError, RunError, RunKind, RunStatus, RunWarningNote,+ complete_trailing_runs, discover_runs, establish_boundary, fail_run, load_reconcile_run,+ record_run_warning, BoundaryOutcome, ReconcileRunError, RunError, RunKind, RunStatus,+ RunWarningNote, SeedPhase,};use cohort_seeder::store::{Claimant, LeaseDuration, MaxAttempts, RenderedError};use cohort_seeder::test_support;@@ -35,9 +37,9 @@ use uuid::Uuid;mod support;use support::{- behavioral_filter, empty_pinned, ensure_lease_lost, insert_participation, insert_person_run,- insert_run, person_filter, person_pinned, pinned_condition, planned_count, with_db,- ACTIVE_HASH, SUPERSEDED_HASH,+ behavioral_filter, empty_pinned, ensure_lease_lost, historical, insert_participation,+ insert_person_run, insert_run, person_filter, person_pinned, pinned_condition, planned_count,+ trailing, with_db, ACTIVE_HASH, SUPERSEDED_HASH,};const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;@@ -492,8 +494,20 @@ async fn planning_is_idempotent_scopes_team_and_gates_on_seeding() -> Result<()>insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);- ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 0);+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100, 101]), ONE_BAND)+ .await?+ )? == 2+ );+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100, 101]), ONE_BAND)+ .await?+ )? == 0+ );let progress = store.chunk_progress(seeding_run).await?;ensure!(progress.total() == 2);ensure!(progress.remaining() == 2);@@ -515,7 +529,9 @@ async fn planning_is_idempotent_scopes_team_and_gates_on_seeding() -> Result<()>).await?;ensure!(matches!(- store.plan_chunks(idle_run, [200], ONE_BAND).await?,+ store+ .plan_chunks(idle_run, historical([200]), ONE_BAND)+ .await?,PlanOutcome::RunNotSeeding));Ok(())@@ -532,8 +548,20 @@ async fn planning_fans_out_bands_and_claims_carry_the_band_count() -> Result<()>insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());let four_bands = NonZeroU16::new(4).context("four is non-zero")?;- ensure!(planned_count(store.plan_chunks(seeding_run, [100], four_bands).await?)? == 4);- ensure!(planned_count(store.plan_chunks(seeding_run, [100], four_bands).await?)? == 0);+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100]), four_bands)+ .await?+ )? == 4+ );+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100]), four_bands)+ .await?+ )? == 0+ );let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -562,7 +590,13 @@ async fn concurrent_claims_take_disjoint_chunks() -> Result<()> {let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100, 101]), ONE_BAND)+ .await?+ )? == 2+ );let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -591,7 +625,7 @@ async fn expired_lease_reclaim_bumps_epoch_and_fences_the_stale_lease() -> Resullet seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -644,7 +678,13 @@ async fn unclaim_returns_chunk_to_pending_and_refunds_one_attempt() -> Result<()let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100]), ONE_BAND)+ .await?+ )? == 1+ );let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -685,7 +725,7 @@ async fn a_failed_chunk_waits_out_its_backoff_before_it_is_claimable_again() ->let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -774,7 +814,13 @@ async fn the_recovery_path_draws_its_wait_from_the_chunks_attempt_count() -> ResRetryBackoffPolicy::new(Duration::from_secs(1), Duration::from_secs(1800)).unwrap();let days = [100, 101, 102, 103];- ensure!(planned_count(store.plan_chunks(seeding_run, days, ONE_BAND).await?)? == 4);+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical(days), ONE_BAND)+ .await?+ )? == 4+ );sqlx::query("UPDATE cohort_backfill_chunks SET attempts = 48 WHERE run_id = $1").bind(seeding_run).execute(&pool)@@ -842,7 +888,7 @@ async fn the_backoff_gate_applies_only_to_the_failed_claim_arm() -> Result<()> {let run_ids = [seeding_run];// A pending chunk carrying a future stamp is still claimable.- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);sqlx::query("UPDATE cohort_backfill_chunks SET next_attempt_at = now() + interval '1 hour' WHERE run_id = $1",)@@ -910,6 +956,176 @@ async fn the_backoff_gate_applies_only_to_the_failed_claim_arm() -> Result<()> {.await}+/// A trailing day is planned with its hold and claimed only once the hold lapses and its run is+/// `trailing`. Discovery admits the trailing run once a hold lapses, prepare keeps it eligible, and+/// the run completes once that day confirms.+#[tokio::test]+async fn a_trailing_day_waits_out_its_hold_and_completes_its_trailing_run() -> Result<()> {+ with_db(|pool| async move {+ let run_id =+ insert_run(&pool, 2, "cohort_created", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let claimant = Claimant::new("worker-a")?;+ let run_ids = [run_id];+ let behavioral = [RunKind::Behavioral];+ let hold = Utc::now() + chrono::Duration::hours(1);+ let [historical_day] = historical([100]);+ ensure!(+ planned_count(+ store+ .plan_chunks(run_id, [historical_day, trailing(101, hold)], ONE_BAND)+ .await?+ )? == 2+ );+ let holds: Vec<Option<DateTime<Utc>>> = sqlx::query_scalar(+ "SELECT claimable_after FROM cohort_backfill_chunks WHERE run_id = $1 ORDER BY day",+ )+ .bind(run_id)+ .fetch_all(&pool)+ .await?;+ ensure!(+ holds+ == [+ None,+ DateTime::from_timestamp_millis(hold.timestamp_millis())+ ],+ "unexpected holds {holds:?}"+ );++ let historical_claim = store+ .claim_next(&run_ids, &claimant, lease60, attempts5)+ .await?+ .context("the historical day was not claimable")?;+ ensure!(historical_claim.chunk.spec().day == 100);+ ensure!(+ store+ .claim_next(&run_ids, &claimant, lease60, attempts5)+ .await?+ .is_none(),+ "the trailing day was claimed before its hold lapsed"+ );+ let historical_lease = historical_claim.chunk.spec().lease;+ test_support::mark_produced_raw(&store, historical_lease, 0, ScanVolume::default()).await?;+ test_support::confirm_raw(&store, historical_lease, &ProduceHwms::default()).await?;+ drop(historical_claim);++ // The finalizer's move once it has stamped readiness. Until a hold lapses nothing of the+ // run can be claimed, so discovery leaves it alone.+ sqlx::query("UPDATE cohort_backfill_runs SET status = 'trailing' WHERE id = $1")+ .bind(run_id)+ .execute(&pool)+ .await?;+ ensure!(+ discover_runs(&pool, &TeamAllowlist::All, &behavioral)+ .await?+ .iter()+ .all(|run| run.run_id != run_id),+ "the trailing run was discovered before any of its holds lapsed"+ );++ sqlx::query(+ "UPDATE cohort_backfill_chunks SET claimable_after = now() - interval '1 second'+ WHERE run_id = $1 AND claimable_after IS NOT NULL",+ )+ .bind(run_id)+ .execute(&pool)+ .await?;+ let resumed = discover_runs(&pool, &TeamAllowlist::All, &behavioral)+ .await?+ .into_iter()+ .find(|run| run.run_id == run_id)+ .context("discovery skipped the trailing run once its hold lapsed")?;+ match establish_boundary(&pool, resumed).await? {+ BoundaryOutcome::AlreadyEstablished(run) => ensure!(run.phase == SeedPhase::Trailing),+ other => bail!("the trailing run resumed as {other:?}"),+ }+ ensure!(+ eligible_run_ids(&pool, &store, &TeamAllowlist::All, &behavioral)+ .await+ .contains(&run_id),+ "prepare did not keep the trailing run claim-eligible"+ );+ ensure!(complete_trailing_runs(&pool, &run_ids).await? == 0);++ let trailing_claim = store+ .claim_next(&run_ids, &claimant, lease60, attempts5)+ .await?+ .context("the trailing day was not claimable after its hold lapsed")?;+ ensure!(trailing_claim.chunk.spec().day == 101);+ let trailing_lease = trailing_claim.chunk.spec().lease;+ test_support::heartbeat(&store, trailing_lease, &claimant, lease60).await?;+ test_support::mark_produced_raw(&store, trailing_lease, 0, ScanVolume::default()).await?;+ test_support::confirm_raw(&store, trailing_lease, &ProduceHwms::default()).await?;+ drop(trailing_claim);++ ensure!(complete_trailing_runs(&pool, &run_ids).await? == 1);+ let (status, finished): (String, bool) = sqlx::query_as(+ "SELECT status, finished_at IS NOT NULL FROM cohort_backfill_runs WHERE id = $1",+ )+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(status == "completed" && finished);+ Ok(())+ })+ .await+}++/// While a run still seeds, a held chunk stays unclaimable even after its hold lapses, so the+/// reconciling CAS cannot cut its lease mid-scan; and once every chunk has confirmed, the trailing+/// sweep leaves the run in `seeding`, since completing it there would skip `reconciling` and the+/// readiness stamp.+#[tokio::test]+async fn a_seeding_run_neither_hands_out_a_lapsed_held_chunk_nor_completes_as_trailing(+) -> Result<()> {+ with_db(|pool| async move {+ let run_id =+ insert_run(&pool, 2, "cohort_created", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [run_id];+ let [historical_day] = historical([100]);+ let lapsed = Utc::now() - chrono::Duration::hours(1);+ store+ .plan_chunks(run_id, [historical_day, trailing(101, lapsed)], ONE_BAND)+ .await?;+ sqlx::query(+ "UPDATE cohort_backfill_chunks SET status = 'confirmed'+ WHERE run_id = $1 AND claimable_after IS NULL",+ )+ .bind(run_id)+ .execute(&pool)+ .await?;+ ensure!(+ store+ .claim_next(&run_ids, &Claimant::new("worker-a")?, lease60, attempts5)+ .await?+ .is_none(),+ "a held chunk was claimed while its run was still seeding"+ );++ sqlx::query("UPDATE cohort_backfill_chunks SET status = 'confirmed' WHERE run_id = $1")+ .bind(run_id)+ .execute(&pool)+ .await?;+ ensure!(complete_trailing_runs(&pool, &run_ids).await? == 0);+ let status: String =+ sqlx::query_scalar("SELECT status FROM cohort_backfill_runs WHERE id = $1")+ .bind(run_id)+ .fetch_one(&pool)+ .await?;+ ensure!(+ status == "seeding",+ "the seeding run was completed as if trailing"+ );+ Ok(())+ })+ .await+}+/// The `scanning`→`produced` CAS records what the scan moved, and planning leaves the byte columns/// at the database-side default. The default is load-bearing: `plan_chunks` inserts an explicit/// column list that names neither column, so a Django-only default would make every planning insert@@ -920,7 +1136,7 @@ async fn mark_produced_records_the_scan_byte_volume_that_planning_defaults_to_zelet seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);let planned: (i64, i64) = sqlx::query_as("SELECT scan_received_bytes, scan_decoded_bytes FROM cohort_backfill_chunks WHERE run_id = $1",@@ -977,7 +1193,7 @@ async fn attempt_cap_is_terminal_for_failed_but_reclaims_expired_produced() -> Rlet run_ids = [seeding_run];// A chunk driven to the attempt cap by claiming, then failed, is not claimable again.- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);sqlx::query("UPDATE cohort_backfill_chunks SET attempts = 4 WHERE run_id = $1").bind(seeding_run).execute(&pool)@@ -1003,7 +1219,7 @@ async fn attempt_cap_is_terminal_for_failed_but_reclaims_expired_produced() -> R.is_none());// A second chunk, marked produced then expired at the cap, IS reclaimed.- ensure!(planned_count(store.plan_chunks(seeding_run, [101], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([101]), ONE_BAND).await?)? == 1);let final_attempt = store.claim_next(&run_ids, &Claimant::new("worker-e")?, lease60, attempts5).await?@@ -1049,7 +1265,7 @@ async fn expired_scanning_chunk_at_the_cap_is_reaped_not_reclaimed() -> Result<(let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -1107,7 +1323,7 @@ async fn runs_with_exhausted_chunks_selects_only_capped_failures() -> Result<()>let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100, 101]), ONE_BAND).await?)? == 2);let attempts5 = MaxAttempts::new(5)?;let run_ids = [seeding_run];@@ -1159,7 +1375,7 @@ async fn exhausted_chunk_and_error_are_read_off_the_same_row() -> Result<()> {let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100, 101]), ONE_BAND).await?)? == 2);let attempts5 = MaxAttempts::new(5)?;// Ordered so the lowest-id chunk carries the *higher* error text: an independent@@ -1203,6 +1419,45 @@ async fn exhausted_chunk_and_error_are_read_off_the_same_row() -> Result<()> {.await}+/// Readiness does not wait for a trailing day, so that day's exhausted chunk fails its run only once+/// the run has stamped readiness and is `trailing`.+#[tokio::test]+async fn an_exhausted_trailing_chunk_fails_its_run_only_once_the_run_is_trailing() -> Result<()> {+ with_db(|pool| async move {+ let run_id =+ insert_run(&pool, 2, "cohort_created", "seeding", true, empty_pinned()).await?;+ let store = PgChunkStore::new(pool.clone());+ let attempts5 = MaxAttempts::new(5)?;+ let run_ids = [run_id];+ store+ .plan_chunks(run_id, [trailing(101, Utc::now())], ONE_BAND)+ .await?;+ sqlx::query(+ "UPDATE cohort_backfill_chunks SET status = 'failed', attempts = 5 WHERE run_id = $1",+ )+ .bind(run_id)+ .execute(&pool)+ .await?;++ ensure!(+ fail_exhausted_runs_of_kind(&pool, &store, &run_ids, RunKind::Behavioral, attempts5)+ .await+ == 0+ );+ sqlx::query("UPDATE cohort_backfill_runs SET status = 'trailing' WHERE id = $1")+ .bind(run_id)+ .execute(&pool)+ .await?;+ ensure!(+ fail_exhausted_runs_of_kind(&pool, &store, &run_ids, RunKind::Behavioral, attempts5)+ .await+ == 1+ );+ Ok(())+ })+ .await+}+/// Failing a run whose chunk exhausted its retries stops the run dead: a still-pending sibling is no/// longer claimable, a live sibling's heartbeat is refused, and a second failure is a no-op rather/// than a double-count. Without it the run sits in `seeding` forever holding its cohort's slot.@@ -1213,7 +1468,7 @@ async fn exhausted_chunk_fails_the_run_and_stops_further_claims() -> Result<()>insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());ensure!(- planned_count(store.plan_chunks(seeding_run, [100, 101, 102], ONE_BAND).await?)? == 3+ planned_count(store.plan_chunks(seeding_run, historical([100, 101, 102]), ONE_BAND).await?)? == 3);let lease60 = LeaseDuration::new(Duration::from_secs(60))?;@@ -1315,7 +1570,13 @@ async fn fail_truncates_chunk_and_run_error_columns() -> Result<()> {let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(+ planned_count(+ store+ .plan_chunks(seeding_run, historical([100]), ONE_BAND)+ .await?+ )? == 1+ );let lease60 = LeaseDuration::new(Duration::from_secs(60))?;let attempts5 = MaxAttempts::new(5)?;@@ -1558,7 +1819,13 @@ async fn person_chunks_claim_after_behavioral_days_and_carry_ranges() -> Result<insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let person_run = insert_person_run(&pool, 2, "seeding", true, person_pinned(&[])).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(behavioral_run, [100], ONE_BAND).await?)? == 1);+ ensure!(+ planned_count(+ store+ .plan_chunks(behavioral_run, historical([100]), ONE_BAND)+ .await?+ )? == 1+ );let boundary = Uuid::from_u128(0x42);let ranges = tile_ranges(&[boundary])?;ensure!(planned_count(store.plan_person_chunks(person_run, &ranges).await?)? == 2);@@ -1614,7 +1881,7 @@ async fn cancelling_a_run_kills_its_live_lease_via_the_heartbeat() -> Result<()>let seeding_run =insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let store = PgChunkStore::new(pool.clone());- ensure!(planned_count(store.plan_chunks(seeding_run, [100], ONE_BAND).await?)? == 1);+ ensure!(planned_count(store.plan_chunks(seeding_run, historical([100]), ONE_BAND).await?)? == 1);let lease3 = LeaseDuration::new(Duration::from_secs(3))?;let attempts5 = MaxAttempts::new(5)?;diff --git a/rust/cohort-seeder/tests/pg_completion.rs b/rust/cohort-seeder/tests/pg_completion.rsindex b884b27f5a21..09bc574a533e 100644--- a/rust/cohort-seeder/tests/pg_completion.rs+++ b/rust/cohort-seeder/tests/pg_completion.rs@@ -38,9 +38,9 @@ use sqlx::PgPool;mod support;use support::{- empty_pinned, ensure_fence_lost, insert_cohort, insert_participation,+ empty_pinned, ensure_fence_lost, historical, insert_cohort, insert_participation,insert_person_participation, insert_person_run, insert_reconciling_run, insert_run,- person_pinned, set_marker_bits, with_db,+ person_pinned, set_marker_bits, trailing, with_db,};const ONE_BAND: NonZeroU16 = NonZeroU16::MIN;@@ -262,11 +262,30 @@ async fn cas_reconciling_is_single_winner_and_gated_on_planned_and_confirmed() -insert_run(&pool, 4, "team_enablement", "seeding", true, empty_pinned()).await?;mark_chunks_planned(&pool, pending, RunKind::Behavioral).await?;PgChunkStore::new(pool.clone())- .plan_chunks(pending, [100], ONE_BAND)+ .plan_chunks(pending, historical([100]), ONE_BAND).await?;ensure!(cas_run_reconciling(&pool, pending, RunKind::Behavioral).await?.is_none());++ // Only a held trailing day unconfirmed: readiness does not wait for it, so the CAS wins.+ let trailing_only =+ insert_run(&pool, 5, "team_enablement", "seeding", true, empty_pinned()).await?;+ mark_chunks_planned(&pool, trailing_only, RunKind::Behavioral).await?;+ let store = PgChunkStore::new(pool.clone());+ store+ .plan_chunks(+ trailing_only,+ [trailing(101, Utc::now() + ChronoDuration::hours(1))],+ ONE_BAND,+ )+ .await?;+ ensure!(store.chunk_progress(trailing_only).await?.remaining() == 0);+ ensure!(+ cas_run_reconciling(&pool, trailing_only, RunKind::Behavioral)+ .await?+ .is_some()+ );Ok(())}).await@@ -463,14 +482,18 @@ async fn runs_with_all_chunks_confirmed_selects_only_fully_confirmed_ledgers() -insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;let confirmed =insert_run(&pool, 3, "team_enablement", "seeding", true, empty_pinned()).await?;- store.plan_chunks(confirmed, [100], ONE_BAND).await?;+ store+ .plan_chunks(confirmed, historical([100]), ONE_BAND)+ .await?;sqlx::query("UPDATE cohort_backfill_chunks SET status = 'confirmed' WHERE run_id = $1").bind(confirmed).execute(&pool).await?;let pending =insert_run(&pool, 4, "team_enablement", "seeding", true, empty_pinned()).await?;- store.plan_chunks(pending, [100, 101], ONE_BAND).await?;+ store+ .plan_chunks(pending, historical([100, 101]), ONE_BAND)+ .await?;sqlx::query("UPDATE cohort_backfill_chunks SET status = 'confirmed' \WHERE id = (SELECT id FROM cohort_backfill_chunks WHERE run_id = $1 LIMIT 1)",@@ -479,9 +502,21 @@ async fn runs_with_all_chunks_confirmed_selects_only_fully_confirmed_ledgers() -.execute(&pool).await?;- let ready = runs_with_all_chunks_confirmed(&pool, &[no_chunks, confirmed, pending]).await?;+ let trailing_only =+ insert_run(&pool, 5, "team_enablement", "seeding", true, empty_pinned()).await?;+ store+ .plan_chunks(+ trailing_only,+ [trailing(101, Utc::now() + ChronoDuration::hours(1))],+ ONE_BAND,+ )+ .await?;++ let ready =+ runs_with_all_chunks_confirmed(&pool, &[no_chunks, confirmed, pending, trailing_only])+ .await?;ensure!(- ready == [no_chunks, confirmed].into_iter().collect(),+ ready == [no_chunks, confirmed, trailing_only].into_iter().collect(),"unexpected ready set: {ready:?}");ensure!(runs_with_all_chunks_confirmed(&pool, &[]).await?.is_empty());diff --git a/rust/cohort-seeder/tests/support/mod.rs b/rust/cohort-seeder/tests/support/mod.rsindex e4aabe91693e..438f2d29c3e8 100644--- a/rust/cohort-seeder/tests/support/mod.rs+++ b/rust/cohort-seeder/tests/support/mod.rs@@ -15,7 +15,8 @@ use std::future::Future;use std::str::FromStr;use anyhow::{bail, Context, Result};-use cohort_seeder::domain::RunId;+use chrono::{DateTime, Utc};+use cohort_seeder::domain::{DayIdx, DaySchedule, PlannedDay, RunId, UtcMillis};use cohort_seeder::store::chunks::{ChunkStoreError, PlanOutcome};use cohort_seeder::store::completion::CompletionStoreError;use serde_json::{json, Value};@@ -25,8 +26,8 @@ use sqlx::{Connection, PgConnection, PgPool};use uuid::Uuid;/// The `cohort_backfill_*` DDL (plus a schema-local `posthog_cohort` projection), pinned to Django-/// migration 0012, applied fresh into each test schema.-pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0012.sql");+/// migration 0015, applied fresh into each test schema.+pub const DDL: &str = include_str!("../fixtures/cohort_backfill_0015.sql");/// A live cohort condition hash used by the superseded-load fixtures.pub const ACTIVE_HASH: &str = "active0000000000";/// A superseded cohort condition hash used by the superseded-load fixtures.@@ -355,3 +356,21 @@ pub fn behavioral_filter(hash: &str, event_name: &str) -> Value {}]}})}++/// Days before a run's boundary, planned the way the seeder plans them: claimable at once.+pub fn historical<const N: usize>(days: [DayIdx; N]) -> [PlannedDay; N] {+ days.map(|day| PlannedDay {+ day,+ schedule: DaySchedule::Historical,+ })+}++/// A day from the boundary day on, held the way the seeder holds it until the day has ended.+pub fn trailing(day: DayIdx, claimable_after: DateTime<Utc>) -> PlannedDay {+ PlannedDay {+ day,+ schedule: DaySchedule::Trailing {+ claimable_after: UtcMillis::new(claimable_after.timestamp_millis()),+ },+ }+}