Skip to content

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

feat(cohorts): claim seeder backfill chunks newest day first (#125053)

Matheus Batistad98d40b860e7
diff --git a/docs/internal/realtime-cohorts/backfill-overview.md b/docs/internal/realtime-cohorts/backfill-overview.md
index c0babf24956f..d4528ad108f1 100644
--- a/docs/internal/realtime-cohorts/backfill-overview.md
+++ b/docs/internal/realtime-cohorts/backfill-overview.md
@@ -146,6 +146,7 @@ A late event that reaches ClickHouse after `S_chunk` is not in the tile.
If live folds it before the tile applies, `max` takes the larger of two disjoint counts instead of their sum, so the day is under-counted.
If live folds it after the tile applies, live adds it on top of the tile, which is correct.
That is bounded to late arrivals on old days.
+The day before the boundary day is claimed first, so when `B` falls just after the team's midnight, its events still in ingestion reach ClickHouse after the scan.
It can drop a person out of a `gte` or `gt` cohort, and wrongly keep one in an `lt`, `lte`, `eq` or negated one.
### Rule 4: person seeds are judged by time, with a margin
@@ -257,7 +258,7 @@ Every backfill gate is on, and the default timings apply: a 5-minute save deboun
The seeder picks up R and sets `B` to 10:05:10.
It plans one chunk per day from 2026-03-03 through 2026-03-09.
4. **10:05:25, scan.**
- Workers claim chunks oldest day first.
+ Workers claim chunks newest day first.
The 2026-03-05 chunk is claimed at 10:05:25, so its `S_chunk` is 10:05:25.
ClickHouse returns p-1's 4 pageviews, all of which arrived long ago.
The seeder produces a tile: p-1, condition H, 2026-03-05, count 4.
@@ -302,4 +303,5 @@ A backlog, a failure or a slow catalog refresh makes it longer.
So reconcile is dispatched long before most seeds apply, and the ordering on each partition is what keeps a reconcile behind its run's held seeds.
- Reconcile requests are not fenced.
A request that reaches a partition before the processor has loaded the cohort's current definition waits for the next catalog refresh, up to one refresh interval, and is withheld only if that refresh still disagrees.
-- Every chunk of every run is claimed oldest day first, so a small new cohort's recent days wait behind a large team run's older days.
+- Behavioral chunks are claimed newest day first across every run, so the older days of a long-window run wait behind the newer days of every other run.
+ They are claimed only once no newer day waits, so under sustained load the wait has no bound.
diff --git a/docs/internal/realtime-cohorts/seeder.md b/docs/internal/realtime-cohorts/seeder.md
index af2893d856f6..0b70669e3cd7 100644
--- a/docs/internal/realtime-cohorts/seeder.md
+++ b/docs/internal/realtime-cohorts/seeder.md
@@ -82,7 +82,8 @@ It stays in `seeding`, holding the cohort's run slot, until an operator cancels
### Claiming and fencing
A worker claims the next chunk with one statement using `FOR UPDATE SKIP LOCKED`.
-It picks the oldest day first across all seeding runs, and admits:
+It picks behavioral chunks before person chunks, then the newest day first across every run.
+It admits:
- pending chunks and failed chunks past their backoff, both under the attempt cap,
- `scanning` chunks whose lease expired, under the attempt cap,
@@ -330,7 +331,7 @@ p-1 hashes to partition 26.
The pinned condition resolves to a 7-day sliding window.
The seeder plans 7 chunks, for 2026-03-03 through 2026-03-09, one band each, and stamps the planning proof.
3. **Claim.**
- Workers claim chunks oldest day first.
+ Workers claim chunks newest day first.
At 15:00:20 one of them claims the 2026-03-05 chunk.
`S_chunk` is 15:00:20 and the claim epoch is 1.
4. **Scan.**
@@ -443,7 +444,8 @@ Set them only to go below the profile.
## Things that surprise people
- `B` is the moment the seeder first saw the run, not when the run was created, except for disaster-recovery runs, whose `B` Django pins.
-- Claims take the oldest day first across every run, so a small new cohort's recent days wait behind a large team run's older days.
+- Behavioral claims take the newest day first across every run, so the older days of a long-window run wait behind the newer days of every other run.
+ If none of its chunks moves for `--stalled-for-hours`, `manage_cohort_backfill_runs inventory` lists it as a `seeding-stalled` cancel candidate, even though it is only queued.
- A chunk in `produced` has enqueued its tiles but may not have all acknowledgments yet.
- The seeder writes the claim epoch into every tile, but the processor ignores it.
Fencing is purely a Postgres concern, and duplicates are absorbed by max-merge.
diff --git a/rust/cohort-seeder/src/domain/person.rs b/rust/cohort-seeder/src/domain/person.rs
index 159827b94b0e..5358805020c9 100644
--- a/rust/cohort-seeder/src/domain/person.rs
+++ b/rust/cohort-seeder/src/domain/person.rs
@@ -36,8 +36,9 @@ use super::projection::ProjectedKeys;
/// The wire cap a single seed's `evaluated` list admits; validation enforces it run-wide.
pub use cohort_core::seed::MAX_PERSON_SEED_HASHES;
-/// The fixed far-future `day` every person chunk is planned under. `claim_next` orders by
-/// `(day, band)`, so behavioral chunks (readiness-gating, fence-sensitive) always claim first.
+/// The fixed far-future `day` every person chunk is planned under. `day` is non-null and part of
+/// the `(run, day, band)` unique key that makes person planning all-or-nothing. `claim_next` takes
+/// its priority between kinds from the run kind, not from this date.
pub fn person_chunk_sentinel_day() -> NaiveDate {
NaiveDate::from_ymd_opt(9999, 1, 1).expect("9999-01-01 is a valid date")
}
diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rs
index 300ae905394a..f1f57d7a0d5c 100644
--- a/rust/cohort-seeder/src/store/chunks.rs
+++ b/rust/cohort-seeder/src/store/chunks.rs
@@ -29,6 +29,7 @@ use crate::domain::{
};
use super::lease::LeaseHandle;
+use super::runs::RunKind;
use super::{Claimant, LeaseDuration, MaxAttempts, RenderedError, PERSISTED_ERROR_LIMIT};
/// Chunk statuses holding a live lease — the targets of the fenced heartbeat/fail/confirm writes.
@@ -268,10 +269,15 @@ impl PgChunkStore {
AND (c.next_attempt_at IS NULL OR c.next_attempt_at <= now()))
OR (c.status = $6 AND c.lease_expires_at < now())
OR (c.status = $5 AND c.lease_expires_at < now() AND c.attempts < $4))
- -- Cross-kind priority rides on this ordering: person chunks are planned under a
- -- far-future sentinel day, so behavioral work (readiness-gating, fence-sensitive)
- -- always drains first. Reordering here silently inverts that.
- ORDER BY c.day, c.band
+ -- `r.backfill_kind = $9` is true only for person runs, and `false` sorts first,
+ -- so behavioral chunks (readiness-gating, fence-sensitive) claim before person
+ -- chunks. The kind key must lead: person chunks sit on a far-future sentinel day,
+ -- which `day DESC` alone would claim first. Newest day first lets a short-window
+ -- cohort, whose days are all recent, finish without waiting behind a long run's
+ -- older days. Claimable trailing days have no key of their own and sort among the
+ -- newest days, because their cohorts already serve as ready and under-count the
+ -- boundary day until the trailing tiles apply.
+ ORDER BY (r.backfill_kind = $9), c.day DESC, c.band
LIMIT 1
FOR UPDATE OF c SKIP LOCKED
)
@@ -302,6 +308,7 @@ impl PgChunkStore {
.bind(ChunkStatus::Produced.as_str())
.bind(ChunkStatus::Pending.as_str())
.bind(ChunkStatus::Failed.as_str())
+ .bind(RunKind::PersonProperty.as_str())
.fetch_optional(&self.pool)
.await?;
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index fe29578b3ba2..3b3a5967c45d 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -1810,19 +1810,30 @@ async fn person_planning_is_all_or_nothing_and_idempotent() -> Result<()> {
.await
}
-/// The sentinel day makes person chunks claim strictly after behavioral days on the shared claim
-/// loop, and a person claim decodes its range with `num_bands` = the run's chunk count.
+/// Behavioral days claim newest first across runs, and person chunks claim strictly after every
+/// behavioral day on the shared claim loop even though their sentinel day is the newest. A person
+/// claim decodes its range with `num_bands` = the run's chunk count.
#[tokio::test]
-async fn person_chunks_claim_after_behavioral_days_and_carry_ranges() -> Result<()> {
+async fn behavioral_days_claim_newest_first_then_person_chunks_with_ranges() -> Result<()> {
with_db(|pool| async move {
let behavioral_run =
insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ // Another team, because a team holds one active team-scoped run per kind.
+ let other_team_run =
+ insert_run(&pool, 3, "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, historical([100]), ONE_BAND)
+ .plan_chunks(behavioral_run, historical([98, 100]), ONE_BAND)
+ .await?
+ )? == 2
+ );
+ ensure!(
+ planned_count(
+ store
+ .plan_chunks(other_team_run, historical([99]), ONE_BAND)
.await?
)? == 1
);
@@ -1832,42 +1843,54 @@ async fn person_chunks_claim_after_behavioral_days_and_carry_ranges() -> Result<
let lease60 = LeaseDuration::new(Duration::from_secs(60))?;
let attempts5 = MaxAttempts::new(5)?;
- let run_ids = [behavioral_run, person_run];
+ let run_ids = [behavioral_run, other_team_run, person_run];
let claimant = Claimant::new("worker-a")?;
- let first = store
- .claim_next(&run_ids, &claimant, lease60, attempts5)
- .await?
- .context("behavioral chunk was not claimed first")?;
- ensure!(first.chunk.spec().lease.run_id() == behavioral_run);
- ensure!(first.chunk.spec().person_range.is_none());
+ let mut behavioral_claims = Vec::new();
+ for _ in 0..3 {
+ let claim = store
+ .claim_next(&run_ids, &claimant, lease60, attempts5)
+ .await?
+ .context("behavioral chunk was not claimed before person chunks")?;
+ ensure!(claim.chunk.spec().person_range.is_none());
+ behavioral_claims.push((claim.chunk.spec().lease.run_id(), claim.chunk.spec().day));
+ }
+ ensure!(
+ behavioral_claims
+ == [
+ (behavioral_run, 100),
+ (other_team_run, 99),
+ (behavioral_run, 98)
+ ],
+ "expected newest day first across runs, got {behavioral_claims:?}"
+ );
- let second = store
+ let first_person = store
.claim_next(&run_ids, &claimant, lease60, attempts5)
.await?
.context("first person chunk was not claimed")?;
- let second_spec = second.chunk.spec();
- ensure!(second_spec.lease.run_id() == person_run);
- ensure!(second_spec.band.band() == 0);
- ensure!(second_spec.band.num_bands().get() == 2);
- let second_range = second_spec
+ let first_person_spec = first_person.chunk.spec();
+ ensure!(first_person_spec.lease.run_id() == person_run);
+ ensure!(first_person_spec.band.band() == 0);
+ ensure!(first_person_spec.band.num_bands().get() == 2);
+ let first_person_range = first_person_spec
.person_range
.context("person claim lost its range")?;
- ensure!(second_range.lo() == Uuid::nil());
- ensure!(second_range.hi() == Some(boundary));
+ ensure!(first_person_range.lo() == Uuid::nil());
+ ensure!(first_person_range.hi() == Some(boundary));
- let third = store
+ let second_person = store
.claim_next(&run_ids, &claimant, lease60, attempts5)
.await?
.context("second person chunk was not claimed")?;
- let third_range = third
+ let second_person_range = second_person
.chunk
.spec()
.person_range
.context("person claim lost its range")?;
- ensure!(third_range.lo() == boundary);
- ensure!(third_range.hi().is_none());
- drop((first, second, third));
+ ensure!(second_person_range.lo() == boundary);
+ ensure!(second_person_range.hi().is_none());
+ drop((first_person, second_person));
Ok(())
})
.await