Skip to content

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

fix(cohorts): never certify a reconcile from a slice missing history (#114526)

Matheus Batista4dcd46e1cf48
diff --git a/docs/internal/realtime-cohorts/backfill-coordination.md b/docs/internal/realtime-cohorts/backfill-coordination.md
index 75f66da49e55..f35ad3466635 100644
--- a/docs/internal/realtime-cohorts/backfill-coordination.md
+++ b/docs/internal/realtime-cohorts/backfill-coordination.md
@@ -161,7 +161,11 @@ Missing one of them fails quietly, so they are worth knowing.
| Behavioral scan limit | `create_cohort_backfill_run` refuses a behavioral team run when its pinned event names had more events than `BEHAVIORAL_BACKFILL_MAX_SCAN_EVENTS_PER_DAY` on the busiest of the last 7 complete UTC days. `--max-scan-events-per-day` overrides it for one invocation, and 0 skips the count and the check. The save path does not check it |
The Rust services have their own switches, and Django cannot see them.
-Two of them gate person runs, and they must open in order.
+A team must reach the processor's copy of `REALTIME_COHORT_TEAM_ALLOWLIST` before the seeder's.
+A processor that does not hold the team withholds every reconcile request of its runs with `team_absent`, and the seeder supersedes those participations.
+No new run is owed afterwards, so the team never becomes ready until an operator creates one.
+`seeder_reconcile_cohorts_withheld_total{reason="team_absent"}` shows that this happened.
+Two of the switches gate person runs, and they must open in order.
The processor's `COHORT_SEED_PERSON_APPLY_ENABLED` must be on everywhere before the seeder's `SEEDER_PERSON_SEEDS_ENABLED`, or the processor skips and commits the seeds.
The seeder's switch must be on before a team with person-leaf cohorts joins the trigger allowlist.
Until it is, the seeder never discovers person runs, so each one waits in `awaiting_boundary`, holding its cohort's run slot.
@@ -230,9 +234,9 @@ Other cases to know:
- **A cohort leaves the realtime set mid-run.**
A soft delete, a switch to static, or losing realtime support skips hash maintenance, so Django does not supersede the run, and the finalizer does not re-check `deleted` or `cohort_type`.
At its next catalog refresh the processor drops a cohort that is deleted or no longer `realtime`.
- It then discards each of the cohort's reconcile requests without a marker, once a catalog refresh that began after the request arrived has run.
- So the run stamps only if every marker landed first.
- Otherwise a soft delete ends with the seeder superseding the participation, and losing realtime support leaves a retryable shortfall that holds the run in `reconciling`.
+ It then withholds each of the cohort's reconcile requests with a `reconcile_withheld` marker, once a catalog refresh that began after the request arrived has run.
+ So the run stamps only if every completion marker landed first.
+ Otherwise the seeder supersedes the participation when it reads a withheld marker, and the run finishes without the cohort.
- **A cohort re-enters the realtime set without a leaf change.**
An undelete, a static-to-dynamic switch, or regained realtime support leaves the hashes as they were, so no run is owed, and the cohort keeps whatever stamps it had.
- **A save from a stale copy of the row.**
diff --git a/docs/internal/realtime-cohorts/backfill-overview.md b/docs/internal/realtime-cohorts/backfill-overview.md
index 7639d9ded006..c0babf24956f 100644
--- a/docs/internal/realtime-cohorts/backfill-overview.md
+++ b/docs/internal/realtime-cohorts/backfill-overview.md
@@ -108,6 +108,8 @@ It affects every behavioral leaf: a matching event in the gap is missing from th
For a disaster-recovery run the operator must pin `B`, at the point where live coverage restarted after the store loss.
Without it the run waits in `awaiting_boundary`.
+That point is the `covered_since` instant of the `reconcile_withheld` markers the lost partitions produce, which the seeder also records in each withheld participation's error.
+The processor applies the same rule to every run: a partition whose history begins after a run's `B` withholds that run.
### Rule 2: tiles are absolute counts, merged with max
@@ -197,7 +199,7 @@ Downstream, the membership consumer also uses the full snapshot to find and dele
[Membership output and readers](membership-output-and-readers.md) explains that sweep.
A reconcile request carries the pinned shape hash of the run's kind.
-A processor whose catalog holds a different hash for that kind discards the request without a marker, after a catalog refresh that began after the request arrived.
+A processor whose catalog holds a different hash for that kind withholds the request with a `reconcile_withheld` marker, after a catalog refresh that began after the request arrived.
That hash is the processor's only check on the definition.
The walk composes the cohort's current tree, so an edit that leaves this kind's hash alone does not stop it.
The final guard against stamping a stale definition is Django's: supersession on edit, and the finalizer's hash and composition checks.
@@ -299,5 +301,5 @@ A backlog, a failure or a slow catalog refresh makes it longer.
- A chunk is confirmed when Kafka acknowledges its seeds, not when the processor applies them.
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 discarded without a marker only if that refresh still disagrees.
+ 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.
diff --git a/docs/internal/realtime-cohorts/completion-and-readiness.md b/docs/internal/realtime-cohorts/completion-and-readiness.md
index 0da3cc674bd5..fa7b578234f9 100644
--- a/docs/internal/realtime-cohorts/completion-and-readiness.md
+++ b/docs/internal/realtime-cohorts/completion-and-readiness.md
@@ -11,6 +11,7 @@ It uses terms from [backfill overview](backfill-overview.md) and [backfill coord
The processor may still be holding tiles behind the fence, and reconcile may not have re-told downstream yet.
A run is complete for a cohort only when **every one of the 64 processor partitions** has finished reconciling that cohort for this run.
Each partition proves it by producing a `reconcile_complete` marker.
+A partition that cannot certify the run says so with a `reconcile_withheld` marker instead, and the seeder supersedes that cohort's participation.
Completion is split three ways:
@@ -30,8 +31,12 @@ sequenceDiagram
S->>M: record the marker topic's start positions
S->>K: one reconcile request per cohort per partition
S->>PG: record request offsets and dispatch epoch
- P->>M: reconcile_complete (cohort, run, partition)
- S->>M: watcher folds markers into per-cohort bitmaps
+ alt the partition can certify the run
+ P->>M: reconcile_complete (cohort, run, partition)
+ else the catalog or the partition's slice rules it out
+ P->>M: reconcile_withheld (cohort, run, partition, reason)
+ end
+ S->>M: watcher folds markers into per-cohort bitmaps, supersedes withheld cohorts
opt a cohort is short
S->>K: read the processor's committed seed offsets
S->>M: capture the marker topic's ends, read up to them
@@ -90,6 +95,16 @@ When a cohort reaches 64 of 64, the watcher writes its bits to Postgres at once
That write records the bits only.
The observation pass, below, decides when the participation is marked complete.
+A `reconcile_withheld` marker is a final answer for its cohort, so it needs no settlement proof.
+The watcher supersedes the participation, with an error naming the partition and the reason.
+The first withheld marker of a cohort decides the error.
+A withheld marker from a partition that already certified the cohort is ignored, because a later refusal cannot revoke that certificate.
+A participation that already completed or carries a readiness stamp is left alone.
+For `partial_coverage`, the error also names the instant the partition's history begins, which is the boundary a [disaster-recovery run](backfill-overview.md) needs.
+
+The supersede rides the same transaction that persists the bits and the watcher's read positions.
+A restarted watcher resumes from the persisted positions, so a verdict persisted any later would be skipped.
+
## Deciding the outcome
When every active participation of the run has all 64 bits, the next observation pass marks them all **complete**, and no further check is needed.
@@ -101,7 +116,8 @@ It proves that in two steps.
1. **Liveness.**
The processor's seed consumer must have committed past every reconcile request on all 64 partitions.
The processor produces a partition's marker, and waits for its acknowledgment, before it lets that request's offset be committed.
- A request the processor discarded, after a catalog refresh that began after the request arrived, or skipped because reconcile is disabled, is committed with no marker.
+ A request the processor withholds is committed only after its withheld marker is acknowledged, too.
+ Only a request skipped because reconcile is disabled is committed with no marker.
So after this point every marker of the dispatch is already on the marker topic.
2. **Read to the end.**
The seeder records the marker topic's current end, and waits until the watcher has read that far.
@@ -115,7 +131,8 @@ Each short participation gets one of these outcomes:
| Markers missing, and the cohort's current shape hash for this kind still equals the pinned one | Retryable shortfall: an error is recorded, and the participation stays open |
| Markers missing, and this kind's shape hash moved or cannot be read, or the cohort is deleted | Superseded |
-Missing markers with an unchanged hash usually mean the processor skipped the request because reconcile was disabled on it, or discarded it after a catalog refresh that began after the request arrived.
+Missing markers with an unchanged hash usually mean the processor skipped the request because reconcile was disabled on it.
+A withheld cohort is never short: its participation is superseded before the run settles, so the finalizer finishes the run without it.
An edit that moved only the other kind's hash also leaves this kind's hash unchanged and gives a retryable shortfall.
A composition-only edit that owes this kind a repair run is different: Django supersedes the participation when the edit commits, so the seeder never settles it.
For a behavioral participation, that is any composition-only edit on a cohort with a hashed behavioral leaf.
diff --git a/docs/internal/realtime-cohorts/invariants.md b/docs/internal/realtime-cohorts/invariants.md
index a092bf9ae25f..794f5be0cbd5 100644
--- a/docs/internal/realtime-cohorts/invariants.md
+++ b/docs/internal/realtime-cohorts/invariants.md
@@ -189,10 +189,14 @@ Most of these are not enforced by a single test, and a violation usually shows u
- Why: live output is at most once, so only a full re-telling repairs downstream, and a stale definition must never be certified.
- Kept by: the walk emits members and explicit non-members alike, and each request carries the pinned shape hash of its kind, checked on every drain.
+ The request also carries its run's boundary, and the guard withholds it when the partition's [slice coverage](state-store-and-durability.md#slice-coverage) begins after that boundary.
+ A withheld request emits a `reconcile_withheld` marker and no rows.
- Limit: the walk composes the processor's current tree, and the guard ignores the composition and the other kind's hash.
Django's finalizer checks those before it stamps.
- Limit: the walk covers only rows the store holds.
It cannot restore a skipped event or find a person whose first Stage 2 row was never written.
+ Coverage catches a slice that lost its history, but not a stale slice, one whose partition another writer advanced while this store held older state.
+ Nothing in one pod produces a stale slice except a rollback of the store or a checkpoint restore.
**25. A run completes only with proof.**
diff --git a/docs/internal/realtime-cohorts/membership-output-and-readers.md b/docs/internal/realtime-cohorts/membership-output-and-readers.md
index 104a3b2c7923..9744d8d963f1 100644
--- a/docs/internal/realtime-cohorts/membership-output-and-readers.md
+++ b/docs/internal/realtime-cohorts/membership-output-and-readers.md
@@ -48,8 +48,26 @@ Its compiled default is `cohort_membership_changed_shadow`, which only a parity
}
```
-The seeder reads markers to decide run completion.
+A partition that cannot certify the run produces a withheld marker under the same key instead, and no reconcile rows:
+
+```json
+{
+ "type": "reconcile_withheld",
+ "team_id": 7,
+ "cohort_id": 42,
+ "partition": 17,
+ "run_id": "01928c3e-...",
+ "reason": "partial_coverage",
+ "covered_since_ms": 1791547200000
+}
+```
+
+`reason` is `partial_coverage`, `team_absent`, `cohort_absent`, `not_emitting`, `hash_unknown` or `hash_mismatch`.
+`covered_since_ms` comes only with `partial_coverage`: it is when the partition's history begins.
+
+The seeder reads markers to decide run completion, and supersedes a withheld cohort's participation.
The membership consumer reads them to decide when stale rows may be deleted.
+It counts a withheld marker and otherwise ignores it, so that run never collects every marker, and its row stays `collecting` until it is abandoned.
The 64 processor partitions that markers count are unrelated to the partitions of the membership topic, which has its own count.
@@ -156,7 +174,7 @@ Taking the lower of the two can only make the sweep delete less.
The consumer knows nothing about Django's supersession.
A run that an edit superseded after its reconcile was dispatched can still collect all 64 markers.
-The processor discards the remaining requests only when the edit moved the shape hash of the run's kind, after a catalog refresh that began after each request arrived, and it cannot take back markers it already produced.
+The processor withholds the remaining requests only when the edit moved the shape hash of the run's kind, after a catalog refresh that began after each request arrived, and it cannot take back markers it already produced.
A run with every marker sweeps like any other run.
A run whose markers stay incomplete never leaves `collecting`, and it is abandoned after a few days.
@@ -165,6 +183,7 @@ A run whose markers stay incomplete never leaves `collecting`, and it is abandon
After a swept reconcile, the table holds the processor's Stage 2 state for the cohort, plus any row written at or after the reconcile began.
It converges to what the processor believes, not to the cohort's definition.
A true member for whom the processor holds no Stage 2 row gets no reconcile row, and the sweep deletes their old row.
+A partition whose slice lost its history after the run's boundary is the large case of this, so it withholds its marker instead of reconciling, and the sweep never runs for that run.
Some rows are never swept:
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.md
index 15316eef7308..5352fec00f08 100644
--- a/docs/internal/realtime-cohorts/processor-runtime.md
+++ b/docs/internal/realtime-cohorts/processor-runtime.md
@@ -182,6 +182,7 @@ If a cooperative rebalance hands the partition straight back, the cleanup is ski
State never moves with a partition.
Whoever owns the partition next, even the same pod later, starts from an empty slice at the last committed offset.
It rebuilds no history, so every cohort on that partition is wrong until a backfill runs.
+The slice's coverage record goes with it, so the new slice withholds every reconcile whose run boundary is earlier than its start.
That is why the processor runs as a single pod that owns every partition.
Nothing moves state between pods, so more than one replica is unsupported, and running two would corrupt state without any error.
@@ -302,6 +303,9 @@ Three variations show the edges.
Anything processed since the last commit replays on the next owner.
- A held offset stays held for the rest of the partition's tenure.
With one pod, that means until the next restart, and the symptom is growing lag on that topic and partition.
+- A created store withholds every reconcile whose run boundary predates its slices, because each slice begins when its partition is assigned.
+ In an environment that wipes the store at every start, that is every run created before the last boot, and `cohort_slices_begun_total` rises at every boot.
+ [Slice coverage](state-store-and-durability.md#slice-coverage) covers the records and their metrics.
- A timer message does not spawn a worker.
Without durable restore that costs nothing, because the store starts empty.
With durable restore, boot spawns a worker for every owned partition, so overdue evictions run from boot.
diff --git a/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md b/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
index a80f7d005fb7..d8554ca3fa17 100644
--- a/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
+++ b/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
@@ -160,13 +160,20 @@ Each worker keeps a queue of reconcile jobs.
A timer sends a drain message down every worker's live lane every couple of seconds while any job exists, and each drain advances the head job by one page.
1. **Guard**, checked on every drain.
- The job is discarded without a marker if the team or cohort left the catalog, if the cohort no longer emits membership, or if its current shape hash for the run's kind is missing or differs from the pinned one.
- It is discarded only after a catalog refresh that began after the request arrived, because each of these misses can mean the catalog has not yet read the cohort's latest write.
+ The job is withheld if the team or cohort left the catalog, if the cohort no longer emits membership, or if its current shape hash for the run's kind is missing or differs from the pinned one.
+ It is withheld only after a catalog refresh that began after the request arrived, because each of these misses can mean the catalog has not yet read the cohort's latest write.
Until such a refresh, and before the first catalog load, the job waits, and so do the jobs queued behind it on that partition.
The wait counts once per job in `cohort_reconcile_jobs_deferred_total`.
The refresh reads the Postgres reader, so this holds while reader lag stays shorter than the delay from the write to the request's arrival.
The guard checks only that one hash.
The walk composes the cohort's tree from the processor's current catalog, so an edit that changes only the composition, or only the other kind's leaves, does not stop it.
+ When the catalog lets the job proceed, the guard then checks the partition's [slice coverage](state-store-and-durability.md#slice-coverage).
+ The job is withheld when the slice's history begins after the run's boundary, or when the request carries no boundary and the slice does not hold its whole history.
+ That check runs before the scan, because rows emitted from such a slice would re-assert its partial answers downstream.
+ A withheld job produces one `reconcile_withheld` marker with the reason, then releases its seed offset once the marker is acknowledged.
+ Consecutive withheld jobs at the head of the queue share one produce of up to one scan page, so a burst of them costs the drain one broker round trip per tick.
+ A failed produce keeps the job, and the jobs behind it, at the head of the queue, and the guard decides them again on the next drain.
+ `cohort_reconcile_jobs_discarded_total{reason}` counts withheld jobs.
2. **Scanning.**
Read the next page of the cohort's Stage 2 rows on this partition.
Recompute each row from stored leaf state and emit it, `entered` or `left`, tagged `origin: reconcile` with the run id, whether or not it changed.
@@ -214,7 +221,7 @@ The committable offset is the lowest of the processed offset, any held offset, a
| A membership produce fails | Hold. At the next rebalance or restart the redelivered seed emits the change again, through the pre-written row for single-leaf cohorts and the unwritten Stage 2 bit for composed ones |
| The processor crashes mid-run | Nothing was committed past the run, so it replays. Every step is idempotent |
| A tile is redelivered | `max` of the same count changes nothing |
-| The cohort is edited mid-run | Old tiles whose hash still maps to a leaf are max-merged into the current leaves, harmlessly. Old reconcile requests are discarded if the edit changed the shape hash for their kind. Otherwise they walk the current definition |
+| The cohort is edited mid-run | Old tiles whose hash still maps to a leaf are max-merged into the current leaves, harmlessly. Old reconcile requests are withheld if the edit changed the shape hash for their kind. Otherwise they walk the current definition |
| A restart interrupts a reconcile | The job's cursor lives in memory, so the replayed request walks the cohort again from the start |
| A reconcile page's produce or commit fails | The same page retries on the next drain, and its rows are emitted again |
| A marker produce fails | The worker retries on the next drain |
diff --git a/docs/internal/realtime-cohorts/seeder.md b/docs/internal/realtime-cohorts/seeder.md
index d89ea3b55902..af2893d856f6 100644
--- a/docs/internal/realtime-cohorts/seeder.md
+++ b/docs/internal/realtime-cohorts/seeder.md
@@ -276,6 +276,7 @@ When every chunk of a run is confirmed and the planning proof is stamped, the se
If unconfirmed chunks show up after the move anyway, it reverts the run to `seeding`.
A watcher then tails the marker topic and records, per participation, which partitions have reported.
+A `reconcile_withheld` marker instead supersedes its participation at once, in the same transaction that records the watcher's position, and counts `seeder_reconcile_cohorts_withheld_total{kind, reason}`.
When every cohort of the run has all 64 markers, the seeder marks them all complete at once, with no further check.
To call a cohort short, the seeder first needs proof that no more markers are coming: the processor's seed consumer must have committed past every reconcile request, and the watcher must have read the marker topic to the end captured after that.
Until that proof arrives, the run's complete cohorts wait with the short ones.
diff --git a/docs/internal/realtime-cohorts/state-store-and-durability.md b/docs/internal/realtime-cohorts/state-store-and-durability.md
index 6ed5b45b36b4..fea75965bac2 100644
--- a/docs/internal/realtime-cohorts/state-store-and-durability.md
+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md
@@ -128,16 +128,17 @@ A live store that fails to open does not fall back either: the pod fails to star
A cold start does not rebuild history.
The consumers resume at their committed offsets, so the store only fills from new traffic, and every cohort's past membership has to come back through a backfill.
+Its slices begin when their partitions are assigned, so the processor withholds every run whose boundary is earlier (see [slice coverage](#slice-coverage)).
A backfill cannot bring back everything.
`performed_event` leaves with an hour or minute window refill only from new live events, and a cohort made only of references refills through cascades from the backfills of the cohorts it references.
With durable restore on, the processor also:
-- deletes the slices of partitions it no longer owns, once its assignment settles,
+- deletes the slices of partitions it no longer owns, with their coverage records, once its assignment settles,
- re-produces every transfer still waiting in the merge outbox,
- seeks every owned events partition back to the first event it polled during boot and did not dispatch,
- spawns a worker for every owned partition when boot ends, and each worker rebuilds its in-memory eviction queue from its behavioral rows,
-- wipes the old slice of a partition that moves in after boot, before its worker spawns.
+- wipes the old slice of a partition that moves in after boot, with its coverage record, before its worker spawns, so the slice begins anew.
Nothing is dispatched to a worker, from the events consumer or a follower, until these boot steps end.
[Processor runtime](processor-runtime.md#startup) lists them in order.
@@ -149,10 +150,43 @@ A failed attempt only logs a warning, and a checkpoint with no offsets for the t
Either way the follower resumes at its broker-stored offsets.
Those can be ahead of the restored state, and the inputs in between are never applied.
-When a partition is revoked, its worker drains and exits, and its slice is deleted.
+When a partition is revoked, its worker drains and exits, and its slice is deleted with its coverage record.
State never moves between pods, which is why the processor runs as a single pod.
[Processor runtime](processor-runtime.md#rebalance-and-the-single-pod-constraint) explains that constraint.
+## Slice coverage
+
+A slice is one partition's state in one store.
+A slice that lost its history looks like any other empty slice, so each slice carries a coverage record.
+The record says either that the slice is complete, or that it holds every event its partition delivered after an instant, and maybe some before.
+It lives in `cf_person_records` under a 3-byte key, `[partition][0xFE]`, which no person-record read reaches.
+
+| What happens | Coverage |
+| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
+| The store is created: none on disk, a wipe at start, a wipe on schema mismatch, or a failed restore | The open stamps `cf_meta[slice_coverage]`, with no records. Each slice begins when its partition is assigned |
+| A store with the stamp reopens | Each slice resumes its own record |
+| A store without the stamp reopens | It predates coverage records. The open writes `complete` for every partition and the stamp in one batch, so it adopts once |
+| A revoke, the boot deletion of an unowned partition, or a move-in wipe | `delete_partition` deletes the record with the slice, and the next worker begins the slice anew from its assignment |
+| A checkpoint restore | The record and the stamp travel inside the checkpoint. A checkpoint from before coverage records is adopted |
+
+A reconcile certifies its partition only when the slice holds the run's history: the slice is complete, or it began at or before the run's boundary.
+Otherwise the partition withholds the run, as [the reconcile guard](seed-apply-and-reconcile.md#the-walk) describes, and its `covered_since` is the boundary a disaster-recovery run must pin.
+
+The record is written once and only deleted with its slice.
+An older image never reads the record or the stamp, and its own partition deletes remove records with their slices.
+A rolled-back image that recreates the store leaves a store without the stamp, and the next open adopts it as complete.
+That is the trust every store had before coverage records existed.
+So before rolling forward again, wipe any store that an older image created.
+
+Coverage does not detect a stale slice, one whose partition another writer advanced while this store held older state.
+With one pod, only a rollback of the store or a checkpoint restore produces one.
+
+Three metrics follow coverage:
+
+- `cohort_slices_adopted_total` rises by the partition count at an adopting open,
+- `cohort_slices_begun_total` counts slices that began without earlier history,
+- `cohort_slice_covered_since_seconds{partition}` is when each owned slice began, and 0 for a complete one.
+
## Keeping the store bounded
- **Behavioral rows** leave through the sweep, which deletes rows that aged out and emits `left` on the way.
diff --git a/nodejs/src/cdp/services/cohort-membership/sweeper.service.serial.test.ts b/nodejs/src/cdp/services/cohort-membership/sweeper.service.serial.test.ts
index c94ad02c7c30..e361395cfab6 100644
--- a/nodejs/src/cdp/services/cohort-membership/sweeper.service.serial.test.ts
+++ b/nodejs/src/cdp/services/cohort-membership/sweeper.service.serial.test.ts
@@ -1,8 +1,10 @@
import { Message } from 'node-rdkafka'
+import { register } from 'prom-client'
import { defaultConfig } from '~/common/config/config'
import { KAFKA_COHORT_RECONCILE_MARKERS } from '~/common/config/kafka-topics'
import { PostgresRouter, PostgresUse } from '~/common/utils/db/postgres'
+import { logger } from '~/common/utils/logger'
import { UUIDT } from '~/common/utils/utils'
import { resetBehavioralCohortsDatabase } from '../../../../tests/helpers/sql'
@@ -168,6 +170,27 @@ describe('CohortMembershipSweeper', () => {
expect(markers.map((marker) => marker.partition)).toEqual([0])
})
+ it('should count a withheld marker without warning, since it is an outcome and not a bad message', async () => {
+ const withheldCount = async (): Promise<number> =>
+ (await register.getSingleMetric('cdp_cohort_membership_markers_consumed')?.get())?.values.find(
+ (value) => value.labels.outcome === 'withheld'
+ )?.value ?? 0
+ const before = await withheldCount()
+ const warn = jest.spyOn(logger, 'warn')
+ try {
+ const markers = sweeper.parseMarkers([
+ markerMessage(0),
+ markerMessage(1, { type: 'reconcile_withheld', reason: 'partial_coverage', covered_since_ms: 1 }),
+ ])
+
+ expect(markers.map((marker) => marker.partition)).toEqual([0])
+ expect(warn).not.toHaveBeenCalled()
+ expect((await withheldCount()) - before).toBe(1)
+ } finally {
+ warn.mockRestore()
+ }
+ })
+
it('should union marker bits and turn the run claimable only once the set is complete', async () => {
const partitions = Array.from({ length: COHORT_PARTITION_COUNT }, (_, partition) => partition)
diff --git a/nodejs/src/cdp/services/cohort-membership/sweeper.service.ts b/nodejs/src/cdp/services/cohort-membership/sweeper.service.ts
index 896fef73b9ed..b5830c7057f7 100644
--- a/nodejs/src/cdp/services/cohort-membership/sweeper.service.ts
+++ b/nodejs/src/cdp/services/cohort-membership/sweeper.service.ts
@@ -65,6 +65,16 @@ const ReconcileCompleteMarkerSchema = z.object({
export type ReconcileCompleteMarker = z.infer<typeof ReconcileCompleteMarkerSchema>
+/** A withheld run never collects every marker, so it is never swept. */
+const ReconcileWithheldMarkerSchema = z.object({
+ type: z.literal('reconcile_withheld'),
+})
+
+const ReconcileMarkerSchema = z.discriminatedUnion('type', [
+ ReconcileCompleteMarkerSchema,
+ ReconcileWithheldMarkerSchema,
+])
+
/** Membership-topic high watermarks at marker completeness, keyed by partition. */
export type MembershipWatermarks = Record<number, number>
@@ -196,7 +206,7 @@ export class CohortMembershipSweeper {
continue
}
- const parsed = ReconcileCompleteMarkerSchema.safeParse(parseJSON(value))
+ const parsed = ReconcileMarkerSchema.safeParse(parseJSON(value))
if (!parsed.success) {
markersConsumed.inc({ outcome: 'skipped' })
logger.warn('Skipping unusable reconcile marker', {
@@ -204,6 +214,10 @@ export class CohortMembershipSweeper {
})
continue
}
+ if (parsed.data.type === 'reconcile_withheld') {
+ markersConsumed.inc({ outcome: 'withheld' })
+ continue
+ }
markersConsumed.inc({ outcome: 'parsed' })
markers.push(parsed.data)
diff --git a/products/cohorts/backend/parity/fold.py b/products/cohorts/backend/parity/fold.py
index 3b6d2aa62da4..006772f411e5 100644
--- a/products/cohorts/backend/parity/fold.py
+++ b/products/cohorts/backend/parity/fold.py
@@ -15,6 +15,7 @@ from typing import Any, Optional, TypeGuard
from uuid import UUID
RECONCILE_COMPLETE_TYPE = "reconcile_complete"
+RECONCILE_WITHHELD_TYPE = "reconcile_withheld"
RECONCILE_PARTITION_COUNT = 64
LIVE_ORIGIN = "live"
@@ -32,6 +33,8 @@ class ReconcileRunCompleteness:
run_id: str
cohort_id: int
partitions_seen: int
+ # (partition, reason) pairs, sorted by partition.
+ withheld: tuple[tuple[int, str], ...] = ()
@property
def expected_partitions(self) -> int:
@@ -41,8 +44,16 @@ class ReconcileRunCompleteness:
def complete(self) -> bool:
return self.partitions_seen == RECONCILE_PARTITION_COUNT
+ @property
+ def summary(self) -> str:
+ seen = f"{self.partitions_seen}/{self.expected_partitions}"
+ state = seen if self.complete else f"partial {seen}"
+ if not self.withheld:
+ return state
+ return f"{state}, withheld " + ", ".join(f"p{partition} {reason}" for partition, reason in self.withheld)
+
-@dataclass
+@dataclass(frozen=False)
class FoldStats:
total: int = 0
folded: int = 0
@@ -52,6 +63,8 @@ class FoldStats:
dropped_after_until: int = 0
cohorts_seen: set[int] = field(default_factory=set)
reconcile_markers: dict[tuple[str, int], set[int]] = field(default_factory=dict)
+ # {(run_id, cohort_id): {partition: reason}}
+ reconcile_withheld: dict[tuple[str, int], dict[int, str]] = field(default_factory=dict)
# Count of accepted marker messages, incl. duplicates — the reconcile_markers set dedups by
# partition, so it undercounts. This keeps folded + drops + markers == total (markers land in
# neither the folded nor the dropped buckets).
@@ -122,6 +135,25 @@ def _record_marker(
stats.cohorts_seen.add(cohort_id)
+def _record_withheld(message: dict[str, Any], cohort_id: Any, stats: FoldStats) -> None:
+ run_id = _parse_marker_run_id(message.get("run_id"))
+ partition = message.get("partition")
+ reason = _optional_string(message.get("reason"))
+ if (
+ run_id is None
+ or not _is_int(cohort_id)
+ or not _is_int(partition)
+ or not 0 <= partition < RECONCILE_PARTITION_COUNT
+ or reason is None
+ ):
+ stats.dropped_malformed += 1
+ return
+ # Withheld markers carry no timestamp, so the since and until bounds do not apply.
+ stats.reconcile_withheld.setdefault((run_id, cohort_id), {})[partition] = reason
+ stats.reconcile_markers_recorded += 1
+ stats.cohorts_seen.add(cohort_id)
+
+
def _bound_for(
cohort_id: Any,
until: Optional[datetime],
@@ -165,6 +197,9 @@ def fold_membership_changes(
if message.get("type") == RECONCILE_COMPLETE_TYPE:
_record_marker(message, cohort_id, last_updated, since, bound, stats)
continue
+ if message.get("type") == RECONCILE_WITHHELD_TYPE:
+ _record_withheld(message, cohort_id, stats)
+ continue
person_id = message.get("person_id")
status = message.get("status")
@@ -204,9 +239,14 @@ def fold_membership_changes(
def reconcile_completeness_by_cohort(stats: FoldStats) -> dict[int, tuple[ReconcileRunCompleteness, ...]]:
"""Group deterministic per-run marker completeness by cohort in a single sorted pass."""
by_cohort: dict[int, list[ReconcileRunCompleteness]] = {}
- for (run_id, cohort_id), partitions in sorted(stats.reconcile_markers.items()):
+ for run_id, cohort_id in sorted(stats.reconcile_markers.keys() | stats.reconcile_withheld.keys()):
by_cohort.setdefault(cohort_id, []).append(
- ReconcileRunCompleteness(run_id=run_id, cohort_id=cohort_id, partitions_seen=len(partitions))
+ ReconcileRunCompleteness(
+ run_id=run_id,
+ cohort_id=cohort_id,
+ partitions_seen=len(stats.reconcile_markers.get((run_id, cohort_id), ())),
+ withheld=tuple(sorted(stats.reconcile_withheld.get((run_id, cohort_id), {}).items())),
+ )
)
return {cohort_id: tuple(runs) for cohort_id, runs in by_cohort.items()}
diff --git a/products/cohorts/backend/parity/report.py b/products/cohorts/backend/parity/report.py
index 219e6a46e7be..5b18bd0074e4 100644
--- a/products/cohorts/backend/parity/report.py
+++ b/products/cohorts/backend/parity/report.py
@@ -56,12 +56,7 @@ def format_notes(rows: Sequence[CohortComparison]) -> str:
def format_reconcile_notes(completeness: Sequence[ReconcileRunCompleteness]) -> tuple[str, ...]:
notes: list[str] = []
for run in sorted(completeness, key=lambda item: (item.run_id, item.cohort_id)):
- partition_summary = (
- f"{run.partitions_seen}/{run.expected_partitions}"
- if run.complete
- else f"partial {run.partitions_seen}/{run.expected_partitions}"
- )
- notes.append(f"reconcile run {run.run_id}: {partition_summary}")
+ notes.append(f"reconcile run {run.run_id}: {run.summary}")
return tuple(notes)
@@ -130,12 +125,7 @@ def format_recompute_notes(rows: Sequence[RecomputeComparison]) -> str:
lines = []
for r in _sorted_recompute_rows(rows):
for run in sorted(r.reconcile_runs, key=lambda item: item.run_id):
- state = (
- f"{run.partitions_seen}/{run.expected_partitions}"
- if run.complete
- else (f"partial {run.partitions_seen}/{run.expected_partitions}")
- )
- lines.append(f" cohort {r.cohort_id}: reconcile run {run.run_id}: {state}")
+ lines.append(f" cohort {r.cohort_id}: reconcile run {run.run_id}: {run.summary}")
for note in r.notes:
lines.append(f" cohort {r.cohort_id}: {note}")
if r.expires_by_day:
diff --git a/products/cohorts/backend/parity/test/test_fold.py b/products/cohorts/backend/parity/test/test_fold.py
index 63aaf5def21e..43f34c8fecda 100644
--- a/products/cohorts/backend/parity/test/test_fold.py
+++ b/products/cohorts/backend/parity/test/test_fold.py
@@ -52,6 +52,12 @@ def _marker_without(field: str) -> dict:
return marker
+def _withheld(partition: int, *, run_id: str = RUN_1, cohort_id: int = 10) -> dict:
+ marker = _marker(partition, run_id=run_id, cohort_id=cohort_id)
+ del marker["last_updated"]
+ return marker | {"type": "reconcile_withheld", "reason": "partial_coverage", "covered_since_ms": 1}
+
+
class TestFold(SimpleTestCase):
def test_last_message_wins_per_pair(self) -> None:
state, stats = fold_membership_changes(
@@ -214,22 +220,30 @@ class TestFold(SimpleTestCase):
# (41..64); its markers must stay under their own cohort so RUN_1 does not read as a
# false 64/64 for cohort 10.
messages.extend(_marker(partition, run_id=RUN_1, cohort_id=20) for partition in range(41, 64))
+ # Withheld markers stay out of the membership fold.
+ messages.append(_withheld(50, run_id=RUN_1))
+ messages.append(_withheld(3, run_id=RUN_2, cohort_id=30))
- _state, stats = fold_membership_changes(messages, team_id=2, since=SINCE)
+ state, stats = fold_membership_changes(messages, team_id=2, since=SINCE)
completeness = reconcile_completeness(stats, cohort_id=10)
self.assertEqual(
- [(run.run_id, run.partitions_seen, run.complete) for run in completeness],
- [(RUN_1, 41, False), (RUN_2, 64, True)],
+ [(run.run_id, run.partitions_seen, run.complete, run.withheld) for run in completeness],
+ [(RUN_1, 41, False, ((50, "partial_coverage"),)), (RUN_2, 64, True, ())],
)
self.assertEqual(
[(run.run_id, run.partitions_seen, run.complete) for run in reconcile_completeness(stats, cohort_id=20)],
[(RUN_1, 23, False)],
)
- # Counts every accepted marker message, including the RUN_1 partition-0 duplicate — 129,
- # not the 128 distinct partitions the completeness sets hold. Keeps the summary's
- # folded + drops + markers == total accounting exact.
- self.assertEqual(stats.reconcile_markers_recorded, 129)
+ self.assertEqual(
+ [(run.run_id, run.partitions_seen, run.withheld) for run in reconcile_completeness(stats, cohort_id=30)],
+ [(RUN_2, 0, ((3, "partial_coverage"),))],
+ )
+ self.assertEqual((state, stats.dropped_malformed), ({}, 0))
+ # Counts every accepted marker message, including the RUN_1 partition-0 duplicate and the
+ # two withheld markers — 131, not the 128 distinct partitions the completeness sets hold.
+ # Keeps the summary's folded + drops + markers == total accounting exact.
+ self.assertEqual(stats.reconcile_markers_recorded, 131)
@parameterized.expand(
[
@@ -241,6 +255,8 @@ class TestFold(SimpleTestCase):
("float_team_id", _marker(1) | {"team_id": 2.0}, 2, 1, 0),
("boolean_team_id", _marker(1, team_id=True), 1, 1, 0),
("before_since", _marker(1, ts="2026-07-07 18:59:59.999999"), 2, 0, 1),
+ ("withheld_out_of_range_partition", _withheld(64), 2, 1, 0),
+ ("withheld_empty_reason", _withheld(1) | {"reason": ""}, 2, 1, 0),
]
)
def test_invalid_or_stale_markers_cannot_certify_reconcile(
@@ -254,6 +270,7 @@ class TestFold(SimpleTestCase):
_state, stats = fold_membership_changes([marker], team_id=team_id, since=SINCE)
self.assertEqual(stats.reconcile_markers, {})
+ self.assertEqual(stats.reconcile_withheld, {})
self.assertEqual(stats.dropped_malformed, expected_malformed)
self.assertEqual(stats.dropped_before_since, expected_before_since)
diff --git a/products/cohorts/backend/parity/test/test_report.py b/products/cohorts/backend/parity/test/test_report.py
index 83102fe3c8a6..cf5e0db7d2dc 100644
--- a/products/cohorts/backend/parity/test/test_report.py
+++ b/products/cohorts/backend/parity/test/test_report.py
@@ -67,16 +67,22 @@ class TestReport(SimpleTestCase):
def test_reconcile_completeness_is_rendered_as_complete_or_partial_notes(self) -> None:
notes = format_reconcile_notes(
[
- ReconcileRunCompleteness(run_id="run-b", cohort_id=10, partitions_seen=41),
+ ReconcileRunCompleteness(
+ run_id="run-b", cohort_id=10, partitions_seen=41, withheld=((7, "partial_coverage"),)
+ ),
ReconcileRunCompleteness(run_id="run-a", cohort_id=10, partitions_seen=64),
]
)
- self.assertEqual(notes, ("reconcile run run-a: 64/64", "reconcile run run-b: partial 41/64"))
+ self.assertEqual(
+ notes,
+ ("reconcile run run-a: 64/64", "reconcile run run-b: partial 41/64, withheld p7 partial_coverage"),
+ )
row = _row(10, VERDICT_PASS, notes=notes)
self.assertEqual(
format_notes([row]),
- " cohort 10: reconcile run run-a: 64/64\n cohort 10: reconcile run run-b: partial 41/64",
+ " cohort 10: reconcile run run-a: 64/64\n"
+ " cohort 10: reconcile run run-b: partial 41/64, withheld p7 partial_coverage",
)
document = to_json([row], AggregateSummary(), {"team_id": 2})
self.assertEqual(document["cohorts"][0]["notes"], notes)
diff --git a/rust/cohort-core/src/seed/decode.rs b/rust/cohort-core/src/seed/decode.rs
index ffa55ebf47d4..533d22bf1ef3 100644
--- a/rust/cohort-core/src/seed/decode.rs
+++ b/rust/cohort-core/src/seed/decode.rs
@@ -65,7 +65,7 @@ mod tests {
use crate::filters::TeamId;
use crate::seed::{
BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, PersonShapeHash,
- ReconcileScope, ReconcileTile, RunId, SChunkMs, ScannedAtMs,
+ ReconcileScope, ReconcileTile, RunBoundaryMs, RunId, SChunkMs, ScannedAtMs,
};
use super::*;
@@ -95,6 +95,7 @@ mod tests {
.unwrap(),
),
RunId(Uuid::nil()),
+ RunBoundaryMs(1_783_470_000_000),
))
.unwrap()
}
@@ -140,6 +141,7 @@ mod tests {
.unwrap(),
),
RunId(Uuid::nil()),
+ RunBoundaryMs(1_783_470_000_000),
))
.unwrap();
assert_eq!(
diff --git a/rust/cohort-core/src/seed/ids.rs b/rust/cohort-core/src/seed/ids.rs
index 58076d651238..23035bc0a93c 100644
--- a/rust/cohort-core/src/seed/ids.rs
+++ b/rust/cohort-core/src/seed/ids.rs
@@ -7,6 +7,7 @@ use std::borrow::Borrow;
use std::fmt;
use std::str::FromStr;
+use chrono::Utc;
use serde::{Deserialize, Serialize};
use sqlx::Type;
use uuid::Uuid;
@@ -44,6 +45,22 @@ pub struct SChunkMs(pub i64);
#[sqlx(transparent)]
pub struct ScannedAtMs(pub i64);
+/// A run's boundary (epoch ms, Postgres clock).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct RunBoundaryMs(pub i64);
+
+/// When a slice began (epoch ms, processor clock).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct CoverageStartMs(pub i64);
+
+impl CoverageStartMs {
+ pub fn now() -> Self {
+ Self(Utc::now().timestamp_millis())
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ConditionHash([u8; 16]);
diff --git a/rust/cohort-core/src/seed/mod.rs b/rust/cohort-core/src/seed/mod.rs
index 5e6d0344310b..b94395c8cce5 100644
--- a/rust/cohort-core/src/seed/mod.rs
+++ b/rust/cohort-core/src/seed/mod.rs
@@ -17,10 +17,14 @@ pub mod reconcile;
pub mod tile;
pub use decode::{decode_seed, DecodedSeed};
-pub use ids::{ClaimEpoch, ConditionHash, ConditionHashError, RunId, SChunkMs, ScannedAtMs};
+pub use ids::{
+ ClaimEpoch, ConditionHash, ConditionHashError, CoverageStartMs, RunBoundaryMs, RunId, SChunkMs,
+ ScannedAtMs,
+};
pub use person::{PersonSeed, PersonSeedError, MAX_PERSON_SEED_HASHES};
pub use reconcile::{
- BehavioralShapeHash, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope, ReconcileTile,
- ReconcileTileError, ScopeKind, ShapeHashError, UnknownScopeKind,
+ BehavioralShapeHash, CatalogMiss, PersonShapeHash, ReconcileCompleteMarker, ReconcileMarker,
+ ReconcileScope, ReconcileTile, ReconcileTileError, ReconcileWithheldMarker, ScopeKind,
+ ShapeHashError, UnknownScopeKind, WithheldReason,
};
pub use tile::SeedTile;
diff --git a/rust/cohort-core/src/seed/reconcile.rs b/rust/cohort-core/src/seed/reconcile.rs
index 8994b4982e5a..1d5f43d1f4f2 100644
--- a/rust/cohort-core/src/seed/reconcile.rs
+++ b/rust/cohort-core/src/seed/reconcile.rs
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
use crate::filters::{CohortId, TeamId};
-use super::ids::RunId;
+use super::ids::{CoverageStartMs, RunBoundaryMs, RunId};
pub(super) const RECONCILE_SCHEMA_VERSION: u32 = 1;
pub(super) const RECONCILE_KIND: &str = "reconcile";
@@ -161,6 +161,7 @@ pub struct ReconcileTile {
cohort_id: CohortId,
scope: ReconcileScope,
run_id: RunId,
+ boundary: Option<RunBoundaryMs>,
}
impl ReconcileTile {
@@ -169,12 +170,14 @@ impl ReconcileTile {
cohort_id: CohortId,
scope: ReconcileScope,
run_id: RunId,
+ boundary: RunBoundaryMs,
) -> Self {
Self {
team_id,
cohort_id,
scope,
run_id,
+ boundary: Some(boundary),
}
}
@@ -193,10 +196,15 @@ impl ReconcileTile {
pub const fn run_id(&self) -> RunId {
self.run_id
}
+
+ /// `None` on a tile from an older seeder.
+ pub const fn boundary(&self) -> Option<RunBoundaryMs> {
+ self.boundary
+ }
}
/// The wire projection. Field order here is the wire order; the scope's kind picks the top-level
-/// `kind` string, so a behavioral tile's bytes stay identical to the pre-person contract.
+/// `kind` string, so a behavioral tile keeps the pre-person `"reconcile"` kind.
#[derive(Serialize)]
struct ReconcileTileOut<'a> {
schema_version: u32,
@@ -205,6 +213,8 @@ struct ReconcileTileOut<'a> {
cohort_id: i32,
filters_hash: &'a str,
run_id: RunId,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ boundary_ms: Option<RunBoundaryMs>,
}
impl Serialize for ReconcileTile {
@@ -219,6 +229,7 @@ impl Serialize for ReconcileTile {
cohort_id: self.cohort_id.0,
filters_hash: self.scope.hash_str(),
run_id: self.run_id,
+ boundary_ms: self.boundary,
}
.serialize(serializer)
}
@@ -236,6 +247,7 @@ struct ReconcileTileWire {
cohort_id: i32,
filters_hash: String,
run_id: RunId,
+ boundary_ms: Option<RunBoundaryMs>,
}
impl TryFrom<ReconcileTileWire> for ReconcileTile {
@@ -250,12 +262,13 @@ impl TryFrom<ReconcileTileWire> for ReconcileTile {
source,
}
})?;
- Ok(Self::new(
- TeamId(wire.team_id),
- CohortId(wire.cohort_id),
+ Ok(Self {
+ team_id: TeamId(wire.team_id),
+ cohort_id: CohortId(wire.cohort_id),
scope,
- wire.run_id,
- ))
+ run_id: wire.run_id,
+ boundary: wire.boundary_ms,
+ })
}
}
@@ -306,12 +319,11 @@ fn deserialize_schema_version<'de, D: Deserializer<'de>>(deserializer: D) -> Res
Ok(value)
}
-pub(super) const RECONCILE_COMPLETE_KIND: &str = "reconcile_complete";
-
/// A completion certificate emitted after one partition's reconcile snapshot is durable. Produced by
/// the stream processor onto the dedicated reconcile-marker topic and folded by the seeder's marker
-/// watcher, so it lives here — the shared seed contract — rather than in either crate. Field order is
-/// the wire order; the golden test below pins the exact bytes both ends depend on.
+/// watcher, so it lives here — the shared seed contract — rather than in either crate. Field order
+/// is the wire order; the golden test below pins the exact bytes both ends depend on. Serialize it
+/// through [`ReconcileMarker`], which adds the `type` tag.
///
/// Deliberately carries no dispatch epoch. A marker is a run-scoped durable fact: that partition's
/// snapshot drained under this run's pinned filters. If a re-dispatch's watcher folds a late marker
@@ -321,8 +333,6 @@ pub(super) const RECONCILE_COMPLETE_KIND: &str = "reconcile_complete";
/// discard that work and buy nothing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReconcileCompleteMarker {
- #[serde(rename = "type")]
- kind: ReconcileCompleteKind,
team_id: i32,
cohort_id: i32,
partition: u16,
@@ -340,7 +350,6 @@ impl ReconcileCompleteMarker {
last_updated: String,
) -> Self {
Self {
- kind: ReconcileCompleteKind,
team_id: team_id.0,
cohort_id: cohort_id.0,
partition,
@@ -370,26 +379,227 @@ impl ReconcileCompleteMarker {
}
}
-/// A zero-sized discriminant proven to be [`RECONCILE_COMPLETE_KIND`] during deserialization.
+/// Why the catalog rules out a reconcile.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CatalogMiss {
+ TeamAbsent,
+ CohortAbsent,
+ NotEmitting,
+ HashUnknown,
+ HashMismatch,
+}
+
+impl CatalogMiss {
+ const ALL: [Self; 5] = [
+ Self::TeamAbsent,
+ Self::CohortAbsent,
+ Self::NotEmitting,
+ Self::HashUnknown,
+ Self::HashMismatch,
+ ];
+
+ /// The wire `reason` and a metric label.
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::TeamAbsent => "team_absent",
+ Self::CohortAbsent => "cohort_absent",
+ Self::NotEmitting => "not_emitting",
+ Self::HashUnknown => "hash_unknown",
+ Self::HashMismatch => "hash_mismatch",
+ }
+ }
+
+ fn parse(value: &str) -> Option<Self> {
+ Self::ALL.into_iter().find(|miss| miss.as_str() == value)
+ }
+}
+
+const PARTIAL_COVERAGE: &str = "partial_coverage";
+
+/// Why a partition withheld its reconcile certificate. Every reason is final for the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-struct ReconcileCompleteKind;
+pub enum WithheldReason {
+ /// The slice's history starts after the run's boundary. A recovery run needs a boundary at or
+ /// after `covered_since`.
+ PartialCoverage {
+ covered_since: CoverageStartMs,
+ },
+ Catalog(CatalogMiss),
+}
+
+impl WithheldReason {
+ /// The wire `reason` and a metric label.
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::PartialCoverage { .. } => PARTIAL_COVERAGE,
+ Self::Catalog(miss) => miss.as_str(),
+ }
+ }
+
+ /// When the slice's history begins, for `partial_coverage` only.
+ pub const fn covered_since(self) -> Option<CoverageStartMs> {
+ match self {
+ Self::PartialCoverage { covered_since } => Some(covered_since),
+ Self::Catalog(_) => None,
+ }
+ }
+}
+
+/// A partition's refusal to certify a run. It shares the complete marker's key.
+#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
+#[serde(try_from = "ReconcileWithheldWire")]
+pub struct ReconcileWithheldMarker {
+ team_id: TeamId,
+ cohort_id: CohortId,
+ partition: u16,
+ run_id: RunId,
+ reason: WithheldReason,
+}
+
+impl ReconcileWithheldMarker {
+ pub const fn new(
+ team_id: TeamId,
+ cohort_id: CohortId,
+ partition: u16,
+ run_id: RunId,
+ reason: WithheldReason,
+ ) -> Self {
+ Self {
+ team_id,
+ cohort_id,
+ partition,
+ run_id,
+ reason,
+ }
+ }
+
+ pub const fn team_id(&self) -> TeamId {
+ self.team_id
+ }
+
+ pub const fn cohort_id(&self) -> CohortId {
+ self.cohort_id
+ }
+
+ pub const fn partition(&self) -> u16 {
+ self.partition
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ self.run_id
+ }
+
+ pub const fn reason(&self) -> WithheldReason {
+ self.reason
+ }
+}
+
+/// The wire projection. Field order is the wire order.
+#[derive(Serialize)]
+struct ReconcileWithheldOut {
+ team_id: i32,
+ cohort_id: i32,
+ partition: u16,
+ run_id: RunId,
+ reason: &'static str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ covered_since_ms: Option<CoverageStartMs>,
+}
-impl Serialize for ReconcileCompleteKind {
+impl Serialize for ReconcileWithheldMarker {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
- serializer.serialize_str(RECONCILE_COMPLETE_KIND)
+ ReconcileWithheldOut {
+ team_id: self.team_id.0,
+ cohort_id: self.cohort_id.0,
+ partition: self.partition,
+ run_id: self.run_id,
+ reason: self.reason.as_str(),
+ covered_since_ms: self.reason.covered_since(),
+ }
+ .serialize(serializer)
}
}
-impl<'de> Deserialize<'de> for ReconcileCompleteKind {
- fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
- let value = String::deserialize(deserializer)?;
- if value != RECONCILE_COMPLETE_KIND {
- return Err(DeError::invalid_value(
- Unexpected::Str(&value),
- &"marker type \"reconcile_complete\"",
- ));
+/// Decoded through [`TryFrom`], so a malformed reason fails the decode.
+#[derive(Deserialize)]
+struct ReconcileWithheldWire {
+ team_id: i32,
+ cohort_id: i32,
+ partition: u16,
+ run_id: RunId,
+ reason: String,
+ covered_since_ms: Option<CoverageStartMs>,
+}
+
+impl TryFrom<ReconcileWithheldWire> for ReconcileWithheldMarker {
+ type Error = WithheldReasonError;
+
+ fn try_from(wire: ReconcileWithheldWire) -> Result<Self, Self::Error> {
+ let reason = match (wire.reason.as_str(), wire.covered_since_ms) {
+ (PARTIAL_COVERAGE, Some(covered_since)) => {
+ WithheldReason::PartialCoverage { covered_since }
+ }
+ (PARTIAL_COVERAGE, None) => return Err(WithheldReasonError::MissingCoveredSince),
+ (other, _) => WithheldReason::Catalog(
+ CatalogMiss::parse(other)
+ .ok_or_else(|| WithheldReasonError::Unknown(wire.reason.clone()))?,
+ ),
+ };
+ Ok(Self::new(
+ TeamId(wire.team_id),
+ CohortId(wire.cohort_id),
+ wire.partition,
+ wire.run_id,
+ reason,
+ ))
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+enum WithheldReasonError {
+ #[error("unknown withheld reason {0:?}")]
+ Unknown(String),
+ #[error("a partial_coverage reason must carry covered_since_ms")]
+ MissingCoveredSince,
+}
+
+/// A reconcile outcome on `cohort_reconcile_markers`, tagged by `type`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "type")]
+pub enum ReconcileMarker {
+ #[serde(rename = "reconcile_complete")]
+ Complete(ReconcileCompleteMarker),
+ #[serde(rename = "reconcile_withheld")]
+ Withheld(ReconcileWithheldMarker),
+}
+
+impl ReconcileMarker {
+ pub const fn team_id(&self) -> TeamId {
+ match self {
+ Self::Complete(marker) => marker.team_id(),
+ Self::Withheld(marker) => marker.team_id(),
+ }
+ }
+
+ pub const fn cohort_id(&self) -> CohortId {
+ match self {
+ Self::Complete(marker) => marker.cohort_id(),
+ Self::Withheld(marker) => marker.cohort_id(),
+ }
+ }
+
+ pub const fn partition(&self) -> u16 {
+ match self {
+ Self::Complete(marker) => marker.partition(),
+ Self::Withheld(marker) => marker.partition(),
+ }
+ }
+
+ pub const fn run_id(&self) -> RunId {
+ match self {
+ Self::Complete(marker) => marker.run_id(),
+ Self::Withheld(marker) => marker.run_id(),
}
- Ok(Self)
}
}
@@ -412,6 +622,7 @@ mod tests {
CohortId(42),
ReconcileScope::parse(kind, SHA256).unwrap(),
RunId(Uuid::nil()),
+ RunBoundaryMs(1_791_547_200_000),
)
}
@@ -427,14 +638,24 @@ mod tests {
"cohort_id": 42,
"filters_hash": SHA256,
"run_id": "00000000-0000-0000-0000-000000000000",
+ "boundary_ms": 1_791_547_200_000_i64,
})
);
assert_eq!(
serde_json::to_string(&tile).unwrap(),
- r#"{"schema_version":1,"kind":"reconcile","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000"}"#
+ r#"{"schema_version":1,"kind":"reconcile","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000","boundary_ms":1791547200000}"#
);
}
+ #[test]
+ fn a_tile_from_a_seeder_without_boundaries_decodes_with_none_and_keeps_its_bytes() {
+ let legacy = r#"{"schema_version":1,"kind":"reconcile","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000"}"#;
+ let decoded = serde_json::from_str::<ReconcileTile>(legacy).unwrap();
+ assert_eq!(decoded.boundary(), None);
+ assert_eq!(decoded.scope(), tile().scope());
+ assert_eq!(serde_json::to_string(&decoded).unwrap(), legacy);
+ }
+
#[test]
fn reconcile_roundtrips_and_rejects_foreign_kind_schema_and_hash() {
let tile = tile();
@@ -475,7 +696,7 @@ mod tests {
let person = scoped_tile(ScopeKind::PersonProperty);
assert_eq!(
serde_json::to_string(&person).unwrap(),
- r#"{"schema_version":1,"kind":"reconcile_person","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000"}"#
+ r#"{"schema_version":1,"kind":"reconcile_person","team_id":2,"cohort_id":42,"filters_hash":"9efcd8a99c5334a19b52f6a7b990e3b862ad116031a0b47481f8bbb09e54a7de","run_id":"00000000-0000-0000-0000-000000000000","boundary_ms":1791547200000}"#
);
assert_eq!(
serde_json::from_str::<ReconcileTile>(&serde_json::to_string(&person).unwrap())
@@ -512,43 +733,134 @@ mod tests {
assert!("person".parse::<ScopeKind>().is_err());
}
- #[test]
- fn reconcile_complete_marker_has_the_exact_wire_contract() {
- let marker = ReconcileCompleteMarker::new(
+ fn withheld(reason: WithheldReason) -> ReconcileMarker {
+ ReconcileMarker::Withheld(ReconcileWithheldMarker::new(
TeamId(42),
CohortId(91204),
7,
RunId(Uuid::nil()),
- "2026-05-26 12:34:56.789123".to_string(),
- );
-
- assert_eq!(
- serde_json::to_string(&marker).unwrap(),
- r#"{"type":"reconcile_complete","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","last_updated":"2026-05-26 12:34:56.789123"}"#,
- );
- assert_eq!(
- serde_json::from_str::<ReconcileCompleteMarker>(
- &serde_json::to_string(&marker).unwrap()
- )
- .unwrap(),
- marker
- );
+ reason,
+ ))
}
#[test]
- fn reconcile_complete_marker_rejects_another_message_type() {
- let marker = ReconcileCompleteMarker::new(
+ fn both_reconcile_markers_have_the_exact_wire_contract() {
+ let complete = ReconcileMarker::Complete(ReconcileCompleteMarker::new(
TeamId(42),
CohortId(91204),
7,
RunId(Uuid::nil()),
"2026-05-26 12:34:56.789123".to_string(),
+ ));
+ let cases = [
+ (
+ complete,
+ r#"{"type":"reconcile_complete","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","last_updated":"2026-05-26 12:34:56.789123"}"#,
+ ),
+ (
+ withheld(WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(1_791_547_200_000),
+ }),
+ r#"{"type":"reconcile_withheld","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","reason":"partial_coverage","covered_since_ms":1791547200000}"#,
+ ),
+ (
+ withheld(WithheldReason::Catalog(CatalogMiss::HashMismatch)),
+ r#"{"type":"reconcile_withheld","team_id":42,"cohort_id":91204,"partition":7,"run_id":"00000000-0000-0000-0000-000000000000","reason":"hash_mismatch"}"#,
+ ),
+ ];
+
+ for (marker, golden) in cases {
+ assert_eq!(serde_json::to_string(&marker).unwrap(), golden);
+ assert_eq!(
+ serde_json::from_str::<ReconcileMarker>(golden).unwrap(),
+ marker
+ );
+ }
+ }
+
+ #[test]
+ fn every_withheld_reason_rides_its_pinned_string() {
+ // Also the `reason` metric label that alerts select on.
+ let cases = [
+ (
+ WithheldReason::Catalog(CatalogMiss::TeamAbsent),
+ "team_absent",
+ ),
+ (
+ WithheldReason::Catalog(CatalogMiss::CohortAbsent),
+ "cohort_absent",
+ ),
+ (
+ WithheldReason::Catalog(CatalogMiss::NotEmitting),
+ "not_emitting",
+ ),
+ (
+ WithheldReason::Catalog(CatalogMiss::HashUnknown),
+ "hash_unknown",
+ ),
+ (
+ WithheldReason::Catalog(CatalogMiss::HashMismatch),
+ "hash_mismatch",
+ ),
+ (
+ WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(1),
+ },
+ "partial_coverage",
+ ),
+ ];
+ // A new variant fails to compile here; add it to `cases` and to `CatalogMiss::ALL`.
+ let _exhaustive = |miss: CatalogMiss| match miss {
+ CatalogMiss::TeamAbsent
+ | CatalogMiss::CohortAbsent
+ | CatalogMiss::NotEmitting
+ | CatalogMiss::HashUnknown
+ | CatalogMiss::HashMismatch => (),
+ };
+ assert_eq!(
+ cases.len(),
+ CatalogMiss::ALL.len() + 1,
+ "every reason is pinned"
);
- let payload = serde_json::to_string(&marker)
+
+ for (reason, pinned) in cases {
+ let marker = withheld(reason);
+ let wire = serde_json::to_value(&marker).unwrap();
+ assert_eq!(wire["reason"], pinned);
+ assert_eq!(
+ serde_json::from_value::<ReconcileMarker>(wire).unwrap(),
+ marker
+ );
+ }
+ }
+
+ #[test]
+ fn a_marker_decode_rejects_a_foreign_type_and_a_half_built_reason() {
+ let partial = serde_json::to_value(withheld(WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(1),
+ }))
+ .unwrap();
+
+ let mut extended = partial.clone();
+ extended["future_metadata"] = serde_json::json!(1);
+ assert!(serde_json::from_value::<ReconcileMarker>(extended).is_ok());
+
+ let mut missing_instant = partial.clone();
+ missing_instant
+ .as_object_mut()
.unwrap()
- .replace("reconcile_complete", "seed");
+ .remove("covered_since_ms");
+ let mut unknown_reason = partial.clone();
+ unknown_reason["reason"] = serde_json::json!("store_on_fire");
+ let mut foreign_type = partial;
+ foreign_type["type"] = serde_json::json!("seed");
- assert!(serde_json::from_str::<ReconcileCompleteMarker>(&payload).is_err());
+ for broken in [missing_instant, unknown_reason, foreign_type] {
+ assert!(
+ serde_json::from_value::<ReconcileMarker>(broken.clone()).is_err(),
+ "accepted {broken}",
+ );
+ }
}
#[test]
diff --git a/rust/cohort-seeder/src/app/completion.rs b/rust/cohort-seeder/src/app/completion.rs
index de45b16f7c53..70cf2795dbbf 100644
--- a/rust/cohort-seeder/src/app/completion.rs
+++ b/rust/cohort-seeder/src/app/completion.rs
@@ -682,6 +682,7 @@ fn build_directive(
WatchDirective {
run_id: completion.run_id,
team_id: completion.team_id,
+ kind: completion.kind,
epoch: dispatched.epoch,
start: dispatched.watch.positions.clone(),
seeded,
diff --git a/rust/cohort-seeder/src/app/reconcile_dispatch.rs b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
index 64318efb361e..f64d09e66de7 100644
--- a/rust/cohort-seeder/src/app/reconcile_dispatch.rs
+++ b/rust/cohort-seeder/src/app/reconcile_dispatch.rs
@@ -582,6 +582,7 @@ mod tests {
crate::domain::BehavioralShapeHash::parse("behavioral-shape").unwrap(),
),
RunId(Uuid::nil()),
+ crate::domain::RunBoundaryMs(0),
)
}
diff --git a/rust/cohort-seeder/src/app/watch.rs b/rust/cohort-seeder/src/app/watch.rs
index f3d1ecb9e01c..35c28793bbed 100644
--- a/rust/cohort-seeder/src/app/watch.rs
+++ b/rust/cohort-seeder/src/app/watch.rs
@@ -1,7 +1,7 @@
//! The single global marker-watch task — the seeder's second lifecycle component.
//!
//! One dedicated consumer tails the whole marker topic, folding every observed
-//! `reconcile_complete` marker into the per-run [`MarkerLedger`] it names. Bits and the watcher's
+//! reconcile marker into the per-run [`MarkerLedger`] it names. Bits and the watcher's
//! resume positions are flushed through the fenced [`persist_marker_observations`] on a cadence
//! (every persist interval), a batch cap (every N consumed messages), or immediately when a cohort's
//! bitmap completes — whichever comes first. The driver publishes the set of runs to watch via a
@@ -27,11 +27,14 @@ use tracing::{info, warn};
use crate::domain::{
DispatchEpoch, MarkerFold, MarkerLedger, NextOffset, PartitionBitmap, RunId, WatchPartition,
- WatchPositions,
+ WatchPositions, WithheldCohort,
};
use crate::kafka::markers::{MarkerWatcher, WatchError, WatchItem};
-use crate::observability::metrics::{RECONCILE_MARKERS_OBSERVED, RECONCILE_WATCH_TRUNCATED};
+use crate::observability::metrics::{
+ RECONCILE_COHORTS_WITHHELD, RECONCILE_MARKERS_OBSERVED, RECONCILE_WATCH_TRUNCATED,
+};
use crate::store::completion::{persist_marker_observations, CompletionStoreError};
+use crate::store::runs::RunKind;
/// One run the driver wants watched: its identity, dispatch fence, watcher start offsets, and the bits
/// already persisted (so a resumed ledger continues rather than restarts).
@@ -39,6 +42,7 @@ use crate::store::completion::{persist_marker_observations, CompletionStoreError
pub struct WatchDirective {
pub run_id: RunId,
pub team_id: TeamId,
+ pub kind: RunKind,
pub epoch: DispatchEpoch,
pub start: WatchPositions,
pub seeded: Vec<(CohortId, PartitionBitmap)>,
@@ -86,11 +90,12 @@ pub trait MarkerFlush: Send {
run_id: RunId,
epoch: DispatchEpoch,
bits: &[(CohortId, PartitionBitmap)],
+ withheld: &[WithheldCohort],
positions: &WatchPositions,
) -> Result<(), CompletionStoreError>;
}
-/// The real flush: the epoch-fenced OR-merge of bits plus the watcher positions.
+/// The real flush: the epoch-fenced OR-merge of bits, withheld supersedes and watcher positions.
pub struct PgMarkerFlush {
pool: PgPool,
marker_topic: String,
@@ -109,6 +114,7 @@ impl MarkerFlush for PgMarkerFlush {
run_id: RunId,
epoch: DispatchEpoch,
bits: &[(CohortId, PartitionBitmap)],
+ withheld: &[WithheldCohort],
positions: &WatchPositions,
) -> Result<(), CompletionStoreError> {
persist_marker_observations(
@@ -116,6 +122,7 @@ impl MarkerFlush for PgMarkerFlush {
run_id,
epoch,
bits,
+ withheld,
positions,
&self.marker_topic,
)
@@ -129,6 +136,7 @@ impl MarkerFlush for PgMarkerFlush {
/// freshly added run cannot claim offsets the stream read before that run's ledger existed — its
/// settlement proof rests on this.
struct RunWatch {
+ kind: RunKind,
epoch: DispatchEpoch,
positions: WatchPositions,
ledger: MarkerLedger,
@@ -137,6 +145,7 @@ struct RunWatch {
impl RunWatch {
fn from_directive(directive: &WatchDirective) -> Self {
Self {
+ kind: directive.kind,
epoch: directive.epoch,
positions: directive.start.clone(),
ledger: MarkerLedger::new(
@@ -427,8 +436,9 @@ impl<S: MarkerStream, F: MarkerFlush> WatchState<S, F> {
.any(|run| run.ledger.completed_since_flush());
}
- /// Persist one run's dirty bits and the watcher positions under its dispatch fence. A lost fence
- /// drops the run (a re-dispatch superseded it); a transient error keeps the bits dirty for retry.
+ /// Persist one run's dirty bits, withheld supersedes and the watcher positions under its dispatch
+ /// fence. A lost fence drops the run (a re-dispatch superseded it); a transient error keeps the
+ /// bits dirty and the withheld cohorts pending for retry.
/// Returns whether the run has nothing left owed — `false` only on a transient error, so the
/// caller knows to keep the retry flag set.
async fn flush_run(&mut self, run_id: RunId) -> bool {
@@ -439,13 +449,34 @@ impl<S: MarkerStream, F: MarkerFlush> WatchState<S, F> {
if !run.ledger.has_dirty() && !self.positions_advanced {
return true;
}
- let epoch = run.epoch;
+ let (kind, epoch) = (run.kind, run.epoch);
let dirty = run.ledger.dirty_bitmaps();
+ let withheld = run.ledger.dirty_withheld();
let positions = run.positions.clone();
- match self.flush.persist(run_id, epoch, &dirty, &positions).await {
+ match self
+ .flush
+ .persist(run_id, epoch, &dirty, &withheld, &positions)
+ .await
+ {
Ok(()) => {
if let Some(run) = self.runs.get_mut(&run_id) {
- run.ledger.clear_dirty();
+ run.ledger.mark_persisted();
+ }
+ for cohort in &withheld {
+ counter!(
+ RECONCILE_COHORTS_WITHHELD,
+ "kind" => kind.as_str(),
+ "reason" => cohort.reason.as_str(),
+ )
+ .increment(1);
+ warn!(
+ run_id = ?run_id,
+ cohort_id = cohort.cohort_id.0,
+ partition = cohort.partition.get(),
+ reason = cohort.reason.as_str(),
+ covered_since_ms = cohort.reason.covered_since().map(|since| since.0),
+ "a partition withheld its reconcile certificate for this cohort",
+ );
}
true
}
@@ -577,7 +608,9 @@ mod tests {
use cohort_core::partitioner::COHORT_PARTITION_COUNT;
use uuid::Uuid;
- use crate::domain::{MarkerPartition, ObservedMarker};
+ use crate::domain::{
+ CatalogMiss, MarkerPartition, MarkerVerdict, ObservedMarker, WithheldReason,
+ };
use crate::store::completion::CompletionOperation;
fn run(seed: u128) -> RunId {
@@ -602,6 +635,7 @@ mod tests {
WatchDirective {
run_id,
team_id: TeamId(2),
+ kind: RunKind::Behavioral,
epoch: epoch(epoch_secs),
start,
seeded: cohorts
@@ -625,6 +659,7 @@ mod tests {
cohort_id: CohortId(cohort),
partition: MarkerPartition::new(bit).unwrap(),
run_id,
+ verdict: MarkerVerdict::Complete,
}),
}
}
@@ -666,6 +701,7 @@ mod tests {
struct FlushCall {
run_id: RunId,
bits: Vec<(CohortId, PartitionBitmap)>,
+ withheld: Vec<WithheldCohort>,
positions: WatchPositions,
}
@@ -697,6 +733,7 @@ mod tests {
run_id: RunId,
_epoch: DispatchEpoch,
bits: &[(CohortId, PartitionBitmap)],
+ withheld: &[WithheldCohort],
positions: &WatchPositions,
) -> Result<(), CompletionStoreError> {
if self
@@ -725,6 +762,7 @@ mod tests {
self.calls.lock().unwrap().push(FlushCall {
run_id,
bits: bits.to_vec(),
+ withheld: withheld.to_vec(),
positions: positions.clone(),
});
Ok(())
@@ -785,16 +823,32 @@ mod tests {
let mut state = make_state(flush, 10_000);
state
.apply_directives(&WatchDirectives {
- runs: vec![directive(run_id, 100, start_at(0, 0), &[10])],
+ runs: vec![directive(run_id, 100, start_at(0, 0), &[10, 11])],
})
.await;
state.ingest(marker_item(0, 1, run_id, 10, 5));
+ let mut withheld = marker_item(0, 2, run_id, 11, 6);
+ let reason = WithheldReason::Catalog(CatalogMiss::HashUnknown);
+ withheld.marker.as_mut().unwrap().verdict = MarkerVerdict::Withheld(reason);
+ state.ingest(withheld);
+ state.flush.fail_once(run_id);
+ state.flush().await;
+ assert!(state.flush.calls().is_empty(), "the persist failed");
state.flush().await;
let first = state.flush.calls();
assert_eq!(first.len(), 1);
assert_eq!(first[0].run_id, run_id);
assert_eq!(first[0].bits.len(), 1, "the dirty cohort is persisted");
+ assert_eq!(
+ first[0].withheld,
+ vec![WithheldCohort {
+ cohort_id: CohortId(11),
+ partition: MarkerPartition::new(6).unwrap(),
+ reason,
+ }],
+ "the withheld cohort's supersede rides the same persist",
+ );
// A second flush with no new bits and no advanced positions is a no-op.
state.flush().await;
diff --git a/rust/cohort-seeder/src/domain/completion.rs b/rust/cohort-seeder/src/domain/completion.rs
index e07a312b723f..00d718cdeed1 100644
--- a/rust/cohort-seeder/src/domain/completion.rs
+++ b/rust/cohort-seeder/src/domain/completion.rs
@@ -9,6 +9,7 @@ use std::collections::BTreeMap;
use chrono::{DateTime, Utc};
use cohort_core::filters::{CohortId, TeamId};
use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+use cohort_core::seed::WithheldReason;
use serde::de::Error as _;
use serde::ser::SerializeMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
@@ -94,6 +95,10 @@ impl PartitionBitmap {
MarkerNovelty::Novel
}
+ pub const fn contains(self, partition: MarkerPartition) -> bool {
+ self.0 & partition.mask() != 0
+ }
+
pub const fn is_complete(self) -> bool {
self.0 == COMPLETE_MASK
}
@@ -504,13 +509,20 @@ impl DispatchEpoch {
}
}
-/// One observed `reconcile_complete` marker, fed to the ledger fold.
+/// One observed reconcile marker, fed to the ledger fold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ObservedMarker {
pub team_id: TeamId,
pub cohort_id: CohortId,
pub partition: MarkerPartition,
pub run_id: RunId,
+ pub verdict: MarkerVerdict,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MarkerVerdict {
+ Complete,
+ Withheld(WithheldReason),
}
/// Which of the two discoverable run statuses a completion row carries.
@@ -1032,6 +1044,7 @@ mod tests {
cohort_id: CohortId(42),
partition: marker(7),
run_id: RunId(Uuid::nil()),
+ verdict: MarkerVerdict::Complete,
};
assert_eq!(observed.partition.get(), 7);
}
diff --git a/rust/cohort-seeder/src/domain/ledger.rs b/rust/cohort-seeder/src/domain/ledger.rs
index fd444274c544..5f1af6371c6d 100644
--- a/rust/cohort-seeder/src/domain/ledger.rs
+++ b/rust/cohort-seeder/src/domain/ledger.rs
@@ -1,4 +1,4 @@
-//! Pure per-run fold of observed `reconcile_complete` markers into per-cohort partition bitmaps.
+//! Pure per-run fold of observed reconcile markers into per-cohort partition bitmaps.
//!
//! The marker watcher's dedicated task reads *all* marker partitions and hands each marker
//! to the ledger of the run it names. Folding is a monotone set-union: a partition's bit, once set,
@@ -7,12 +7,17 @@
//! consumes a [`SettleProof`] — the capability minted in [`super::completion`] once the watcher has
//! read past the marker-topic end-watermarks captured at the liveness pass. No proof, no negative
//! verdict.
+//!
+//! A withheld marker needs no proof: the next flush supersedes the cohort, which then leaves.
use std::collections::BTreeMap;
use cohort_core::filters::{CohortId, TeamId};
+use cohort_core::seed::WithheldReason;
-use super::completion::{MarkerNovelty, ObservedMarker, PartitionBitmap, SettleProof};
+use super::completion::{
+ MarkerNovelty, MarkerPartition, MarkerVerdict, ObservedMarker, PartitionBitmap, SettleProof,
+};
use super::ids::RunId;
/// How one observed marker was routed. Only [`Novel`](MarkerFold::Novel) mutates a bitmap; the rest
@@ -30,6 +35,8 @@ pub enum MarkerFold {
ForeignTeam,
/// This run, but a cohort it does not track (superseded and excluded by the caller, or garbage).
UnknownCohort,
+ /// A withheld marker for one of this run's cohorts.
+ Withheld,
/// No ledger names this run. Decided by the watcher before any ledger sees the marker, and the
/// dominant outcome since the watcher tails a topic carrying every run's markers.
Unwatched,
@@ -44,6 +51,7 @@ impl MarkerFold {
Self::ForeignRun => "foreign_run",
Self::ForeignTeam => "foreign_team",
Self::UnknownCohort => "unknown_cohort",
+ Self::Withheld => "withheld",
Self::Unwatched => "unwatched",
}
}
@@ -65,15 +73,26 @@ pub enum SettledVerdict {
NoMarkers,
}
+/// A cohort withheld from the run, as its first withheld marker reported it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WithheldCohort {
+ pub cohort_id: CohortId,
+ pub partition: MarkerPartition,
+ pub reason: WithheldReason,
+}
+
/// One tracked cohort's fold state.
#[derive(Debug, Clone, Copy)]
struct CohortFold {
bitmap: PartitionBitmap,
- /// A bit was set since the last [`MarkerLedger::clear_dirty`]. Drives incremental flushes.
+ /// A bit was set since the last [`MarkerLedger::mark_persisted`]. Drives incremental flushes.
dirty: bool,
- /// The bitmap reached its full set since the last [`MarkerLedger::clear_dirty`]. Drives the
+ /// The bitmap reached its full set since the last [`MarkerLedger::mark_persisted`]. Drives the
/// flush-on-completion trigger.
newly_complete: bool,
+ /// The first withheld marker's partition and reason. A set value marks the cohort for
+ /// supersede, and [`MarkerLedger::mark_persisted`] drops the cohort once that persists.
+ withheld: Option<(MarkerPartition, WithheldReason)>,
}
/// A run's marker fold: its identity plus the per-cohort bitmaps it accumulates. Seeded from the bits
@@ -102,6 +121,7 @@ impl MarkerLedger {
bitmap,
dirty: false,
newly_complete: false,
+ withheld: None,
},
)
})
@@ -118,7 +138,7 @@ impl MarkerLedger {
}
/// Fold one observed marker. Routing is pure: team, then run, then cohort membership. Only a
- /// marker naming this run and a tracked cohort touches a bitmap.
+ /// marker naming this run and a tracked cohort touches the cohort's state.
pub fn observe(&mut self, marker: &ObservedMarker) -> MarkerFold {
if marker.team_id != self.team_id {
return MarkerFold::ForeignTeam;
@@ -129,15 +149,26 @@ impl MarkerLedger {
let Some(fold) = self.cohorts.get_mut(&marker.cohort_id) else {
return MarkerFold::UnknownCohort;
};
- match fold.bitmap.set(marker.partition) {
- MarkerNovelty::Duplicate => MarkerFold::Duplicate,
- MarkerNovelty::Novel => {
- fold.dirty = true;
- if fold.bitmap.is_complete() {
- fold.newly_complete = true;
- }
- MarkerFold::Novel
+ match marker.verdict {
+ // A later refusal cannot revoke a certificate this partition already gave, for example
+ // after the slice lost its history and the tile was delivered again.
+ MarkerVerdict::Withheld(_) if fold.bitmap.contains(marker.partition) => {
+ MarkerFold::Duplicate
}
+ MarkerVerdict::Withheld(reason) => {
+ fold.withheld.get_or_insert((marker.partition, reason));
+ MarkerFold::Withheld
+ }
+ MarkerVerdict::Complete => match fold.bitmap.set(marker.partition) {
+ MarkerNovelty::Duplicate => MarkerFold::Duplicate,
+ MarkerNovelty::Novel => {
+ fold.dirty = true;
+ if fold.bitmap.is_complete() {
+ fold.newly_complete = true;
+ }
+ MarkerFold::Novel
+ }
+ },
}
}
@@ -148,8 +179,9 @@ impl MarkerLedger {
self.cohorts.values().all(|fold| fold.bitmap.is_complete())
}
- /// The cohorts whose bitmap changed since the last [`Self::clear_dirty`], with their current bits.
- /// Flushed through the idempotent OR-merge persist, so re-flushing the same bits is a no-op.
+ /// The cohorts whose bitmap changed since the last [`Self::mark_persisted`], with their current
+ /// bits. Flushed through the idempotent OR-merge persist, so re-flushing the same bits is a
+ /// no-op.
pub fn dirty_bitmaps(&self) -> Vec<(CohortId, PartitionBitmap)> {
self.cohorts
.iter()
@@ -158,18 +190,35 @@ impl MarkerLedger {
.collect()
}
+ /// The withheld cohorts the next flush supersedes.
+ pub fn dirty_withheld(&self) -> Vec<WithheldCohort> {
+ self.cohorts
+ .iter()
+ .filter_map(|(cohort_id, fold)| {
+ fold.withheld.map(|(partition, reason)| WithheldCohort {
+ cohort_id: *cohort_id,
+ partition,
+ reason,
+ })
+ })
+ .collect()
+ }
+
pub fn has_dirty(&self) -> bool {
- self.cohorts.values().any(|fold| fold.dirty)
+ self.cohorts
+ .values()
+ .any(|fold| fold.dirty || fold.withheld.is_some())
}
- /// A cohort reached its full partition set since the last [`Self::clear_dirty`]. The watcher
+ /// A cohort reached its full partition set since the last [`Self::mark_persisted`]. The watcher
/// flushes immediately on this so a completed cohort's outcome is durable without waiting a tick.
pub fn completed_since_flush(&self) -> bool {
self.cohorts.values().any(|fold| fold.newly_complete)
}
- /// Clear the incremental-flush flags after a successful persist. Bitmaps are untouched.
- pub fn clear_dirty(&mut self) {
+ /// After a successful persist, clear the flush flags and drop the superseded cohorts.
+ pub fn mark_persisted(&mut self) {
+ self.cohorts.retain(|_, fold| fold.withheld.is_none());
for fold in self.cohorts.values_mut() {
fold.dirty = false;
fold.newly_complete = false;
@@ -210,16 +259,23 @@ impl MarkerLedger {
mod tests {
use super::*;
use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+ use cohort_core::seed::{CatalogMiss, CoverageStartMs};
use uuid::Uuid;
- use crate::domain::MarkerPartition;
-
fn marker(team: i32, cohort: i32, run: RunId, partition: u32) -> ObservedMarker {
ObservedMarker {
team_id: TeamId(team),
cohort_id: CohortId(cohort),
partition: MarkerPartition::new(partition).unwrap(),
run_id: run,
+ verdict: MarkerVerdict::Complete,
+ }
+ }
+
+ fn withheld(cohort: i32, partition: u32, reason: WithheldReason) -> ObservedMarker {
+ ObservedMarker {
+ verdict: MarkerVerdict::Withheld(reason),
+ ..marker(2, cohort, run(1), partition)
}
}
@@ -265,6 +321,55 @@ mod tests {
);
}
+ #[test]
+ fn a_withheld_cohort_is_owed_one_supersede_with_its_first_reason_then_leaves() {
+ let first = WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(1_791_547_200_000),
+ };
+ let mut ledger = ledger(&[10, 11]);
+ ledger.observe(&marker(2, 10, run(1), 0));
+ ledger.mark_persisted();
+ assert!(!ledger.has_dirty());
+ assert_eq!(
+ ledger.observe(&withheld(10, 0, first)),
+ MarkerFold::Duplicate,
+ "a partition that already certified the cohort cannot withhold it",
+ );
+ assert!(!ledger.has_dirty());
+
+ assert_eq!(
+ ledger.observe(&withheld(10, 7, first)),
+ MarkerFold::Withheld
+ );
+ assert_eq!(
+ ledger.observe(&withheld(
+ 10,
+ 9,
+ WithheldReason::Catalog(CatalogMiss::HashMismatch)
+ )),
+ MarkerFold::Withheld,
+ );
+ // A withheld cohort alone must trigger a flush.
+ assert!(ledger.has_dirty());
+ assert_eq!(
+ ledger.dirty_withheld(),
+ vec![WithheldCohort {
+ cohort_id: CohortId(10),
+ partition: MarkerPartition::new(7).unwrap(),
+ reason: first,
+ }],
+ );
+
+ ledger.mark_persisted();
+ assert!(ledger.dirty_withheld().is_empty(), "superseded once");
+ assert_eq!(
+ ledger.observe(&marker(2, 10, run(1), 1)),
+ MarkerFold::UnknownCohort,
+ "the superseded cohort is no longer tracked",
+ );
+ assert_eq!(ledger.observe(&marker(2, 11, run(1), 1)), MarkerFold::Novel);
+ }
+
#[test]
fn fold_is_order_independent() {
let markers = [
@@ -313,7 +418,7 @@ mod tests {
complete_cohort(&mut ledger, 10);
assert!(ledger.completed_since_flush());
- ledger.clear_dirty();
+ ledger.mark_persisted();
assert!(!ledger.has_dirty());
assert!(!ledger.completed_since_flush());
assert!(
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 0416aa312eeb..b9f9e2fd0be3 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -38,8 +38,10 @@ pub use chunk::{
ScanVolume, ScannedChunk, StreamedChunk, UnknownChunkStatus,
};
pub use cohort_core::seed::{
- BehavioralShapeHash, PersonSeed, PersonShapeHash, ReconcileCompleteMarker, ReconcileScope,
- ReconcileTile, ScopeKind, SeedTile, ShapeHashError, UnknownScopeKind,
+ BehavioralShapeHash, CatalogMiss, CoverageStartMs, PersonSeed, PersonShapeHash,
+ ReconcileCompleteMarker, ReconcileMarker, ReconcileScope, ReconcileTile,
+ ReconcileWithheldMarker, RunBoundaryMs, ScopeKind, SeedTile, ShapeHashError, UnknownScopeKind,
+ WithheldReason,
};
pub use columns::{ColumnName, MaterializedColumns};
pub use compare::{diff_tiles, Divergence, DivergenceClass, TileDiff, MAX_EXEMPLARS_PER_CLASS};
@@ -47,7 +49,7 @@ pub(crate) use completion::MARKER_WATCH_SCHEMA;
pub use completion::{
CommittedOffset, CompletionParts, CompletionPhase, CompletionStatus, DispatchEpoch,
DispatchedReconcile, LivenessCheck, MarkerNovelty, MarkerPartition, MarkerPartitionError,
- MarkerWatch, NextOffset, ObservationEnds, ObservedMarker, PartitionBitmap,
+ MarkerVerdict, MarkerWatch, NextOffset, ObservationEnds, ObservedMarker, PartitionBitmap,
PartitionBitmapError, ProducedOffset, ReconcileHwms, ReconcileHwmsError, SeedGroupCommits,
SettleProof, UndispatchedReason, WatchPartition, WatchPositions,
};
@@ -59,7 +61,7 @@ pub use ids::{
Band, ChunkId, ClaimEpoch, ConditionHash, ConditionHashError, DayIdx, RunId, SChunkMs,
ScannedAtMs, UtcMillis, UtcMsRange, UtcRangeError,
};
-pub use ledger::{MarkerFold, MarkerLedger, SettledVerdict};
+pub use ledger::{MarkerFold, MarkerLedger, SettledVerdict, WithheldCohort};
pub use partition::{SeedPartition, SeedPartitionCountError, SeedPartitions};
pub use person::{
person_chunk_sentinel_day, tile_ranges, EvaluatedConditions, PersonChunkSpec,
diff --git a/rust/cohort-seeder/src/kafka/markers.rs b/rust/cohort-seeder/src/kafka/markers.rs
index bb5e190d6b1b..7fa3db823112 100644
--- a/rust/cohort-seeder/src/kafka/markers.rs
+++ b/rust/cohort-seeder/src/kafka/markers.rs
@@ -1,11 +1,11 @@
-//! Tails the reconcile-marker topic for `reconcile_complete` markers — the completion *authority*.
+//! Tails the reconcile-marker topic — the completion *authority*.
//!
//! An assign-only consumer with a unique throwaway group id: it never subscribes and never commits, so
//! it participates in no rebalance and leaves no durable offset. It watches every marker partition
//! from explicit start offsets (the high watermarks captured at dispatch), with `auto.offset.reset=
//! error` so a start below the log's low watermark surfaces as [`WatchError::Truncated`] instead of
//! silently jumping. Records are classified by payload alone: a marker refuses to deserialize unless
-//! its `type` is `reconcile_complete`, so a mis-pointed topic is caught without this crate depending
+//! its `type` is a reconcile outcome, so a mis-pointed topic is caught without this crate depending
//! on the key format the processor writes. Anything the parse rejects is counted by `reason`, and
//! skipped messages still advance the partition's next-read offset. rdkafka types stay confined
//! here — the watcher yields typed [`WatchItem`]s.
@@ -23,7 +23,7 @@ use rdkafka::message::Message;
use rdkafka::{ClientConfig, Offset, TopicPartitionList};
use crate::domain::{
- MarkerPartition, NextOffset, ObservedMarker, ReconcileCompleteMarker, WatchPartition,
+ MarkerPartition, MarkerVerdict, NextOffset, ObservedMarker, ReconcileMarker, WatchPartition,
WatchPositions,
};
use crate::observability::metrics::RECONCILE_MARKER_PARSE_FAILURES;
@@ -172,7 +172,7 @@ fn build_assignment(
/// On a dedicated topic every record should be a marker, so each rejection is counted under the
/// `reason` that explains it rather than silently skipped. A record that came from a mis-pointed
-/// topic fails the payload's `reconcile_complete` discriminant and lands under `decode`.
+/// topic fails the payload's `type` discriminant and lands under `decode`.
fn classify_marker(payload: Option<&[u8]>) -> Option<ObservedMarker> {
let skip = |reason: &'static str| {
counter!(RECONCILE_MARKER_PARSE_FAILURES, "reason" => reason).increment(1);
@@ -181,15 +181,20 @@ fn classify_marker(payload: Option<&[u8]>) -> Option<ObservedMarker> {
let Some(payload) = payload else {
return skip("no_payload");
};
- let Ok(marker) = serde_json::from_slice::<ReconcileCompleteMarker>(payload) else {
+ let Ok(marker) = serde_json::from_slice::<ReconcileMarker>(payload) else {
return skip("decode");
};
+ let verdict = match &marker {
+ ReconcileMarker::Complete(_) => MarkerVerdict::Complete,
+ ReconcileMarker::Withheld(withheld) => MarkerVerdict::Withheld(withheld.reason()),
+ };
match MarkerPartition::new(u32::from(marker.partition())) {
Ok(partition) => Some(ObservedMarker {
team_id: marker.team_id(),
cohort_id: marker.cohort_id(),
partition,
run_id: marker.run_id(),
+ verdict,
}),
Err(_) => skip("partition_out_of_range"),
}
@@ -247,17 +252,19 @@ pub enum WatchError {
mod tests {
use super::*;
use cohort_core::filters::{CohortId, TeamId};
- use cohort_core::seed::RunId;
+ use cohort_core::seed::{CoverageStartMs, RunId};
use uuid::Uuid;
+ use crate::domain::{ReconcileCompleteMarker, ReconcileWithheldMarker, WithheldReason};
+
fn marker_payload(partition: u16) -> Vec<u8> {
- serde_json::to_vec(&ReconcileCompleteMarker::new(
+ serde_json::to_vec(&ReconcileMarker::Complete(ReconcileCompleteMarker::new(
TeamId(2),
CohortId(42),
partition,
RunId(Uuid::nil()),
"2026-05-26 12:34:56.789123".to_string(),
- ))
+ )))
.unwrap()
}
@@ -267,6 +274,20 @@ mod tests {
assert_eq!(observed.team_id, TeamId(2));
assert_eq!(observed.cohort_id, CohortId(42));
assert_eq!(observed.partition.get(), 7);
+ assert_eq!(observed.verdict, MarkerVerdict::Complete);
+
+ // An outcome, not a parse failure.
+ let reason = WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(1_791_547_200_000),
+ };
+ let withheld = serde_json::to_vec(&ReconcileMarker::Withheld(
+ ReconcileWithheldMarker::new(TeamId(2), CohortId(42), 7, RunId(Uuid::nil()), reason),
+ ))
+ .unwrap();
+ assert_eq!(
+ classify_marker(Some(&withheld)).unwrap().verdict,
+ MarkerVerdict::Withheld(reason),
+ );
// A membership row, i.e. what a mis-pointed topic delivers: no `reconcile_complete` type.
assert!(classify_marker(Some(b"{\"not\":\"a marker\"}")).is_none());
diff --git a/rust/cohort-seeder/src/kafka/producer.rs b/rust/cohort-seeder/src/kafka/producer.rs
index fe9de94e48d5..87b5677d12cc 100644
--- a/rust/cohort-seeder/src/kafka/producer.rs
+++ b/rust/cohort-seeder/src/kafka/producer.rs
@@ -305,6 +305,7 @@ mod tests {
crate::domain::BehavioralShapeHash::parse("shape").unwrap(),
),
crate::domain::RunId(Uuid::nil()),
+ crate::domain::RunBoundaryMs(0),
);
assert_eq!(
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index ef5ce77837a5..613d9651eb03 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -169,6 +169,8 @@ pub const RECONCILE_COHORTS_PARTIAL: &str = "seeder_reconcile_cohorts_partial_to
/// Cohort participations short of their markers with the pinned shape unchanged — the retryable
/// half of the split — labelled by the run's `kind` (counter).
pub const RECONCILE_COHORTS_SHORTFALL: &str = "seeder_reconcile_cohorts_shortfall_total";
+/// Participations superseded by a withheld marker, labelled by `kind` and `reason` (counter).
+pub const RECONCILE_COHORTS_WITHHELD: &str = "seeder_reconcile_cohorts_withheld_total";
/// Runs that settled without a single marker — the shape a processor that cannot decode the
/// tile's kind produces — labelled by the run's `kind` (counter).
pub const RECONCILE_ZERO_MARKER_RUNS: &str = "seeder_reconcile_zero_marker_runs_total";
diff --git a/rust/cohort-seeder/src/store/completion.rs b/rust/cohort-seeder/src/store/completion.rs
index a35bd26deaa4..b555f3119590 100644
--- a/rust/cohort-seeder/src/store/completion.rs
+++ b/rust/cohort-seeder/src/store/completion.rs
@@ -29,7 +29,7 @@ use std::fmt;
use crate::domain::{
CompletionParts, CompletionPhase, CompletionStatus, DispatchEpoch, MarkerWatch,
ObservationEnds, PartitionBitmap, PartitionBitmapError, ReconcileHwms, ReconcileScope, RunId,
- ScopeKind, ShapeHashError, WatchPositions, MARKER_WATCH_SCHEMA,
+ ScopeKind, ShapeHashError, WatchPositions, WithheldCohort, WithheldReason, MARKER_WATCH_SCHEMA,
};
use super::runs::RunKind;
@@ -457,11 +457,13 @@ pub async fn persist_observation_ends(
/// fenced transaction. The bit merge is idempotent (`bits | $bits`), so a replayed flush is a no-op.
/// Repeated cohort ids in `bit_updates` are folded with `bit_or` first: `UPDATE ... FROM` applies a
/// single source row per target, so unfolded duplicates would silently drop every bit but one's.
+/// The same transaction supersedes withheld cohorts, sparing completed and stamped ones.
pub async fn persist_marker_observations(
pool: &PgPool,
run_id: RunId,
epoch: DispatchEpoch,
bit_updates: &[(CohortId, PartitionBitmap)],
+ withheld: &[WithheldCohort],
positions: &WatchPositions,
marker_topic: &str,
) -> Result<(), CompletionStoreError> {
@@ -524,10 +526,49 @@ pub async fn persist_marker_observations(
.await?;
}
+ if !withheld.is_empty() {
+ let cohort_ids: Vec<i32> = withheld.iter().map(|cohort| cohort.cohort_id.0).collect();
+ let errors: Vec<String> = withheld.iter().map(withheld_error).collect();
+ sqlx::query(
+ r#"
+ UPDATE cohort_backfill_run_cohorts c
+ SET superseded_at = COALESCE(c.superseded_at, now()),
+ error = CASE WHEN c.superseded_at IS NULL THEN u.error ELSE c.error END
+ FROM unnest($2::int[], $3::text[]) AS u(cohort_id, error)
+ WHERE c.run_id = $1 AND c.cohort_id = u.cohort_id
+ AND c.stamped_at IS NULL AND c.reconcile_completed_at IS NULL
+ "#,
+ )
+ .bind(run_id)
+ .bind(cohort_ids)
+ .bind(errors)
+ .execute(&mut *tx)
+ .await?;
+ }
+
tx.commit().await?;
Ok(())
}
+fn withheld_error(cohort: &WithheldCohort) -> String {
+ let partition = cohort.partition.get();
+ let reason = cohort.reason.as_str();
+ match cohort.reason {
+ WithheldReason::PartialCoverage { covered_since } => {
+ let since = DateTime::<Utc>::from_timestamp_millis(covered_since.0)
+ .map_or_else(|| covered_since.0.to_string(), |at| at.to_rfc3339());
+ format!(
+ "reconcile withheld by partition {partition} ({reason}): its slice holds history \
+ only since {since}, after this run's boundary; a recovery run needs a boundary at \
+ or after that instant"
+ )
+ }
+ WithheldReason::Catalog(_) => {
+ format!("reconcile withheld by partition {partition} ({reason})")
+ }
+ }
+}
+
/// Mark one cohort's reconcile complete (64/64 markers). Idempotent via the `IS NULL` guard, and
/// skipped for superseded participations — supersession trumps completion.
pub async fn mark_participation_completed(
@@ -599,8 +640,7 @@ pub async fn record_participation_partial(
}
/// Record a retryable shortfall: markers short but the hash still matches (a partially-gated fleet,
-/// marker loss, allowlist shrink). Error only — `superseded_at` stays NULL so the run is
-/// re-dispatchable.
+/// marker loss). Error only — `superseded_at` stays NULL so the run is re-dispatchable.
pub async fn record_participation_shortfall(
pool: &PgPool,
run_id: RunId,
diff --git a/rust/cohort-seeder/src/store/runs.rs b/rust/cohort-seeder/src/store/runs.rs
index d57942c72ac5..0dfd071cb90d 100644
--- a/rust/cohort-seeder/src/store/runs.rs
+++ b/rust/cohort-seeder/src/store/runs.rs
@@ -13,8 +13,8 @@ use sqlx::{FromRow, PgPool};
use crate::domain::{
PersonPinnedSnapshot, PersonRunValidation, PinnedError, PinnedParticipation,
PinnedParticipationState, PinnedPersonRun, PinnedRun, PinnedRunSnapshot, ReconcileScope,
- ReconcileTile, RunId, ScopeKind, ShapeHashError, TriggerKind, UnknownScopeKind, UtcMillis,
- ValidatedPinnedRun,
+ ReconcileTile, RunBoundaryMs, RunId, ScopeKind, ShapeHashError, TriggerKind, UnknownScopeKind,
+ UtcMillis, ValidatedPinnedRun,
};
use super::{RenderedError, PERSISTED_ERROR_LIMIT};
@@ -375,13 +375,15 @@ impl SeedableRun {
}
/// A run proven safe to expand into reconcile control tiles. Construction validates the run state,
-/// tenant boundary, active participation set, and every persisted shape hash of the run's own kind.
+/// tenant boundary, run boundary, active participation set, and every persisted shape hash of the
+/// run's own kind.
#[derive(Debug, Clone)]
pub struct ReconcileRun {
run_id: RunId,
kind: RunKind,
status: RunStatus,
team_id: TeamId,
+ boundary: RunBoundaryMs,
participations: Vec<ReconcileParticipation>,
}
@@ -409,6 +411,7 @@ impl ReconcileRun {
participation.cohort_id,
participation.scope.clone(),
self.run_id,
+ self.boundary,
)
})
}
@@ -684,6 +687,10 @@ pub async fn load_reconcile_run(
status: run.status,
});
}
+ let boundary = run
+ .boundary_at
+ .map(|boundary_at| RunBoundaryMs(boundary_at.timestamp_millis()))
+ .ok_or(RunError::SeedingBoundaryMissing(run_id))?;
let rows = sqlx::query_as::<_, ReconcileParticipationRow>(READ_ACTIVE_RECONCILE_PARTICIPATIONS)
.bind(run_id)
@@ -722,6 +729,7 @@ pub async fn load_reconcile_run(
kind: run.kind,
status: run.status,
team_id: run.team_id,
+ boundary,
participations,
})
}
diff --git a/rust/cohort-seeder/tests/pg_completion.rs b/rust/cohort-seeder/tests/pg_completion.rs
index 09bc574a533e..2a9232f782cf 100644
--- a/rust/cohort-seeder/tests/pg_completion.rs
+++ b/rust/cohort-seeder/tests/pg_completion.rs
@@ -16,9 +16,10 @@ use chrono::{DateTime, Duration as ChronoDuration, Utc};
use cohort_core::filters::{CohortId, TeamId};
use cohort_core::partitioner::COHORT_PARTITION_COUNT;
use cohort_seeder::domain::{
- CompletionPhase, DispatchEpoch, MarkerPartition, MarkerWatch, NextOffset, ObservationEnds,
- PartitionBitmap, PersonShapeHash, ProducedOffset, ReconcileHwms, ReconcileScope, RunId,
- SeedPartition, UndispatchedReason, WatchPartition, WatchPositions,
+ CatalogMiss, CompletionPhase, CoverageStartMs, DispatchEpoch, MarkerPartition, MarkerWatch,
+ NextOffset, ObservationEnds, PartitionBitmap, PersonShapeHash, ProducedOffset, ReconcileHwms,
+ ReconcileScope, RunBoundaryMs, RunId, SeedPartition, UndispatchedReason, WatchPartition,
+ WatchPositions, WithheldCohort, WithheldReason,
};
use cohort_seeder::store::chunks::PgChunkStore;
use cohort_seeder::store::completion::{
@@ -199,6 +200,14 @@ async fn person_run_loads_pin_the_person_hash_and_ignore_the_empty_behavioral_co
let run = load_reconcile_run(&pool, run_id).await?;
ensure!(run.kind() == RunKind::PersonProperty);
+ let boundary_at: DateTime<Utc> =
+ sqlx::query_scalar("SELECT boundary_at FROM cohort_backfill_runs WHERE id = $1")
+ .bind(run_id)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(run
+ .tiles()
+ .all(|tile| tile.boundary() == Some(RunBoundaryMs(boundary_at.timestamp_millis()))));
let scopes: Vec<ReconcileScope> = run.tiles().map(|tile| tile.scope().clone()).collect();
ensure!(
scopes
@@ -444,6 +453,7 @@ async fn record_is_fenced_against_a_dispatch_recorded_after_the_claim() -> Resul
run_id,
epoch,
&[(CohortId(301), PartitionBitmap::from_bits(3)?)],
+ &[],
&WatchPositions::new(),
MARKER_TOPIC,
)
@@ -567,6 +577,121 @@ async fn recording_a_partial_preserves_an_existing_supersession_reason() -> Resu
.await
}
+/// A withheld supersede rides the fenced flush and spares completed, stamped and superseded rows.
+#[tokio::test]
+async fn a_withheld_supersede_rides_the_fenced_marker_flush() -> Result<()> {
+ with_db(|pool| async move {
+ let run_id = insert_reconciling_run(&pool, 2).await?;
+ for cohort_id in [401, 402, 403, 404] {
+ insert_participation(&pool, run_id, 2, cohort_id, false, empty_pinned()).await?;
+ }
+ let claim = confirm_reconciling(&pool, run_id, RunKind::Behavioral)
+ .await?
+ .context("run should be claimable")?;
+ let epoch = claim.record(&pool, &full_hwms(), &empty_watch()).await?;
+ mark_participation_completed(&pool, run_id, epoch, CohortId(402)).await?;
+ sqlx::query(
+ "UPDATE cohort_backfill_run_cohorts SET stamped_at = now() \
+ WHERE run_id = $1 AND cohort_id = 403",
+ )
+ .bind(run_id)
+ .execute(&pool)
+ .await?;
+ let edited = RenderedError::from_message("Cohort definition changed during backfill");
+ record_participation_partial(&pool, run_id, epoch, CohortId(404), &edited).await?;
+
+ let withheld = |cohort_id: i32, reason: WithheldReason| WithheldCohort {
+ cohort_id: CohortId(cohort_id),
+ partition: MarkerPartition::new(7).expect("7 is a marker partition"),
+ reason,
+ };
+ let catalog = WithheldReason::Catalog(CatalogMiss::HashUnknown);
+ let verdicts = [
+ withheld(
+ 401,
+ WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(1_791_547_200_000),
+ },
+ ),
+ withheld(402, catalog),
+ withheld(403, catalog),
+ withheld(404, catalog),
+ ];
+ let mut bits = PartitionBitmap::default();
+ bits.set(MarkerPartition::new(0)?);
+ let bit_updates = [(CohortId(401), bits)];
+ let mut advanced = WatchPositions::new();
+ advanced.insert(WatchPartition::new(0), NextOffset::from_high_watermark(42));
+
+ let stale = test_support::epoch_at(epoch.as_datetime() - ChronoDuration::hours(1));
+ ensure_fence_lost(
+ persist_marker_observations(
+ &pool,
+ run_id,
+ stale,
+ &bit_updates,
+ &verdicts,
+ &advanced,
+ MARKER_TOPIC,
+ )
+ .await,
+ )?;
+ let outcomes = || async {
+ sqlx::query_as::<_, (i32, bool, String, i64)>(
+ "SELECT cohort_id, superseded_at IS NOT NULL, error, reconcile_marker_bits \
+ FROM cohort_backfill_run_cohorts WHERE run_id = $1 ORDER BY cohort_id",
+ )
+ .bind(run_id)
+ .fetch_all(&pool)
+ .await
+ };
+ let positions = || async {
+ sqlx::query_scalar::<_, Json<MarkerWatch>>(
+ "SELECT marker_watch FROM cohort_backfill_runs WHERE id = $1",
+ )
+ .bind(run_id)
+ .fetch_one(&pool)
+ .await
+ .map(|watch| watch.0.positions)
+ };
+ let before = outcomes().await?;
+ ensure!(
+ before.iter().map(|row| row.1).collect::<Vec<_>>() == [false, false, false, true],
+ "a stale epoch superseded a participation: {before:?}"
+ );
+ ensure!(before[0].3 == 0, "a stale epoch merged bits");
+ ensure!(positions().await? == WatchPositions::new());
+
+ persist_marker_observations(
+ &pool,
+ run_id,
+ epoch,
+ &bit_updates,
+ &verdicts,
+ &advanced,
+ MARKER_TOPIC,
+ )
+ .await?;
+
+ let after = outcomes().await?;
+ ensure!(
+ after.iter().map(|row| row.1).collect::<Vec<_>>() == [true, false, false, true],
+ "only the open participation is superseded: {after:?}"
+ );
+ ensure!(
+ after[0].2.contains("partition 7 (partial_coverage)")
+ && after[0].2.contains("2026-10-09T12:00:00+00:00"),
+ "the error must name the partition and the recovery instant: {}",
+ after[0].2
+ );
+ ensure!(after[0].3 != 0, "the bits rode the same flush");
+ ensure!(after[3].2 == edited.as_str(), "an earlier reason is kept");
+ ensure!(positions().await? == advanced);
+ Ok(())
+ })
+ .await
+}
+
/// Every fenced observation write is rejected under a stale epoch and under a run whose status has
/// left `reconciling`, while a matching epoch on a reconciling run is accepted.
#[tokio::test]
@@ -602,6 +727,7 @@ async fn fenced_writes_reject_stale_epoch_and_wrong_status() -> Result<()> {
run_id,
at,
&bit_updates,
+ &[],
&WatchPositions::new(),
MARKER_TOPIC,
)
@@ -736,7 +862,8 @@ async fn capturing_ends_leaves_the_watcher_positions_alone() -> Result<()> {
let mut advanced = WatchPositions::new();
advanced.insert(WatchPartition::new(0), NextOffset::from_high_watermark(42));
- persist_marker_observations(&pool, run_id, epoch, &[], &advanced, MARKER_TOPIC).await?;
+ persist_marker_observations(&pool, run_id, epoch, &[], &[], &advanced, MARKER_TOPIC)
+ .await?;
persist_observation_ends(&pool, run_id, epoch, &captured_ends(), MARKER_TOPIC).await?;
let watch: Json<MarkerWatch> =
@@ -818,6 +945,7 @@ async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()
run_id,
epoch,
&[(CohortId(401), low)],
+ &[],
&WatchPositions::new(),
MARKER_TOPIC,
)
@@ -830,6 +958,7 @@ async fn marker_observations_or_merge_round_trip_including_bit_63() -> Result<()
run_id,
epoch,
&[(CohortId(401), high)],
+ &[],
&WatchPositions::new(),
MARKER_TOPIC,
)
diff --git a/rust/cohort-stream-processor/clippy.toml b/rust/cohort-stream-processor/clippy.toml
index 14849f84636b..f6d46abdf46d 100644
--- a/rust/cohort-stream-processor/clippy.toml
+++ b/rust/cohort-stream-processor/clippy.toml
@@ -25,6 +25,8 @@ disallowed-methods = [
{ path = "cohort_stream_processor::store::rocks::CohortStore::scan_behavioral", reason = "async code must scan through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::scan_behavioral_prefix", reason = "async code must scan through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::delete_partition", reason = "async code must use StoreHandle::delete_partition (or delete_partition_blocking under a no-await guard) — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::slice_coverage", reason = "async code must not read the store on a runtime thread; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::resume_or_begin_slice", reason = "async code must use StoreHandle::resume_or_begin_slice — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::flush", reason = "async code must go through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::flush_wal_sync", reason = "async code must use StoreHandle::flush_wal_sync; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::create_checkpoint", reason = "async code must go through the checkpoint sweeper's own offload; sync contexts need a module-level allow — see store/handle.rs" },
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index 1e81b224bb27..0c2abc9cf418 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -966,6 +966,8 @@ impl Config {
periodic_compaction_seconds: self.cohort_periodic_compaction_seconds,
max_background_jobs: self.cohort_max_background_jobs,
person_record_ttl_days: self.cohort_person_record_ttl_days,
+ // A count past `u16::MAX` fails the topic checks at startup.
+ partition_count: u16::try_from(self.cohort_partition_count).unwrap_or(u16::MAX),
..StoreConfig::default()
}
}
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index f1b805d5a85a..eb58e3c9ce75 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -13,8 +13,9 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
+use cohort_core::seed::CoverageStartMs;
use dashmap::mapref::entry::Entry;
-use dashmap::{DashMap, DashSet};
+use dashmap::DashMap;
use lifecycle::Handle;
use metrics::{counter, gauge, histogram};
use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, StreamConsumer};
@@ -45,6 +46,7 @@ use crate::observability::metrics::{
PARTITIONS_PAUSED, PARTITIONS_REVOKED_TOTAL, PARTITION_STATE_DELETED_TOTAL,
PENDING_HELD_EVENTS, REBALANCE_CLEANUP_SKIPPED_TOTAL, REVOKE_DRAIN_DURATION_SECONDS,
SEED_HELD_OFFSET_GAUGE, SEED_OLDEST_HELD_AGE_MS, SEED_PAUSE_AGE_MS,
+ SLICE_COVERED_SINCE_SECONDS,
};
use crate::partitions::backpressure::Backpressure;
use crate::partitions::offset_tracker::OffsetTracker;
@@ -114,8 +116,9 @@ pub struct EventDispatcher {
router: Arc<PartitionRouter>,
tracker: Arc<OffsetTracker>,
workers: Arc<DashMap<i32, WorkerSlot>>,
- /// Partitions currently assigned to this consumer.
- owned: Arc<DashSet<i32>>,
+ /// Partitions currently assigned to this consumer, with when each was assigned. A slice
+ /// without a coverage record begins at that instant, not at its worker's spawn.
+ owned: Arc<DashMap<i32, CoverageStartMs>>,
handle: StoreHandle,
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
@@ -151,7 +154,7 @@ impl EventDispatcher {
router: Arc::new(router),
tracker,
workers: Arc::new(DashMap::new()),
- owned: Arc::new(DashSet::new()),
+ owned: Arc::new(DashMap::new()),
handle,
readiness: BootReadiness::new(catalog.clone()),
catalog,
@@ -248,7 +251,7 @@ impl EventDispatcher {
let mut not_owned = 0u64;
for consumed in batch {
let partition = consumed.partition;
- if !self.owned.contains(&partition) {
+ if !self.owned.contains_key(&partition) {
not_owned += 1;
continue;
}
@@ -335,7 +338,7 @@ impl EventDispatcher {
/// Snapshot of the partitions currently owned, for the backpressure prune/reconcile pass.
pub fn owned_set(&self) -> HashSet<i32> {
- self.owned.iter().map(|entry| *entry).collect()
+ self.owned.iter().map(|entry| *entry.key()).collect()
}
/// Route a consumed `person_merge_events` batch to per-partition workers, ceiling on the merge
@@ -432,7 +435,7 @@ impl EventDispatcher {
let mut owned_seeds: Vec<ConsumedSeed> = Vec::with_capacity(batch.len());
let mut not_owned = 0u64;
for consumed in batch {
- if !self.owned.contains(&consumed.partition) {
+ if !self.owned.contains_key(&consumed.partition) {
not_owned += 1;
continue;
}
@@ -487,7 +490,7 @@ impl EventDispatcher {
let mut messages: Vec<(i32, ShuffleMessage)> = Vec::with_capacity(items.len());
for (partition, offset, message) in items {
- if !self.owned.contains(&partition) {
+ if !self.owned.contains_key(&partition) {
stats.not_owned_skipped += 1;
continue;
}
@@ -518,9 +521,9 @@ impl EventDispatcher {
}
Entry::Vacant(slot) => {
// No `.await` in this arm — the DashMap shard guard is held.
- if !self.owned.contains(&partition) {
+ let Some(assigned_at) = self.owned.get(&partition).map(|entry| *entry) else {
return;
- }
+ };
if self.draining.load(Ordering::SeqCst) {
return;
}
@@ -549,6 +552,7 @@ impl EventDispatcher {
self.merge.clone(),
restore,
self.event_name_gating(),
+ assigned_at,
);
slot.insert(WorkerSlot::Running(worker));
counter!(COHORT_STREAM_WORKERS_SPAWNED).increment(1);
@@ -573,7 +577,7 @@ impl EventDispatcher {
}
pub fn owns(&self, partition: i32) -> bool {
- self.owned.contains(&partition)
+ self.owned.contains_key(&partition)
}
/// End boot and open the readiness gate. Every owned partition gets its worker first, so the
@@ -590,7 +594,7 @@ impl EventDispatcher {
/// Snapshot of the partitions currently owned by this consumer.
pub fn owned_partitions(&self) -> Vec<i32> {
- self.owned.iter().map(|entry| *entry).collect()
+ self.owned.iter().map(|entry| *entry.key()).collect()
}
pub(crate) fn merge_deps(&self) -> &MergeWorkerDeps {
@@ -667,7 +671,7 @@ impl EventDispatcher {
// Forget before ownership flips: every tenure starts fail-closed for the seed fence, and
// a concurrent idle-probe advance can't slip in between.
self.merge.live_watermarks.forget_partition(partition);
- self.owned.insert(partition);
+ self.owned.insert(partition, CoverageStartMs::now());
counter!(PARTITIONS_ASSIGNED_TOTAL).increment(1);
}
@@ -681,7 +685,7 @@ impl EventDispatcher {
/// Asynchronous half of a revoke: reclaim the partition unless a reassign re-acquired it.
/// Re-checks ownership at entry and after the worker join to handle rapid revoke-then-assign.
pub async fn revoke_partition_drain(&self, partition: i32) {
- if self.owned.contains(&partition) {
+ if self.owned.contains_key(&partition) {
counter!(REBALANCE_CLEANUP_SKIPPED_TOTAL, "phase" => "entry").increment(1);
debug!(
partition,
@@ -715,7 +719,7 @@ impl EventDispatcher {
histogram!(REVOKE_DRAIN_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
}
- if self.owned.contains(&partition) {
+ if self.owned.contains_key(&partition) {
// The draining sentinel prevents an in-flight follower batch from spawning a replacement
// worker before the old in-memory reconcile queue is gone and its tracker tenure resets.
// The rebalance worker then rewinds the follower, so anything dropped against the
@@ -747,6 +751,7 @@ impl EventDispatcher {
gauge!(LIVE_WATERMARK_AGE_MS, "partition" => partition.to_string()).set(0.0);
gauge!(SEED_PAUSE_AGE_MS, "partition" => partition.to_string()).set(0.0);
gauge!(SEED_OLDEST_HELD_AGE_MS, "partition" => partition.to_string()).set(0.0);
+ gauge!(SLICE_COVERED_SINCE_SECONDS, "partition" => partition.to_string()).set(0.0);
let Some(partition_id) = partition_to_store_id(partition) else {
warn!(
@@ -980,7 +985,7 @@ impl EventDispatcher {
self.tracker
.committable_offsets()
.into_iter()
- .filter(|(partition, _)| self.owned.contains(partition))
+ .filter(|(partition, _)| self.owned.contains_key(partition))
.collect()
}
@@ -1526,7 +1531,9 @@ mod tests {
use tempfile::TempDir;
use uuid::Uuid;
- use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
+ use cohort_core::seed::{
+ BehavioralShapeHash, CoverageStartMs, ReconcileScope, ReconcileTile, RunBoundaryMs, RunId,
+ };
use crate::consumers::readiness::NotReady;
use crate::consumers::seeds::SeedWork;
@@ -1545,7 +1552,8 @@ mod tests {
use crate::stage1::{Stage1State, StatefulRecord};
use crate::store::{
Behavioral, BehavioralKey, CohortStore, LeafStateKey, MergeAppliedKey, MergeDrainKey,
- OffloadConfig, OffloadMode, PendingTransferKey, StoreConfig, TombstoneKey,
+ OffloadConfig, OffloadMode, PendingTransferKey, SliceCoverage, SliceCoverageKey,
+ SliceCoverages, StoreConfig, TombstoneKey,
};
use crate::workers::TransferRetryPolicy;
@@ -2014,7 +2022,13 @@ mod tests {
dispatcher
.reconcile_boot_assignment(&[6].into_iter().collect(), 5)
.await;
+ let before_move_in = CoverageStartMs::now();
dispatcher.assign_partition(5);
+ store
+ .write_batch(|b| {
+ b.put::<SliceCoverages>(&SliceCoverageKey(5), &SliceCoverage::Complete.encode())
+ })
+ .unwrap();
dispatcher.ensure_worker(5);
assert!(
@@ -2036,6 +2050,13 @@ mod tests {
);
dispatcher.shutdown().await;
+ assert!(
+ matches!(
+ store.slice_coverage(5).unwrap(),
+ Some(SliceCoverage::Since(since)) if since >= before_move_in
+ ),
+ "the wiped slice's complete record went with it, so the moved-in slice began again",
+ );
}
#[tokio::test]
@@ -2558,24 +2579,68 @@ mod tests {
);
}
+ /// A worker resolves its slice coverage first, so a processed offset proves it resolved.
+ async fn processed_through(dispatcher: &EventDispatcher, partition: i32, next: i64) {
+ let start = Instant::now();
+ while dispatcher.tracker.committable_offsets().get(&partition) != Some(&next) {
+ assert!(
+ start.elapsed() < Duration::from_secs(10),
+ "offset {next} on partition {partition} was never processed",
+ );
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ }
+
#[tokio::test]
async fn reassign_after_a_full_revoke_respawns_and_advances_offsets() {
let (_dir, store) = temp_store();
let dispatcher = dispatcher_with(&store, behavioral_catalog());
+ // Recorded by an earlier tenure.
+ let earlier = SliceCoverage::Since(CoverageStartMs(1));
+ store
+ .write_batch(|b| b.put::<SliceCoverages>(&SliceCoverageKey(0), &earlier.encode()))
+ .unwrap();
dispatcher.assign_partition(0);
dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ processed_through(&dispatcher, 0, 11).await;
+ assert_eq!(
+ store.slice_coverage(0).unwrap(),
+ Some(earlier),
+ "a spawn resumes the recorded coverage instead of beginning the slice again",
+ );
dispatcher.revoke_partition_sync(0);
dispatcher.revoke_partition_drain(0).await;
assert_eq!(dispatcher.workers.len(), 0);
+ assert_eq!(
+ store.slice_coverage(0).unwrap(),
+ None,
+ "the revoke deleted it"
+ );
+ let before_respawn = CoverageStartMs::now();
dispatcher.assign_partition(0);
+ let reassigned = CoverageStartMs::now();
+ // Spawn in a later millisecond, so a slice begun at spawn fails the bound below.
+ while CoverageStartMs::now() <= reassigned {
+ tokio::task::yield_now().await;
+ }
dispatcher.dispatch(vec![consumed(person(2), 0, 20)]).await;
assert_eq!(
dispatcher.workers.len(),
1,
"a reassigned partition respawns"
);
+ processed_through(&dispatcher, 0, 21).await;
+ assert!(
+ matches!(
+ store.slice_coverage(0).unwrap(),
+ Some(SliceCoverage::Since(since))
+ if before_respawn <= since && since <= reassigned
+ ),
+ "a revoked slice comes back without its history, never complete, and begins at its \
+ reassignment rather than its first delivery",
+ );
let tracker = dispatcher.shutdown().await;
assert_eq!(tracker.committable_offsets().get(&0), Some(&21));
@@ -2651,6 +2716,7 @@ mod tests {
CohortId(1),
ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::from_u128(1)),
+ RunBoundaryMs(0),
);
let held = dispatcher.dispatch_seeds(vec![ConsumedSeed {
work: SeedWork::Reconcile(tile.clone()),
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index 9d6d4cc62379..4b72be2dd897 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -853,7 +853,7 @@ mod tests {
use cohort_core::seed::{
BehavioralShapeHash, ClaimEpoch, ConditionHash, PersonSeed, ReconcileScope, ReconcileTile,
- RunId, SChunkMs, ScannedAtMs,
+ RunBoundaryMs, RunId, SChunkMs, ScannedAtMs,
};
use uuid::Uuid;
@@ -1261,6 +1261,7 @@ mod tests {
.unwrap(),
),
RunId(Uuid::nil()),
+ RunBoundaryMs(0),
);
let bytes = serde_json::to_vec(&reconcile).unwrap();
assert!(matches!(
@@ -1302,6 +1303,7 @@ mod tests {
CohortId(42),
ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::nil()),
+ RunBoundaryMs(0),
);
let reconcile_seed = |offset| ConsumedSeed {
work: SeedWork::Reconcile(reconcile.clone()),
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 8a8e2039ec09..bf21abbc0217 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -76,6 +76,12 @@ pub const DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL: &str = "durable_restore_partiti
/// from the committed offset (counter).
pub const DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL: &str =
"durable_restore_partitions_wiped_stale_total";
+/// Partitions adopted as complete by opening a store without coverage records (counter).
+pub const SLICES_ADOPTED_TOTAL: &str = "cohort_slices_adopted_total";
+/// Slices that began without earlier history (counter). Runs with an earlier boundary withhold.
+pub const SLICES_BEGUN_TOTAL: &str = "cohort_slices_begun_total";
+/// When each slice began, in epoch seconds, by `partition` (gauge). `0` if complete or unowned.
+pub const SLICE_COVERED_SINCE_SECONDS: &str = "cohort_slice_covered_since_seconds";
/// `cf_behavioral` keys re-seeded into a worker's `EvictionQueue` on spawn during a durable restart,
/// labelled by `partition` (counter). Re-fires a dormant person's `Left`.
pub const EVICTION_QUEUE_REBUILT_KEYS_TOTAL: &str = "eviction_queue_rebuilt_keys_total";
@@ -655,9 +661,9 @@ pub const RECONCILE_JOBS_ENQUEUED_TOTAL: &str = "cohort_reconcile_jobs_enqueued_
pub const RECONCILE_JOBS_COMPLETED_TOTAL: &str = "cohort_reconcile_jobs_completed_total";
/// Queued jobs replaced by a higher Kafka offset for the same team, cohort, and `kind` (counter).
pub const RECONCILE_JOBS_SUPERSEDED_TOTAL: &str = "cohort_reconcile_jobs_superseded_total";
-/// Reconcile jobs invalidated by a drain-time guard, labelled by bounded `reason` and `kind`
+/// Reconcile jobs withheld by the drain-time guard, labelled by bounded `reason` and `kind`
/// (counter).
-pub const RECONCILE_JOBS_DISCARDED_TOTAL: &str = "cohort_reconcile_jobs_discarded_total";
+pub const RECONCILE_JOBS_WITHHELD_TOTAL: &str = "cohort_reconcile_jobs_discarded_total";
/// Reconcile jobs the guard would discard against a catalog snapshot older than the job, held until
/// a refresh that began after the job's admission, labelled by `reason` and `kind`. Counted once per
/// job (counter). Each one is a catalog race the processor absorbed instead of stranding the run.
@@ -699,11 +705,11 @@ pub const RECONCILE_PAGE_DURATION_SECONDS: &str = "cohort_reconcile_page_duratio
pub const RECONCILE_ROWS_EMITTED_TOTAL: &str = "cohort_reconcile_rows_emitted_total";
/// Stale Stage 2 bits durably fixed, labelled by `direction` (counter).
pub const RECONCILE_BITS_FIXED_TOTAL: &str = "cohort_reconcile_bits_fixed_total";
-/// Reconcile completion markers acknowledged by Kafka, labelled by `kind` (counter).
+/// Reconcile markers acknowledged by Kafka, labelled by `kind` and `marker` (counter).
pub const RECONCILE_MARKERS_EMITTED_TOTAL: &str = "cohort_reconcile_markers_emitted_total";
-/// Failed completion-marker produces, labelled by `kind` (counter). A permanently failing produce —
-/// a missing or mis-provisioned marker topic — otherwise only shows up as a seed offset that never
-/// advances.
+/// Failed reconcile-marker produce attempts, labelled by `kind` and `marker` (counter). A
+/// permanently failing produce — a missing or mis-provisioned marker topic — otherwise only shows
+/// up as a seed offset that never advances.
pub const RECONCILE_MARKER_PRODUCE_ERRORS: &str = "cohort_reconcile_marker_produce_errors_total";
/// Partition-local reconcile queue depth, labelled by `partition` (gauge).
pub const RECONCILE_QUEUE_DEPTH: &str = "cohort_reconcile_queue_depth";
@@ -805,6 +811,13 @@ mod tests {
DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL,
"durable_restore_pending_transfers_recovered_partitions_total",
);
+ // Alerts select on these.
+ assert_eq!(SLICES_ADOPTED_TOTAL, "cohort_slices_adopted_total");
+ assert_eq!(SLICES_BEGUN_TOTAL, "cohort_slices_begun_total");
+ assert_eq!(
+ SLICE_COVERED_SINCE_SECONDS,
+ "cohort_slice_covered_since_seconds"
+ );
}
#[test]
@@ -1088,7 +1101,7 @@ mod tests {
"cohort_reconcile_jobs_superseded_total",
);
assert_eq!(
- RECONCILE_JOBS_DISCARDED_TOTAL,
+ RECONCILE_JOBS_WITHHELD_TOTAL,
"cohort_reconcile_jobs_discarded_total",
);
assert_eq!(
diff --git a/rust/cohort-stream-processor/src/producer/marker.rs b/rust/cohort-stream-processor/src/producer/marker.rs
index 894af32c94f6..f1d9a222e619 100644
--- a/rust/cohort-stream-processor/src/producer/marker.rs
+++ b/rust/cohort-stream-processor/src/producer/marker.rs
@@ -4,16 +4,19 @@
//! membership output has to move to its own cluster, while markers stay alongside the seed topic on
//! ingestion, and one shared producer would force them to move together.
//!
-//! One topic property the seeder's watcher depends on, recorded here because the topic is
-//! provisioned in another repo and would fail silently: a stable partition count. The watcher
-//! captures a start offset per partition at dispatch and is assigned exactly those, so a partition
-//! added mid-run is never read. Added before that run's observation ends are captured, it holds the
-//! run open until a re-dispatch; added after them, it is not even consulted, and the run settles
-//! short on the markers that landed where nothing was watching.
+//! Two topic properties the seeder's watcher depends on, recorded here because the topic is
+//! provisioned in another repo and would fail silently. The first is a stable partition count. The
+//! watcher captures a start offset per partition at dispatch and is assigned exactly those, so a
+//! partition added mid-run is never read. Added before that run's observation ends are captured, it
+//! holds the run open until a re-dispatch; added after them, it is not even consulted, and the run
+//! settles short on the markers that landed where nothing was watching.
//!
-//! The key ([`reconcile_complete_key`]) carries the body partition, so a run's 64 certificates are
-//! 64 distinct keys rather than one — what stops a compacting topic from keeping whichever arrived
-//! last and recording a completed backfill as short.
+//! The second is the `delete` cleanup policy, never compaction. The key ([`reconcile_marker_key`])
+//! carries the body partition, so a run's 64 certificates are 64 distinct keys rather than one. A
+//! complete and a withheld marker for the same body partition share their key, which puts them on
+//! one topic partition in the order they were produced, and the seeder ignores a withheld marker
+//! that follows its partition's certificate. Compaction would keep only the later of the two, so a
+//! watcher that reads after it would supersede a cohort the partition certified.
use anyhow::{Context, Result};
use async_trait::async_trait;
@@ -25,14 +28,11 @@ use rdkafka::producer::FutureProducer;
use crate::producer::kafka::AlwaysHealthy;
use crate::producer::merge::Capture;
-use crate::producer::ReconcileCompleteMarker;
+use crate::producer::ReconcileMarker;
#[async_trait]
pub trait ReconcileMarkerSink: Send + Sync {
- async fn produce(
- &self,
- markers: Vec<ReconcileCompleteMarker>,
- ) -> Vec<Result<(), KafkaProduceError>>;
+ async fn produce(&self, markers: Vec<ReconcileMarker>) -> Vec<Result<(), KafkaProduceError>>;
}
pub struct KafkaReconcileMarkerSink {
@@ -51,14 +51,11 @@ impl KafkaReconcileMarkerSink {
#[async_trait]
impl ReconcileMarkerSink for KafkaReconcileMarkerSink {
- async fn produce(
- &self,
- markers: Vec<ReconcileCompleteMarker>,
- ) -> Vec<Result<(), KafkaProduceError>> {
+ async fn produce(&self, markers: Vec<ReconcileMarker>) -> Vec<Result<(), KafkaProduceError>> {
send_keyed_iter_to_kafka_with_headers(
&self.producer,
&self.topic,
- reconcile_complete_key,
+ reconcile_marker_key,
|_| None,
markers,
)
@@ -76,10 +73,7 @@ pub struct NoopReconcileMarkerSink;
#[async_trait]
impl ReconcileMarkerSink for NoopReconcileMarkerSink {
- async fn produce(
- &self,
- markers: Vec<ReconcileCompleteMarker>,
- ) -> Vec<Result<(), KafkaProduceError>> {
+ async fn produce(&self, markers: Vec<ReconcileMarker>) -> Vec<Result<(), KafkaProduceError>> {
markers
.into_iter()
.map(|_| Err(KafkaProduceError::KafkaProduceCanceled))
@@ -88,7 +82,7 @@ impl ReconcileMarkerSink for NoopReconcileMarkerSink {
}
#[derive(Debug, Default, Clone)]
-pub struct CaptureReconcileMarkerSink(Capture<ReconcileCompleteMarker>);
+pub struct CaptureReconcileMarkerSink(Capture<ReconcileMarker>);
impl CaptureReconcileMarkerSink {
pub fn new() -> Self {
@@ -99,25 +93,25 @@ impl CaptureReconcileMarkerSink {
Self(Capture::failing_first(n))
}
- pub fn markers(&self) -> Vec<ReconcileCompleteMarker> {
+ pub fn markers(&self) -> Vec<ReconcileMarker> {
self.0.recorded()
}
+
+ pub fn produce_calls(&self) -> usize {
+ self.0.produce_calls()
+ }
}
#[async_trait]
impl ReconcileMarkerSink for CaptureReconcileMarkerSink {
- async fn produce(
- &self,
- markers: Vec<ReconcileCompleteMarker>,
- ) -> Vec<Result<(), KafkaProduceError>> {
+ async fn produce(&self, markers: Vec<ReconcileMarker>) -> Vec<Result<(), KafkaProduceError>> {
self.0.produce(markers)
}
}
-/// Unique per marker, not per run: the partition is what makes 64 distinct keys out of one dispatch,
-/// so no cleanup policy can collapse them. Nothing downstream reads the key and the ledger's fold is
-/// order-independent, so the grouping carries no meaning beyond that.
-fn reconcile_complete_key(marker: &ReconcileCompleteMarker) -> Option<String> {
+/// One key per run, cohort and body partition, shared by its complete and withheld markers so both
+/// land on one topic partition in order. Nothing downstream reads the key.
+fn reconcile_marker_key(marker: &ReconcileMarker) -> Option<String> {
Some(format!(
"{}:{}:{}:{}",
marker.team_id().0,
@@ -131,30 +125,31 @@ fn reconcile_complete_key(marker: &ReconcileCompleteMarker) -> Option<String> {
mod tests {
use super::*;
use crate::filters::{CohortId, TeamId};
+ use crate::producer::ReconcileCompleteMarker;
use cohort_core::seed::RunId;
use uuid::Uuid;
const TS: &str = "2026-05-26 12:34:56.789123";
- fn marker(partition: u16) -> ReconcileCompleteMarker {
- ReconcileCompleteMarker::new(
+ fn marker(partition: u16) -> ReconcileMarker {
+ ReconcileMarker::Complete(ReconcileCompleteMarker::new(
TeamId(42),
CohortId(91204),
partition,
RunId(Uuid::nil()),
TS.to_string(),
- )
+ ))
}
#[test]
- fn reconcile_complete_key_is_unique_per_partition_marker() {
+ fn reconcile_marker_key_is_unique_per_partition_marker() {
assert_eq!(
- reconcile_complete_key(&marker(63)),
+ reconcile_marker_key(&marker(63)),
Some("42:91204:00000000-0000-0000-0000-000000000000:63".to_string())
);
assert_ne!(
- reconcile_complete_key(&marker(63)),
- reconcile_complete_key(&marker(0)),
+ reconcile_marker_key(&marker(63)),
+ reconcile_marker_key(&marker(0)),
"a shared key would let a compacting topic erase all but one marker of a run",
);
}
diff --git a/rust/cohort-stream-processor/src/producer/mod.rs b/rust/cohort-stream-processor/src/producer/mod.rs
index 12bd1b1f8b16..77f0a696cf10 100644
--- a/rust/cohort-stream-processor/src/producer/mod.rs
+++ b/rust/cohort-stream-processor/src/producer/mod.rs
@@ -19,7 +19,7 @@ use serde::{Deserialize, Serialize};
use cohort_core::seed::RunId;
// Hoisted to the shared seed contract so the seeder's marker watcher and this producer agree on the
// wire bytes; re-exported here so processor call sites keep their `crate::producer` import path.
-pub use cohort_core::seed::ReconcileCompleteMarker;
+pub use cohort_core::seed::{ReconcileCompleteMarker, ReconcileMarker, ReconcileWithheldMarker};
use crate::filters::reverse_index::TeamFilters;
use crate::filters::CohortId;
diff --git a/rust/cohort-stream-processor/src/store/coverage.rs b/rust/cohort-stream-processor/src/store/coverage.rs
new file mode 100644
index 000000000000..780ebe939fa1
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/coverage.rs
@@ -0,0 +1,114 @@
+//! Slice coverage: what part of its partition's history a slice holds. Written when the slice
+//! begins and deleted with it, never rewritten, so an older image cannot make it stale.
+
+use cohort_core::seed::{CoverageStartMs, RunBoundaryMs};
+
+/// Not the person-record format version `1`, so the TTL compaction filter keeps the value.
+const VALUE_TAG: u8 = 0xC5;
+const VALUE_FORMAT: u8 = 1;
+const KIND_COMPLETE: u8 = 0;
+const KIND_SINCE: u8 = 1;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SliceCoverage {
+ /// The whole history. Only adoption writes it.
+ Complete,
+ /// Every event the partition delivered after this instant.
+ Since(CoverageStartMs),
+}
+
+impl SliceCoverage {
+ /// A run certifies only if coverage began at or before its boundary; with no boundary, only a
+ /// complete slice does. `Err` is the boundary a recovery run needs. Assumes NTP-synced clocks.
+ pub fn admits(self, boundary: Option<RunBoundaryMs>) -> Result<(), CoverageStartMs> {
+ match (self, boundary) {
+ (Self::Complete, _) => Ok(()),
+ (Self::Since(start), Some(boundary)) if start.0 <= boundary.0 => Ok(()),
+ (Self::Since(start), _) => Err(start),
+ }
+ }
+
+ pub(crate) fn encode(self) -> Vec<u8> {
+ match self {
+ Self::Complete => vec![VALUE_TAG, VALUE_FORMAT, KIND_COMPLETE],
+ Self::Since(start) => {
+ let mut out = vec![VALUE_TAG, VALUE_FORMAT, KIND_SINCE];
+ out.extend_from_slice(&start.0.to_be_bytes());
+ out
+ }
+ }
+ }
+
+ /// `None` reads as no record, so the slice begins again.
+ pub(crate) fn decode(bytes: &[u8]) -> Option<Self> {
+ match bytes {
+ [VALUE_TAG, VALUE_FORMAT, KIND_COMPLETE] => Some(Self::Complete),
+ [VALUE_TAG, VALUE_FORMAT, KIND_SINCE, start @ ..] => Some(Self::Since(
+ CoverageStartMs(i64::from_be_bytes(start.try_into().ok()?)),
+ )),
+ _ => None,
+ }
+ }
+}
+
+/// What resuming a slice found.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SliceTenure {
+ Resumed(SliceCoverage),
+ /// No record, so the slice holds nothing from before this start.
+ Begun(CoverageStartMs),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const T: i64 = 1_791_547_200_000;
+
+ #[test]
+ fn a_partial_slice_certifies_only_runs_whose_boundary_is_at_or_after_its_start() {
+ let since = SliceCoverage::Since(CoverageStartMs(T));
+ let cases = [
+ (SliceCoverage::Complete, None, Ok(())),
+ (SliceCoverage::Complete, Some(T - 1), Ok(())),
+ (since, None, Err(CoverageStartMs(T))),
+ (since, Some(T - 1), Err(CoverageStartMs(T))),
+ (since, Some(T), Ok(())),
+ (since, Some(T + 1), Ok(())),
+ ];
+ for (coverage, boundary, expected) in cases {
+ assert_eq!(
+ coverage.admits(boundary.map(RunBoundaryMs)),
+ expected,
+ "{coverage:?} against boundary {boundary:?}",
+ );
+ }
+ }
+
+ #[test]
+ fn a_coverage_value_round_trips_and_anything_else_reads_as_no_record() {
+ for coverage in [
+ SliceCoverage::Complete,
+ SliceCoverage::Since(CoverageStartMs(T)),
+ SliceCoverage::Since(CoverageStartMs(i64::MIN)),
+ ] {
+ assert_eq!(SliceCoverage::decode(&coverage.encode()), Some(coverage));
+ }
+
+ let mut truncated = SliceCoverage::Since(CoverageStartMs(T)).encode();
+ truncated.pop();
+ let mut extended = SliceCoverage::Complete.encode();
+ extended.push(0);
+ let mut future_format = SliceCoverage::Complete.encode();
+ future_format[1] = VALUE_FORMAT + 1;
+ for undecodable in [
+ Vec::new(),
+ truncated,
+ extended,
+ future_format,
+ vec![VALUE_TAG, VALUE_FORMAT, 7],
+ ] {
+ assert_eq!(SliceCoverage::decode(&undecodable), None, "{undecodable:?}");
+ }
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/handle.rs b/rust/cohort-stream-processor/src/store/handle.rs
index cdc8140170ac..1a27fb06e537 100644
--- a/rust/cohort-stream-processor/src/store/handle.rs
+++ b/rust/cohort-stream-processor/src/store/handle.rs
@@ -22,10 +22,12 @@ use std::str::FromStr;
use std::sync::Arc;
use std::time::Instant;
+use cohort_core::seed::CoverageStartMs;
use metrics::{gauge, histogram};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::task::JoinError;
+use super::coverage::SliceTenure;
use super::keys::{
PendingTransferKey, Stage2CohortPrefix, Stage2DirtyKey, Stage2Key, TombstoneKey,
};
@@ -496,6 +498,18 @@ impl StoreHandle {
.await
}
+ /// Resume a slice's coverage, or begin it at `start`. No permit.
+ pub async fn resume_or_begin_slice(
+ &self,
+ partition_id: u16,
+ start: CoverageStartMs,
+ ) -> Result<SliceTenure, StoreError> {
+ self.write("resume_or_begin_slice", false, move |store| {
+ store.resume_or_begin_slice(partition_id, start)
+ })
+ .await
+ }
+
/// Synchronously fsync the WAL, making every write so far durable. No permit — the commit cadence
/// must not queue behind reads. Under Maintenance this offloads (the fsync is the expensive
/// syscall) even though ordinary writes run inline.
diff --git a/rust/cohort-stream-processor/src/store/keyspace.rs b/rust/cohort-stream-processor/src/store/keyspace.rs
index 1da9318d3e11..604fcf625bf5 100644
--- a/rust/cohort-stream-processor/src/store/keyspace.rs
+++ b/rust/cohort-stream-processor/src/store/keyspace.rs
@@ -143,6 +143,31 @@ impl PersonRecordKey {
}
}
+/// `[partition_id u16][0xFE]` in `cf_person_records`: every image's `delete_partition` removes it
+/// with its slice, and person-record reads are 26-byte point gets that never reach it.
+#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
+pub struct SliceCoverageKey(pub u16);
+
+const SLICE_COVERAGE_KEY_LEN: usize = 3;
+const SLICE_COVERAGE_KEY_SUFFIX: u8 = 0xFE;
+
+impl SliceCoverageKey {
+ pub fn encode(&self) -> [u8; SLICE_COVERAGE_KEY_LEN] {
+ let [high, low] = self.0.to_be_bytes();
+ [high, low, SLICE_COVERAGE_KEY_SUFFIX]
+ }
+
+ pub fn decode(bytes: &[u8]) -> Result<Self, StoreError> {
+ check_len(bytes, SLICE_COVERAGE_KEY_LEN, "slice_coverage")?;
+ if bytes[2] != SLICE_COVERAGE_KEY_SUFFIX {
+ return Err(StoreError::UnknownKey {
+ kind: "slice_coverage",
+ });
+ }
+ Ok(Self(u16::from_be_bytes(array2(&bytes[0..2]))))
+ }
+}
+
/// `cf_meta` key: a small set of ASCII-literal keys carrying store-wide guards (schema version). Not
/// partition-prefixed, so it is exempt from partition wipes.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
@@ -151,6 +176,12 @@ pub struct MetaKey(pub &'static [u8]);
/// `cf_meta[b"schema_version"]` → the store schema version as a big-endian `u32`.
pub const META_SCHEMA_VERSION: MetaKey = MetaKey(b"schema_version");
+/// Present once the store records slice coverage. The value is empty.
+pub const META_SLICE_COVERAGE: MetaKey = MetaKey(b"slice_coverage");
+
+// `Meta::decode` assumes one key length.
+const _: () = assert!(META_SLICE_COVERAGE.0.len() == META_SCHEMA_VERSION.0.len());
+
mod sealed {
/// Sealed so only this module's keyspaces implement [`super::Keyspace`]; downstream code cannot
/// bind a new key type to a CF without declaring its partitioning here.
@@ -193,6 +224,25 @@ impl Keyspace for Behavioral {
}
}
+/// One coverage record per partition, in `cf_person_records`.
+pub struct SliceCoverages;
+
+impl sealed::Sealed for SliceCoverages {}
+
+impl Keyspace for SliceCoverages {
+ const CF: Cf = Cf::PersonRecords;
+ const PARTITIONED: bool = true;
+ type Key = SliceCoverageKey;
+
+ fn encode(key: &SliceCoverageKey) -> Vec<u8> {
+ key.encode().to_vec()
+ }
+
+ fn decode(bytes: &[u8]) -> Result<SliceCoverageKey, StoreError> {
+ SliceCoverageKey::decode(bytes)
+ }
+}
+
/// The per-person-record keyspace: one row per person under the 26-byte prefix. Partitioned, so a
/// partition wipe reclaims it via the shared partition range.
pub struct PersonRecords;
@@ -233,8 +283,11 @@ impl Keyspace for Meta {
// `cf_meta` keys are a closed set of literals; match them rather than fabricate a `&'static`
// from runtime bytes. A wrong length is a length error; a right-length key that matches no
// literal is an unknown key — conflating the two would report "expected N bytes, got N".
- if bytes == META_SCHEMA_VERSION.0 {
- Ok(META_SCHEMA_VERSION)
+ if let Some(key) = [META_SCHEMA_VERSION, META_SLICE_COVERAGE]
+ .into_iter()
+ .find(|key| key.0 == bytes)
+ {
+ Ok(key)
} else if bytes.len() != META_SCHEMA_VERSION.0.len() {
Err(StoreError::KeyDecode {
kind: "meta",
@@ -452,6 +505,10 @@ mod tests {
// match `delete_partition` relies on. A drift here would range-delete (or spare) the wrong CF.
assert_eq!(Behavioral::PARTITIONED, Cf::Behavioral.partitioned());
assert_eq!(PersonRecords::PARTITIONED, Cf::PersonRecords.partitioned());
+ assert_eq!(
+ SliceCoverages::PARTITIONED,
+ SliceCoverages::CF.partitioned()
+ );
assert_eq!(Meta::PARTITIONED, Cf::Meta.partitioned());
}
@@ -512,6 +569,10 @@ mod tests {
Meta::decode(b"schema_version").unwrap(),
META_SCHEMA_VERSION,
);
+ assert_eq!(
+ Meta::decode(b"slice_coverage").unwrap(),
+ META_SLICE_COVERAGE,
+ );
// Wrong length reports the length; a right-length unknown key reports the content — a
// conflation would claim "expected 14 bytes, got 14" for the latter.
assert!(matches!(
diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rs
index 6a183a5dffce..5f04c0821695 100644
--- a/rust/cohort-stream-processor/src/store/mod.rs
+++ b/rust/cohort-stream-processor/src/store/mod.rs
@@ -1,6 +1,7 @@
//! RocksDB state store.
pub mod column_families;
+pub mod coverage;
pub mod durability;
pub mod handle;
pub mod keys;
@@ -13,6 +14,7 @@ pub use column_families::{
Cf, OpaqueCf, CF_BEHAVIORAL, CF_MERGE_APPLIED, CF_MERGE_DRAINS_APPLIED, CF_MERGE_TOMBSTONES,
CF_META, CF_PENDING_TRANSFERS, CF_PERSON_RECORDS, CF_STAGE2,
};
+pub use coverage::{SliceCoverage, SliceTenure};
pub use handle::{OffloadConfig, OffloadMode, ReadLane, StoreHandle};
pub use keys::{
MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2CohortPrefix, Stage2DirtyKey,
@@ -21,7 +23,7 @@ pub use keys::{
};
pub use keyspace::{
Behavioral, BehavioralKey, Keyspace, Meta, MetaKey, PersonPrefix, PersonRecordKey,
- PersonRecords,
+ PersonRecords, SliceCoverageKey, SliceCoverages,
};
pub use rocks::{
BatchBuilder, CfStats, CohortStore, EventSnapshotRaw, Stage2DirtyTrackingGuard, StoreConfig,
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
index caf9123c96e2..0292c7ce5c67 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -22,23 +22,28 @@ use rocksdb::{
ReadOptions, SingleThreaded, WriteBatch, WriteOptions,
};
use thiserror::Error;
-use tracing::warn;
+use tracing::{info, warn};
+
+use cohort_core::partitioner::COHORT_PARTITION_COUNT;
+use cohort_core::seed::CoverageStartMs;
use super::column_families::{self, Cf, OpaqueCf};
+use super::coverage::{SliceCoverage, SliceTenure};
use super::keys::{
self, MergeAppliedKey, MergeDrainKey, PendingTransferKey, Stage2CohortPrefix, Stage2DirtyKey,
Stage2Key, Stage2TransferredRegisterKey, Stage2TransferredRegisterPersonPrefix, TombstoneKey,
STAGE2_DIRTY_KEY_LEN,
};
use super::keyspace::{
- BehavioralKey, Keyspace, Meta, PersonPrefix, PersonRecordKey, META_SCHEMA_VERSION,
+ BehavioralKey, Keyspace, Meta, PersonPrefix, PersonRecordKey, SliceCoverageKey, SliceCoverages,
+ META_SCHEMA_VERSION, META_SLICE_COVERAGE,
};
use super::staged::{StagedBatch, StagedOp};
use crate::observability::metrics::{
- CHECKPOINT_DURATION_SECONDS, STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL, STORE_ERRORS_TOTAL,
- STORE_READS_TOTAL, STORE_READ_DURATION_SECONDS, STORE_SCHEMA_MISMATCH_WIPES_TOTAL,
- STORE_WRITE_BATCH_TOTAL, STORE_WRITE_DURATION_SECONDS, WAL_FSYNC_DURATION_SECONDS,
- WAL_FSYNC_ERRORS_TOTAL,
+ CHECKPOINT_DURATION_SECONDS, SLICES_ADOPTED_TOTAL, STAGE2_SCAN_UNDECODABLE_KEYS_TOTAL,
+ STORE_ERRORS_TOTAL, STORE_READS_TOTAL, STORE_READ_DURATION_SECONDS,
+ STORE_SCHEMA_MISMATCH_WIPES_TOTAL, STORE_WRITE_BATCH_TOTAL, STORE_WRITE_DURATION_SECONDS,
+ WAL_FSYNC_DURATION_SECONDS, WAL_FSYNC_ERRORS_TOTAL,
};
/// On-disk store schema version, stamped into `cf_meta` at first open and checked on every reopen.
@@ -112,6 +117,8 @@ pub struct StoreConfig {
/// `cf_person_records` **only** — never `cf_behavioral`, whose eviction deadlines are the sweep's
/// contract. See [`super::ttl_filter`].
pub person_record_ttl_days: u32,
+ /// Partitions adopted as complete when the store predates coverage records.
+ pub partition_count: u16,
}
impl Default for StoreConfig {
@@ -134,6 +141,7 @@ impl Default for StoreConfig {
periodic_compaction_seconds: 0,
max_background_jobs: 0,
person_record_ttl_days: 0,
+ partition_count: COHORT_PARTITION_COUNT as u16,
}
}
}
@@ -320,6 +328,8 @@ impl CohortStore {
/// which destroys and recreates the store, then stamps the fresh one. A store carrying a CF outside
/// `Cf::ALL` never reaches this guard: it fails earlier in [`Self::open_inner`] (see there for the
/// extra-vs-subset asymmetry the version key exists to close).
+ ///
+ /// An existing store without the coverage stamp adopts every partition as complete.
pub fn open(config: &StoreConfig) -> Result<Self, StoreError> {
let db_opts = db_options(config);
@@ -331,7 +341,12 @@ impl CohortStore {
loop {
let store = Self::open_inner(config, &db_opts)?;
match store.check_schema(path_existed, config.wipe_on_schema_mismatch)? {
- SchemaCheck::Ok => return Ok(store),
+ SchemaCheck::Ok => {
+ if path_existed {
+ store.settle_coverage(config.partition_count)?;
+ }
+ return Ok(store);
+ }
SchemaCheck::WipeAndRetry => {
// Drop the handle before destroy: RocksDB cannot destroy an open DB.
drop(store);
@@ -396,7 +411,7 @@ impl CohortStore {
wipe_on_schema_mismatch: bool,
) -> Result<SchemaCheck, StoreError> {
if !path_existed {
- self.stamp_schema_version()?;
+ self.stamp_new_store()?;
return Ok(SchemaCheck::Ok);
}
let found = self
@@ -418,13 +433,73 @@ impl CohortStore {
}
}
- /// Stamp `cf_meta[b"schema_version"]` with the current schema version (big-endian `u32`).
- fn stamp_schema_version(&self) -> Result<(), StoreError> {
+ /// Stamp a new store with the schema version (big-endian `u32`) and the coverage stamp.
+ fn stamp_new_store(&self) -> Result<(), StoreError> {
self.write_batch(|batch| {
batch.put::<Meta>(&META_SCHEMA_VERSION, &STORE_SCHEMA_VERSION.to_be_bytes());
+ batch.put::<Meta>(&META_SLICE_COVERAGE, &[]);
})
}
+ /// Adopt every partition as complete in a store without the coverage stamp. The stamp rides the
+ /// same batch, so adoption happens once.
+ fn settle_coverage(&self, partition_count: u16) -> Result<(), StoreError> {
+ if self
+ .get(Meta::CF, &Meta::encode(&META_SLICE_COVERAGE))?
+ .is_some()
+ {
+ return Ok(());
+ }
+ let complete = SliceCoverage::Complete.encode();
+ self.write_batch(|batch| {
+ for partition_id in 0..partition_count {
+ batch.put::<SliceCoverages>(&SliceCoverageKey(partition_id), &complete);
+ }
+ batch.put::<Meta>(&META_SLICE_COVERAGE, &[]);
+ })?;
+ counter!(SLICES_ADOPTED_TOTAL).increment(u64::from(partition_count));
+ info!(
+ partitions = partition_count,
+ "store predates slice coverage records; adopted every partition as complete",
+ );
+ Ok(())
+ }
+
+ /// `None` when the slice has no readable record.
+ pub fn slice_coverage(&self, partition_id: u16) -> Result<Option<SliceCoverage>, StoreError> {
+ let key = SliceCoverages::encode(&SliceCoverageKey(partition_id));
+ let Some(value) = self.get(SliceCoverages::CF, &key)? else {
+ return Ok(None);
+ };
+ let coverage = SliceCoverage::decode(&value);
+ if coverage.is_none() {
+ warn!(
+ partition_id,
+ "undecodable slice coverage record; the slice begins again"
+ );
+ }
+ Ok(coverage)
+ }
+
+ /// Begins the slice at `start` when it has no record. The commit loop's fsync makes the write
+ /// durable before any offset commits.
+ pub fn resume_or_begin_slice(
+ &self,
+ partition_id: u16,
+ start: CoverageStartMs,
+ ) -> Result<SliceTenure, StoreError> {
+ if let Some(coverage) = self.slice_coverage(partition_id)? {
+ return Ok(SliceTenure::Resumed(coverage));
+ }
+ self.write_batch(|batch| {
+ batch.put::<SliceCoverages>(
+ &SliceCoverageKey(partition_id),
+ &SliceCoverage::Since(start).encode(),
+ );
+ })?;
+ Ok(SliceTenure::Begun(start))
+ }
+
/// Read a raw value from any CF.
pub fn get(&self, cf: Cf, key: &[u8]) -> Result<Option<Vec<u8>>, StoreError> {
let handle = self.cf(cf)?;
@@ -2617,6 +2692,80 @@ mod tests {
assert_eq!(lsks, sorted, "leaves come back in lsk-byte order");
}
+ #[test]
+ fn slice_coverage_is_settled_once_per_store_and_dies_with_its_slice() {
+ let t = CoverageStartMs(1_791_547_200_000);
+ let later = CoverageStartMs(t.0 + 60_000);
+ let created = TempDir::new().unwrap();
+ let config = StoreConfig {
+ path: created.path().join("db"),
+ partition_count: 4,
+ ..StoreConfig::default()
+ };
+ {
+ let store = CohortStore::open(&config).unwrap();
+ assert_eq!(
+ store.slice_coverage(0).unwrap(),
+ None,
+ "a created store adopts nothing"
+ );
+ for partition_id in [1, 2] {
+ assert_eq!(
+ store.resume_or_begin_slice(partition_id, t).unwrap(),
+ SliceTenure::Begun(t),
+ );
+ }
+ }
+
+ // Reopened: records resume, and nothing is adopted.
+ let store = CohortStore::open(&config).unwrap();
+ assert_eq!(store.slice_coverage(0).unwrap(), None);
+ assert_eq!(
+ store.resume_or_begin_slice(1, later).unwrap(),
+ SliceTenure::Resumed(SliceCoverage::Since(t)),
+ );
+
+ // The record dies with its slice.
+ store.delete_partition(1).unwrap();
+ assert_eq!(
+ store.resume_or_begin_slice(1, later).unwrap(),
+ SliceTenure::Begun(later),
+ );
+ assert_eq!(
+ store.slice_coverage(2).unwrap(),
+ Some(SliceCoverage::Since(t))
+ );
+
+ // A store without the stamp adopts every partition.
+ let legacy = TempDir::new().unwrap();
+ let config = StoreConfig {
+ path: legacy.path().join("db"),
+ ..config
+ };
+ CohortStore::open(&config)
+ .unwrap()
+ .write_batch(|batch| batch.delete::<Meta>(&META_SLICE_COVERAGE))
+ .unwrap();
+ let store = CohortStore::open(&config).unwrap();
+ assert_eq!(
+ (0..5)
+ .map(|partition_id| store.slice_coverage(partition_id).unwrap())
+ .collect::<Vec<_>>(),
+ [[Some(SliceCoverage::Complete); 4].as_slice(), &[None]].concat(),
+ );
+
+ // Adoption happens once.
+ store.delete_partition(0).unwrap();
+ drop(store);
+ assert_eq!(
+ CohortStore::open(&config)
+ .unwrap()
+ .slice_coverage(0)
+ .unwrap(),
+ None
+ );
+ }
+
#[test]
fn delete_partition_wipes_partitioned_cfs_but_preserves_the_schema_stamp() {
let dir = TempDir::new().unwrap();
diff --git a/rust/cohort-stream-processor/src/store/ttl_filter.rs b/rust/cohort-stream-processor/src/store/ttl_filter.rs
index 5e70ed28fc91..8f70b274a4ff 100644
--- a/rust/cohort-stream-processor/src/store/ttl_filter.rs
+++ b/rust/cohort-stream-processor/src/store/ttl_filter.rs
@@ -137,7 +137,10 @@ fn filter_name() -> CString {
#[cfg(test)]
mod tests {
use super::*;
+ use cohort_core::seed::CoverageStartMs;
+
use crate::stage1::person_record::{PersonRecord, Stamp};
+ use crate::store::SliceCoverage;
fn record_with_last_seen(last_seen_ms: i64) -> Vec<u8> {
let mut record = PersonRecord::absent();
@@ -173,6 +176,10 @@ mod tests {
#[test]
fn malformed_values_are_always_kept() {
let mut filter = factory_at(40 * MS_PER_DAY, 30).create(context()); // cutoff = day 10
+
+ // Slice coverage records share the CF.
+ let complete = SliceCoverage::Complete.encode();
+ let since_day_one = SliceCoverage::Since(CoverageStartMs(MS_PER_DAY)).encode();
for value in [
[].as_slice(),
&[FORMAT_VERSION], // version only
@@ -180,6 +187,8 @@ mod tests {
// tightest truncation the length guard must reject.
&[FORMAT_VERSION, 0, 0, 0, 0, 0, 0, 0, 0],
&[0xFF; 32], // wrong version byte, plenty long
+ &complete,
+ &since_day_one,
] {
assert!(
matches!(filter.filter(0, b"k", value), Decision::Keep),
diff --git a/rust/cohort-stream-processor/src/sweep/reconcile.rs b/rust/cohort-stream-processor/src/sweep/reconcile.rs
index 5ae739615b0c..2cb867a62c98 100644
--- a/rust/cohort-stream-processor/src/sweep/reconcile.rs
+++ b/rust/cohort-stream-processor/src/sweep/reconcile.rs
@@ -43,12 +43,16 @@ mod tests {
use uuid::Uuid;
use cohort_core::filters::{CohortId, TeamId};
- use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
+ use cohort_core::seed::{
+ BehavioralShapeHash, ReconcileScope, ReconcileTile, RunBoundaryMs, RunId,
+ };
use crate::filters::{CatalogHandle, FilterCatalog};
use crate::partitions::{OffsetTracker, PartitionRouter};
use crate::producer::{CaptureSink, MembershipSink};
- use crate::store::{CohortStore, OffloadConfig, OffloadMode, StoreConfig, StoreHandle};
+ use crate::store::{
+ CohortStore, OffloadConfig, OffloadMode, SliceCoverage, StoreConfig, StoreHandle,
+ };
use crate::workers::reconcile::ReconcileQueue;
use crate::workers::MergeWorkerDeps;
@@ -92,13 +96,20 @@ mod tests {
let tracker = OffsetTracker::new();
tracker.mark_dispatched(0, 6);
- let mut queue = ReconcileQueue::new(0, backlog, handle, Arc::new(CatalogHandle::new()));
+ let mut queue = ReconcileQueue::new(
+ 0,
+ backlog,
+ handle,
+ Arc::new(CatalogHandle::new()),
+ SliceCoverage::Complete,
+ );
queue.enqueue(
ReconcileTile::new(
TeamId(7),
CohortId(1),
ReconcileScope::Behavioral(BehavioralShapeHash::parse("shape-v1").unwrap()),
RunId(Uuid::nil()),
+ RunBoundaryMs(0),
),
tracker.defer(0, 5),
);
diff --git a/rust/cohort-stream-processor/src/workers/reconcile.rs b/rust/cohort-stream-processor/src/workers/reconcile.rs
index cfa437b50728..be9647299095 100644
--- a/rust/cohort-stream-processor/src/workers/reconcile.rs
+++ b/rust/cohort-stream-processor/src/workers/reconcile.rs
@@ -16,14 +16,14 @@ use cohort_core::clickhouse_timestamp_to_millis;
use cohort_core::filters::{CohortId, TeamId};
#[cfg(test)]
use cohort_core::seed::RunId;
-use cohort_core::seed::{ReconcileScope, ReconcileTile, ScopeKind};
+use cohort_core::seed::{CatalogMiss, ReconcileScope, ReconcileTile, ScopeKind, WithheldReason};
use cohort_core::CohortEligibility;
use crate::filters::manager::{CatalogHandle, CatalogView, RefreshSeq};
use crate::filters::reverse_index::TeamFilters;
use crate::observability::metrics::{
COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH, RECONCILE_BITS_FIXED_TOTAL,
- RECONCILE_JOBS_COMPLETED_TOTAL, RECONCILE_JOBS_DEFERRED_TOTAL, RECONCILE_JOBS_DISCARDED_TOTAL,
+ RECONCILE_JOBS_COMPLETED_TOTAL, RECONCILE_JOBS_DEFERRED_TOTAL, RECONCILE_JOBS_WITHHELD_TOTAL,
RECONCILE_MARKERS_EMITTED_TOTAL, RECONCILE_MARKER_PRODUCE_ERRORS,
RECONCILE_PAGE_DURATION_SECONDS, RECONCILE_QUEUE_DEPTH, RECONCILE_ROWS_EMITTED_TOTAL,
RECONCILE_ROWS_SCANNED_TOTAL,
@@ -31,11 +31,12 @@ use crate::observability::metrics::{
use crate::partitions::offset_tracker::{DeferredOffset, MarkOutcome, OffsetTracker};
use crate::producer::{
ChangeOrigin, CohortMembershipChange, MembershipSink, NoopReconcileMarkerSink,
- ReconcileCompleteMarker, ReconcileMarkerSink,
+ ReconcileCompleteMarker, ReconcileMarker, ReconcileMarkerSink, ReconcileWithheldMarker,
};
use crate::stage2::Stage2State;
use crate::store::{
- ReadLane, Stage2CohortPrefix, Stage2DirtyKey, Stage2Key, StagedBatch, StoreHandle,
+ ReadLane, SliceCoverage, Stage2CohortPrefix, Stage2DirtyKey, Stage2Key, StagedBatch,
+ StoreHandle,
};
use crate::workers::merge_path::MergeWorkerDeps;
use crate::workers::reconcile_page::read_page;
@@ -150,6 +151,8 @@ pub(crate) struct ReconcileQueue {
/// `enqueue` records the newest refresh this handle has begun on each job, and the drain compares
/// it with the refresh this handle last published.
catalog: Arc<CatalogHandle>,
+ /// Fixed for the worker's life: a record changes only when its slice is deleted.
+ coverage: SliceCoverage,
}
impl ReconcileQueue {
@@ -158,6 +161,7 @@ impl ReconcileQueue {
backlog: Arc<ReconcileBacklog>,
handle: StoreHandle,
catalog: Arc<CatalogHandle>,
+ coverage: SliceCoverage,
) -> Self {
let queue = Self {
jobs: VecDeque::new(),
@@ -165,6 +169,7 @@ impl ReconcileQueue {
partition_label: Arc::from(partition_id.to_string()),
handle,
catalog,
+ coverage,
};
queue.record_depth();
queue
@@ -277,28 +282,7 @@ impl Drop for ReconcileQueue {
enum ReconcileRetryReason {
CatalogNotLoaded,
/// The snapshot predates the job, so the miss may be a write it has not read yet.
- AwaitingRefresh(ReconcileDiscardReason),
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum ReconcileDiscardReason {
- TeamAbsent,
- CohortAbsent,
- NotEmitting,
- HashMismatch,
- HashUnknown,
-}
-
-impl ReconcileDiscardReason {
- const fn as_str(self) -> &'static str {
- match self {
- Self::TeamAbsent => "team_absent",
- Self::CohortAbsent => "cohort_absent",
- Self::NotEmitting => "not_emitting",
- Self::HashMismatch => "hash_mismatch",
- Self::HashUnknown => "hash_unknown",
- }
- }
+ AwaitingRefresh(CatalogMiss),
}
#[derive(Debug)]
@@ -310,30 +294,30 @@ enum ReconcileGuard {
eligibility: CohortEligibility,
},
Retry(ReconcileRetryReason),
- Discard(ReconcileDiscardReason),
+ Withhold(WithheldReason),
}
/// The catalog's answer alone, with no view of how fresh the catalog is.
fn catalog_verdict(
filters: Option<&Arc<TeamFilters>>,
tile: &ReconcileTile,
-) -> Result<(Arc<TeamFilters>, CohortEligibility), ReconcileDiscardReason> {
+) -> Result<(Arc<TeamFilters>, CohortEligibility), CatalogMiss> {
let Some(filters) = filters else {
- return Err(ReconcileDiscardReason::TeamAbsent);
+ return Err(CatalogMiss::TeamAbsent);
};
if !filters.cohorts.contains_key(&tile.cohort_id()) {
- return Err(ReconcileDiscardReason::CohortAbsent);
+ return Err(CatalogMiss::CohortAbsent);
}
let Some(&eligibility) = filters.eligibility.get(&tile.cohort_id()) else {
- return Err(ReconcileDiscardReason::CohortAbsent);
+ return Err(CatalogMiss::CohortAbsent);
};
if !eligibility.registers_membership() {
- return Err(ReconcileDiscardReason::NotEmitting);
+ return Err(CatalogMiss::NotEmitting);
}
// The tile's scope picks the guard map, so a person hash is never checked against a behavioral
// one. An absent entry means the cohort has no leaves of that kind (the loader omits the column
// when it is empty) or the run was superseded; either way this is the intended fail-closed skip,
- // observable via the `hash_unknown` discard counter.
+ // observable via the `hash_unknown` withheld marker.
let matches = match tile.scope() {
ReconcileScope::Behavioral(pinned) => filters
.behavioral_shape_hashes
@@ -345,20 +329,23 @@ fn catalog_verdict(
.map(|current| current == pinned),
};
match matches {
- None => Err(ReconcileDiscardReason::HashUnknown),
- Some(false) => Err(ReconcileDiscardReason::HashMismatch),
+ None => Err(CatalogMiss::HashUnknown),
+ Some(false) => Err(CatalogMiss::HashMismatch),
Some(true) => Ok((filters.clone(), eligibility)),
}
}
-/// The one place that decides a job's fate. Every discard reason reads the catalog, so a miss
+/// The one place that decides a job's fate. Every catalog miss reads the catalog, so a miss
/// against a snapshot whose refresh began before the job was admitted may only mean that refresh
/// had not read the run's writes yet. Such a miss waits. After one later refresh it stands, so a
/// superseded run still fails closed.
+///
+/// Coverage is checked after the catalog and before any scan, so a partial slice emits no rows.
fn evaluate_guard(
view: &CatalogView,
admitted_after: RefreshSeq,
tile: &ReconcileTile,
+ coverage: SliceCoverage,
) -> ReconcileGuard {
let (published, catalog) = match view {
CatalogView::NotLoaded => {
@@ -367,18 +354,23 @@ fn evaluate_guard(
CatalogView::Loaded { published, catalog } => (*published, catalog),
};
match catalog_verdict(catalog.team(tile.team_id()), tile) {
- Ok((filters, eligibility)) => ReconcileGuard::Proceed {
- filters,
- eligibility,
+ Err(miss) if published > admitted_after => {
+ ReconcileGuard::Withhold(WithheldReason::Catalog(miss))
+ }
+ Err(miss) => ReconcileGuard::Retry(ReconcileRetryReason::AwaitingRefresh(miss)),
+ Ok((filters, eligibility)) => match coverage.admits(tile.boundary()) {
+ Ok(()) => ReconcileGuard::Proceed {
+ filters,
+ eligibility,
+ },
+ Err(covered_since) => {
+ ReconcileGuard::Withhold(WithheldReason::PartialCoverage { covered_since })
+ }
},
- Err(reason) if published > admitted_after => ReconcileGuard::Discard(reason),
- Err(reason) => ReconcileGuard::Retry(ReconcileRetryReason::AwaitingRefresh(reason)),
}
}
-/// Advance at most one scan page for the queue head. Guard-discarded jobs are drained in the same
-/// tick; a successfully completed job stops the tick so the next queued snapshot gets its own page
-/// budget.
+/// Advance the queue head by at most one scan page or one marker produce per tick.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_reconcile_drain(
partition_id: u16,
@@ -396,72 +388,55 @@ pub(crate) async fn handle_reconcile_drain(
let phase = job.phase.clone();
let source_offset = job.offset.offset();
- let (filters, eligibility) =
- match evaluate_guard(&queue.catalog.view(), job.admitted_after, &tile) {
- ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded) => {
- debug!(
- partition_id,
- team_id = tile.team_id().0,
- cohort_id = tile.cohort_id().0,
- run_id = %tile.run_id().0,
- "reconcile drain waiting for the first filter catalog load",
- );
- return;
- }
- ReconcileGuard::Retry(ReconcileRetryReason::AwaitingRefresh(reason)) => {
- let job = queue
- .front_mut()
- .expect("the guarded queue head is still present");
- if !job.deferral_counted {
- job.deferral_counted = true;
- counter!(
- RECONCILE_JOBS_DEFERRED_TOTAL,
- "reason" => reason.as_str(),
- "kind" => tile.scope().kind().as_str(),
- )
- .increment(1);
- info!(
- partition_id,
- team_id = tile.team_id().0,
- cohort_id = tile.cohort_id().0,
- run_id = %tile.run_id().0,
- reason = reason.as_str(),
- kind = tile.scope().kind().as_str(),
- "reconcile job waits for a catalog refresh that began after it arrived",
- );
- }
- return;
- }
- ReconcileGuard::Discard(reason) => {
- let discarded = queue
- .finish_front()
- .expect("the guarded queue head is still present");
- complete_offset(
- &merge.seed_tracker,
- partition_id,
- discarded.offset,
- "discarded reconcile",
- );
+ let (filters, eligibility) = match evaluate_guard(
+ &queue.catalog.view(),
+ job.admitted_after,
+ &tile,
+ queue.coverage,
+ ) {
+ ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded) => {
+ debug!(
+ partition_id,
+ team_id = tile.team_id().0,
+ cohort_id = tile.cohort_id().0,
+ run_id = %tile.run_id().0,
+ "reconcile drain waiting for the first filter catalog load",
+ );
+ return;
+ }
+ ReconcileGuard::Retry(ReconcileRetryReason::AwaitingRefresh(reason)) => {
+ let job = queue
+ .front_mut()
+ .expect("the guarded queue head is still present");
+ if !job.deferral_counted {
+ job.deferral_counted = true;
counter!(
- RECONCILE_JOBS_DISCARDED_TOTAL,
+ RECONCILE_JOBS_DEFERRED_TOTAL,
"reason" => reason.as_str(),
"kind" => tile.scope().kind().as_str(),
)
.increment(1);
- warn_job!(
- tile,
+ info!(
partition_id,
+ team_id = tile.team_id().0,
+ cohort_id = tile.cohort_id().0,
+ run_id = %tile.run_id().0,
reason = reason.as_str(),
kind = tile.scope().kind().as_str(),
- "discarding reconcile job without a completion marker",
+ "reconcile job waits for a catalog refresh that began after it arrived",
);
- continue;
}
- ReconcileGuard::Proceed {
- filters,
- eligibility,
- } => (filters, eligibility),
- };
+ return;
+ }
+ ReconcileGuard::Withhold(reason) => {
+ drain_withheld(partition_id, merge, queue, reason).await;
+ return;
+ }
+ ReconcileGuard::Proceed {
+ filters,
+ eligibility,
+ } => (filters, eligibility),
+ };
// Only flipped bits of a full-tree cohort cascade to referrers; single-leaf fixes never do.
let cascades_flips = eligibility.writes_cf_stage2();
@@ -766,6 +741,95 @@ async fn drain_dirty(
}
}
+/// Withhold the consecutive withheld jobs at the head in one produce, releasing the acked prefix.
+async fn drain_withheld(
+ partition_id: u16,
+ merge: &MergeWorkerDeps,
+ queue: &mut ReconcileQueue,
+ head: WithheldReason,
+) {
+ let view = queue.catalog.view();
+ let coverage = queue.coverage;
+ let reasons: Vec<WithheldReason> = std::iter::once(head)
+ .chain(queue.jobs.iter().skip(1).map_while(|job| {
+ match evaluate_guard(&view, job.admitted_after, &job.tile, coverage) {
+ ReconcileGuard::Withhold(reason) => Some(reason),
+ ReconcileGuard::Proceed { .. } | ReconcileGuard::Retry(_) => None,
+ }
+ }))
+ // A tick produces at most one scan page of messages, as a scan tick does, so a burst spreads
+ // over ticks instead of holding the live lane behind one unbounded produce.
+ .take(merge.reconcile.scan_page)
+ .collect();
+ let markers = queue
+ .jobs
+ .iter()
+ .zip(&reasons)
+ .map(|(job, &reason)| {
+ ReconcileMarker::Withheld(ReconcileWithheldMarker::new(
+ job.tile.team_id(),
+ job.tile.cohort_id(),
+ partition_id,
+ job.tile.run_id(),
+ reason,
+ ))
+ })
+ .collect();
+ let acks = merge.reconcile.marker_sink.produce(markers).await;
+ let acked = acks
+ .iter()
+ .take_while(|ack| ack.is_ok())
+ .count()
+ .min(reasons.len());
+
+ for reason in &reasons[..acked] {
+ let job = queue
+ .finish_front()
+ .expect("an acked withheld job is still queued");
+ let kind = job.tile.scope().kind().as_str();
+ counter!(RECONCILE_MARKERS_EMITTED_TOTAL, "kind" => kind, "marker" => "withheld")
+ .increment(1);
+ complete_offset(
+ &merge.seed_tracker,
+ partition_id,
+ job.offset,
+ "withheld reconcile",
+ );
+ counter!(
+ RECONCILE_JOBS_WITHHELD_TOTAL,
+ "reason" => reason.as_str(),
+ "kind" => kind,
+ )
+ .increment(1);
+ warn_job!(
+ job.tile,
+ partition_id,
+ reason = reason.as_str(),
+ covered_since_ms = reason.covered_since().map(|since| since.0),
+ kind,
+ "withholding the reconcile certificate",
+ );
+ }
+ if acked < reasons.len() {
+ let tile = &queue
+ .front()
+ .expect("the unacked withheld job is still queued")
+ .tile;
+ counter!(
+ RECONCILE_MARKER_PRODUCE_ERRORS,
+ "kind" => tile.scope().kind().as_str(),
+ "marker" => "withheld",
+ )
+ .increment(1);
+ warn_job!(
+ tile,
+ partition_id,
+ unacked = reasons.len() - acked,
+ "reconcile withheld-marker produce failed; deciding the jobs again on the next tick",
+ );
+ }
+}
+
/// Emit the per-partition completion marker once the dirty set is drained. A failed marker produce
/// retries the marker only; work dirtied while the marker was pending is settled before the retry.
async fn drain_marker(
@@ -798,19 +862,20 @@ async fn drain_marker(
.phase = ScanPhase::DrainingDirty { cursor: None };
return DrainStep::Reenter;
}
- let marker = ReconcileCompleteMarker::new(
+ let marker = ReconcileMarker::Complete(ReconcileCompleteMarker::new(
tile.team_id(),
tile.cohort_id(),
partition_id,
tile.run_id(),
last_updated.to_string(),
- );
+ ));
let acks = merge.reconcile.marker_sink.produce(vec![marker]).await;
let kind = tile.scope().kind().as_str();
// Exactly one marker went in, so anything but a single successful ack is a produce failure.
let failed_acks = acks.iter().filter(|ack| ack.is_err()).count();
if acks.len() != 1 || failed_acks > 0 {
- counter!(RECONCILE_MARKER_PRODUCE_ERRORS, "kind" => kind).increment(1);
+ counter!(RECONCILE_MARKER_PRODUCE_ERRORS, "kind" => kind, "marker" => "complete")
+ .increment(1);
warn_job!(
tile,
partition_id,
@@ -821,7 +886,7 @@ async fn drain_marker(
return DrainStep::Yield;
}
- counter!(RECONCILE_MARKERS_EMITTED_TOTAL, "kind" => kind).increment(1);
+ counter!(RECONCILE_MARKERS_EMITTED_TOTAL, "kind" => kind, "marker" => "complete").increment(1);
let completed = queue
.finish_front()
.expect("the marker-producing queue head is still present");
@@ -1069,12 +1134,16 @@ fn complete_offset(
#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
+ use std::sync::atomic::AtomicBool;
+
+ use async_trait::async_trait;
use chrono_tz::UTC;
+ use common_kafka::kafka_producer::KafkaProduceError;
use serde_json::{json, Value};
use tempfile::TempDir;
use uuid::Uuid;
- use cohort_core::seed::{BehavioralShapeHash, PersonShapeHash};
+ use cohort_core::seed::{BehavioralShapeHash, CoverageStartMs, PersonShapeHash, RunBoundaryMs};
use cohort_core::{CohortEligibility, ExcludedReason, FilterCatalog, LeafStateKey};
use crate::filters::tree::{CohortTree, FilterNode};
@@ -1100,6 +1169,8 @@ mod tests {
const PERSON_HASH: [u8; 16] = *b"fedcba9876543210";
const SHAPE_HASH: &str = "shape-v1";
const TS: &str = "2026-05-26 12:34:56.789123";
+ /// Start of a partial slice, and the default tile boundary.
+ const SLICE_START: i64 = 1_791_547_200_000;
fn temp_store() -> (TempDir, CohortStore) {
let dir = TempDir::new().unwrap();
@@ -1257,6 +1328,7 @@ mod tests {
deps.reconcile.backlog.clone(),
handle.clone(),
catalog.clone(),
+ SliceCoverage::Complete,
);
Self {
_dir,
@@ -1271,6 +1343,18 @@ mod tests {
}
}
+ /// Replaces the queue, so call it before enqueueing.
+ fn cover(&mut self, coverage: SliceCoverage) {
+ assert_eq!(self.queue.len(), 0, "covering replaces the queue");
+ self.queue = ReconcileQueue::new(
+ PARTITION,
+ self.deps.reconcile.backlog.clone(),
+ self.handle.clone(),
+ self.catalog.clone(),
+ coverage,
+ );
+ }
+
/// Re-arm the marker sink to fail its first produce, isolating the marker phase's retry from
/// the membership leg's.
fn fail_first_marker(&mut self) {
@@ -1390,11 +1474,22 @@ mod tests {
}
fn scoped_tile(team_id: i32, cohort_id: i32, run_id: u128, guard: ScopeKind) -> ReconcileTile {
+ bounded_tile(team_id, cohort_id, run_id, guard, SLICE_START)
+ }
+
+ fn bounded_tile(
+ team_id: i32,
+ cohort_id: i32,
+ run_id: u128,
+ guard: ScopeKind,
+ boundary: i64,
+ ) -> ReconcileTile {
ReconcileTile::new(
TeamId(team_id),
CohortId(cohort_id),
ReconcileScope::parse(guard, SHAPE_HASH).unwrap(),
RunId(Uuid::from_u128(run_id)),
+ RunBoundaryMs(boundary),
)
}
@@ -1406,8 +1501,13 @@ mod tests {
tracker.mark_dispatched(3, 11);
{
- let mut queue =
- ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
+ let mut queue = ReconcileQueue::new(
+ 3,
+ backlog.clone(),
+ store_handle(&store),
+ unloaded(),
+ SliceCoverage::Complete,
+ );
queue.enqueue(tile(1, 7, 1), tracker.defer(3, 10));
assert_eq!(queue.len(), 1);
assert_eq!(backlog.len(), 1);
@@ -1431,7 +1531,13 @@ mod tests {
let tracker = OffsetTracker::new();
let backlog = Arc::new(ReconcileBacklog::default());
tracker.mark_dispatched(PARTITION as i32, 12);
- let mut queue = ReconcileQueue::new(PARTITION, backlog, store_handle(&store), unloaded());
+ let mut queue = ReconcileQueue::new(
+ PARTITION,
+ backlog,
+ store_handle(&store),
+ unloaded(),
+ SliceCoverage::Complete,
+ );
queue.enqueue(tile(TEAM, COHORT, 1), tracker.defer(PARTITION as i32, 10));
queue.enqueue(
tile(TEAM, COHORT + 1, 2),
@@ -1496,7 +1602,13 @@ mod tests {
let tracker = OffsetTracker::new();
let backlog = Arc::new(ReconcileBacklog::default());
tracker.mark_dispatched(3, 14);
- let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
+ let mut queue = ReconcileQueue::new(
+ 3,
+ backlog.clone(),
+ store_handle(&store),
+ unloaded(),
+ SliceCoverage::Complete,
+ );
queue.enqueue(tile(1, 7, 1), tracker.defer(3, 10));
queue.enqueue(tile(1, 8, 2), tracker.defer(3, 11));
queue.enqueue(tile(2, 7, 3), tracker.defer(3, 12));
@@ -1526,7 +1638,13 @@ mod tests {
let tracker = OffsetTracker::new();
let backlog = Arc::new(ReconcileBacklog::default());
tracker.mark_dispatched(3, 20);
- let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
+ let mut queue = ReconcileQueue::new(
+ 3,
+ backlog.clone(),
+ store_handle(&store),
+ unloaded(),
+ SliceCoverage::Complete,
+ );
queue.enqueue(
scoped_tile(TEAM, COHORT, 1, ScopeKind::Behavioral),
tracker.defer(3, 10),
@@ -1575,7 +1693,13 @@ mod tests {
let tracker = OffsetTracker::new();
let backlog = Arc::new(ReconcileBacklog::default());
tracker.mark_dispatched(3, 20);
- let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
+ let mut queue = ReconcileQueue::new(
+ 3,
+ backlog.clone(),
+ store_handle(&store),
+ unloaded(),
+ SliceCoverage::Complete,
+ );
queue.enqueue(tile(1, 7, 2), tracker.defer(3, 15));
for replayed_offset in [10, 15] {
@@ -1702,7 +1826,7 @@ mod tests {
fn verdict(
filters: TeamFilters,
tile: &ReconcileTile,
- ) -> Result<CohortEligibility, ReconcileDiscardReason> {
+ ) -> Result<CohortEligibility, CatalogMiss> {
catalog_verdict(Some(&Arc::new(filters)), tile).map(|(_, eligibility)| eligibility)
}
@@ -1712,26 +1836,23 @@ mod tests {
assert_eq!(
catalog_verdict(None, &reconcile).map(|(_, eligibility)| eligibility),
- Err(ReconcileDiscardReason::TeamAbsent),
+ Err(CatalogMiss::TeamAbsent),
);
assert_eq!(
verdict(TeamFilters::default(), &reconcile),
- Err(ReconcileDiscardReason::CohortAbsent),
+ Err(CatalogMiss::CohortAbsent),
);
let behavioral_guard = &[(ScopeKind::Behavioral, SHAPE_HASH)];
assert_eq!(
verdict(guard_filters(None, behavioral_guard), &reconcile),
- Err(ReconcileDiscardReason::CohortAbsent),
+ Err(CatalogMiss::CohortAbsent),
);
let excluded = guard_filters(
Some(CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf)),
behavioral_guard,
);
- assert_eq!(
- verdict(excluded, &reconcile),
- Err(ReconcileDiscardReason::NotEmitting),
- );
+ assert_eq!(verdict(excluded, &reconcile), Err(CatalogMiss::NotEmitting),);
for eligibility in [
CohortEligibility::SingleLeaf(LeafStateKey(BEHAVIORAL_HASH)),
@@ -1764,18 +1885,18 @@ mod tests {
);
assert_eq!(
verdict(guard_filters(emitting, &[(guard, "shape-v2")]), &reconcile),
- Err(ReconcileDiscardReason::HashMismatch),
+ Err(CatalogMiss::HashMismatch),
"{guard} diverged",
);
assert_eq!(
verdict(guard_filters(emitting, &[]), &reconcile),
- Err(ReconcileDiscardReason::HashUnknown),
+ Err(CatalogMiss::HashUnknown),
"{guard} has no persisted hash",
);
// The catalog carries only the *other* kind's hash, at the very value the tile pins.
assert_eq!(
verdict(guard_filters(emitting, &[(other, SHAPE_HASH)]), &reconcile),
- Err(ReconcileDiscardReason::HashUnknown),
+ Err(CatalogMiss::HashUnknown),
"{guard} must not be satisfied by the {other} map",
);
}
@@ -1786,7 +1907,7 @@ mod tests {
enum Fate {
Proceed(CohortEligibility),
Retry(ReconcileRetryReason),
- Discard(ReconcileDiscardReason),
+ Withhold(WithheldReason),
}
impl From<ReconcileGuard> for Fate {
@@ -1794,7 +1915,7 @@ mod tests {
match guard {
ReconcileGuard::Proceed { eligibility, .. } => Self::Proceed(eligibility),
ReconcileGuard::Retry(reason) => Self::Retry(reason),
- ReconcileGuard::Discard(reason) => Self::Discard(reason),
+ ReconcileGuard::Withhold(reason) => Self::Withhold(reason),
}
}
}
@@ -1825,40 +1946,88 @@ mod tests {
}
}
+ #[derive(Debug, Clone, Copy)]
+ enum Slice {
+ Complete,
+ BeganAtBoundary,
+ BeganAfterBoundary,
+ }
+
+ impl Slice {
+ fn coverage(self) -> SliceCoverage {
+ match self {
+ Self::Complete => SliceCoverage::Complete,
+ Self::BeganAtBoundary | Self::BeganAfterBoundary => {
+ SliceCoverage::Since(CoverageStartMs(SLICE_START))
+ }
+ }
+ }
+
+ fn run_boundary(self) -> i64 {
+ match self {
+ Self::BeganAtBoundary => SLICE_START,
+ Self::Complete | Self::BeganAfterBoundary => SLICE_START - 1,
+ }
+ }
+ }
+
#[test]
- fn a_catalog_miss_discards_only_against_a_refresh_begun_after_admission() {
- let reconcile = tile(TEAM, COHORT, 1);
- let team_absent = ReconcileDiscardReason::TeamAbsent;
+ fn a_catalog_miss_withholds_only_after_a_later_refresh_and_coverage_only_after_the_catalog() {
+ let team_absent = CatalogMiss::TeamAbsent;
+ let partial = WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(SLICE_START),
+ };
let cases = [
// Nothing is published before the first load, so the snapshot kind does not matter.
(
Freshness::NotLoaded,
Snapshot::MissingTeam,
+ Slice::BeganAfterBoundary,
Fate::Retry(ReconcileRetryReason::CatalogNotLoaded),
),
(
Freshness::RefreshedBeforeAdmission,
Snapshot::Emitting,
+ Slice::Complete,
Fate::Proceed(CohortEligibility::Stage2Composable),
),
+ // The catalog wait comes before coverage.
(
Freshness::RefreshedBeforeAdmission,
Snapshot::MissingTeam,
+ Slice::BeganAfterBoundary,
Fate::Retry(ReconcileRetryReason::AwaitingRefresh(team_absent)),
),
(
Freshness::RefreshedAfterAdmission,
Snapshot::Emitting,
+ Slice::Complete,
Fate::Proceed(CohortEligibility::Stage2Composable),
),
+ (
+ Freshness::RefreshedAfterAdmission,
+ Snapshot::Emitting,
+ Slice::BeganAtBoundary,
+ Fate::Proceed(CohortEligibility::Stage2Composable),
+ ),
+ (
+ Freshness::RefreshedAfterAdmission,
+ Snapshot::Emitting,
+ Slice::BeganAfterBoundary,
+ Fate::Withhold(partial),
+ ),
+ // The catalog's reason wins over coverage.
(
Freshness::RefreshedAfterAdmission,
Snapshot::MissingTeam,
- Fate::Discard(team_absent),
+ Slice::BeganAfterBoundary,
+ Fate::Withhold(WithheldReason::Catalog(team_absent)),
),
];
- for (freshness, snapshot, expected) in cases {
+ for (freshness, snapshot, slice, expected) in cases {
+ let reconcile =
+ bounded_tile(TEAM, COHORT, 1, ScopeKind::Behavioral, slice.run_boundary());
let catalog = CatalogHandle::new();
let admitted_after = match freshness {
Freshness::NotLoaded => catalog.last_begun(),
@@ -1874,9 +2043,14 @@ mod tests {
};
assert_eq!(
- Fate::from(evaluate_guard(&catalog.view(), admitted_after, &reconcile)),
+ Fate::from(evaluate_guard(
+ &catalog.view(),
+ admitted_after,
+ &reconcile,
+ slice.coverage(),
+ )),
expected,
- "{freshness:?} with {snapshot:?}",
+ "{freshness:?} with {snapshot:?} on a {slice:?} slice",
);
}
}
@@ -1935,16 +2109,22 @@ mod tests {
.publish(team_catalog(cohort_filters(true, Some(refreshed_hash))));
shell.tick().await;
- let markers: Vec<RunId> = shell
- .markers
- .markers()
- .iter()
- .map(|marker| marker.run_id())
- .collect();
+ let markers = shell.markers.markers();
+ assert_eq!(markers.len(), 1, "{refreshed_hash}");
+ assert_eq!(markers[0].run_id(), RunId(Uuid::from_u128(1)));
if completes {
- assert_eq!(markers, vec![RunId(Uuid::from_u128(1))]);
+ assert!(matches!(markers[0], ReconcileMarker::Complete(_)));
} else {
- assert!(markers.is_empty(), "a superseded run still fails closed");
+ // A superseded run fails closed with a withheld marker.
+ assert!(
+ matches!(
+ &markers[0],
+ ReconcileMarker::Withheld(withheld)
+ if withheld.reason()
+ == WithheldReason::Catalog(CatalogMiss::HashMismatch)
+ ),
+ "{markers:?}",
+ );
assert_eq!(
counted(
&metrics,
@@ -2040,7 +2220,7 @@ mod tests {
.markers
.markers()
.iter()
- .map(ReconcileCompleteMarker::run_id)
+ .map(ReconcileMarker::run_id)
.collect::<Vec<_>>(),
vec![RunId(Uuid::from_u128(31)), RunId(Uuid::from_u128(32))],
);
@@ -2250,25 +2430,135 @@ mod tests {
}
#[tokio::test]
- async fn discard_continues_to_a_zero_row_job_and_emits_only_its_marker() {
+ async fn a_partial_slice_withholds_without_rows_and_the_next_run_still_completes() {
let sink = CaptureSink::new();
let mut shell =
DrainShell::new(false, Arc::new(sink.clone()), CaptureCascadeSink::new(), 8);
- shell.enqueue(tile(999, COHORT, 1), 5);
- shell.enqueue(tile(TEAM, COHORT, 2), 6);
- shell
- .catalog
- .publish(team_catalog(cohort_filters(false, Some(SHAPE_HASH))));
+ shell.cover(SliceCoverage::Since(CoverageStartMs(SLICE_START)));
+ shell.fail_first_marker();
+ shell.write_current(Uuid::from_u128(1), true, true, true);
+ let before_slice =
+ |run_id| bounded_tile(TEAM, COHORT, run_id, ScopeKind::Behavioral, SLICE_START - 1);
+ shell.enqueue(before_slice(1), 5);
+ shell.enqueue(before_slice(3), 6);
+ shell.enqueue(tile(TEAM, COHORT, 2), 7);
+ // Not part of the head's withheld burst.
+ shell.enqueue(before_slice(4), 8);
+
+ // The produce fails, so nothing is released or scanned.
+ shell.tick().await;
+ assert!(shell.markers.markers().is_empty());
+ assert!(sink.changes().is_empty());
+ assert_eq!(shell.queue.front_run_id(), Some(RunId(Uuid::from_u128(1))));
+ assert_eq!(shell.committable(), Some(5));
+ // One produce for both withheld jobs.
shell.tick().await;
+ assert_eq!(shell.markers.produce_calls(), 2, "one produce per tick");
+ assert_eq!(shell.queue.front_run_id(), Some(RunId(Uuid::from_u128(2))));
+ assert_eq!(shell.committable(), Some(7));
- assert!(sink.changes().is_empty());
+ for _ in 0..8 {
+ if shell.queue.front().is_none() {
+ break;
+ }
+ shell.tick().await;
+ }
+
+ let partial = WithheldReason::PartialCoverage {
+ covered_since: CoverageStartMs(SLICE_START),
+ };
let markers = shell.markers.markers();
- assert_eq!(markers.len(), 1);
- assert_eq!(markers[0].run_id(), RunId(Uuid::from_u128(2)));
- assert!(shell.queue.front().is_none());
+ assert!(
+ matches!(
+ markers.as_slice(),
+ [
+ ReconcileMarker::Withheld(first),
+ ReconcileMarker::Withheld(second),
+ ReconcileMarker::Complete(complete),
+ ReconcileMarker::Withheld(last),
+ ] if first.run_id() == RunId(Uuid::from_u128(1))
+ && second.run_id() == RunId(Uuid::from_u128(3))
+ && complete.run_id() == RunId(Uuid::from_u128(2))
+ && last.run_id() == RunId(Uuid::from_u128(4))
+ && [first, second, last].iter().all(|marker| marker.reason() == partial)
+ ),
+ "{markers:?}",
+ );
+ assert!(
+ sink.changes()
+ .iter()
+ .all(|change| change.run_id == Some(RunId(Uuid::from_u128(2)))),
+ "a slice missing the run's history emits no rows for it",
+ );
+ assert!(!sink.changes().is_empty());
assert!(shell.deps.reconcile.backlog.is_empty());
- assert_eq!(shell.committable(), Some(7));
+ assert_eq!(shell.committable(), Some(9));
+ }
+
+ #[tokio::test]
+ async fn a_withheld_burst_produces_at_most_one_scan_page_per_tick() {
+ let mut shell = DrainShell::new(
+ false,
+ Arc::new(CaptureSink::new()),
+ CaptureCascadeSink::new(),
+ 2,
+ );
+ shell.cover(SliceCoverage::Since(CoverageStartMs(SLICE_START)));
+ let before_slice =
+ |run_id| bounded_tile(TEAM, COHORT, run_id, ScopeKind::Behavioral, SLICE_START - 1);
+ for run_id in 1..=3 {
+ shell.enqueue(before_slice(run_id), 4 + run_id as i64);
+ }
+
+ shell.tick().await;
+
+ assert_eq!(shell.markers.markers().len(), 2);
+ assert_eq!(shell.queue.front_run_id(), Some(RunId(Uuid::from_u128(3))));
+ }
+
+ /// Fails the first marker of its first produce and acks the rest.
+ #[derive(Default)]
+ struct FailHeadOnce(CaptureReconcileMarkerSink, AtomicBool);
+
+ #[async_trait]
+ impl ReconcileMarkerSink for FailHeadOnce {
+ async fn produce(
+ &self,
+ markers: Vec<ReconcileMarker>,
+ ) -> Vec<Result<(), KafkaProduceError>> {
+ if self.1.swap(true, Ordering::SeqCst) {
+ return self.0.produce(markers).await;
+ }
+ let mut acks = vec![Err(KafkaProduceError::KafkaProduceCanceled)];
+ acks.extend(self.0.produce(markers[1..].to_vec()).await);
+ acks
+ }
+ }
+
+ #[tokio::test]
+ async fn a_later_ack_never_releases_an_unacked_withheld_head() {
+ let mut shell = DrainShell::new(
+ false,
+ Arc::new(CaptureSink::new()),
+ CaptureCascadeSink::new(),
+ 8,
+ );
+ shell.cover(SliceCoverage::Since(CoverageStartMs(SLICE_START)));
+ shell.deps.reconcile.marker_sink = Arc::new(FailHeadOnce::default());
+ let before_slice =
+ |run_id| bounded_tile(TEAM, COHORT, run_id, ScopeKind::Behavioral, SLICE_START - 1);
+ shell.enqueue(before_slice(1), 5);
+ shell.enqueue(before_slice(2), 6);
+
+ shell.tick().await;
+
+ assert_eq!(shell.queue.front_run_id(), Some(RunId(Uuid::from_u128(1))));
+ assert_eq!(
+ shell.committable(),
+ Some(5),
+ "a later ack must not release an unacked head"
+ );
}
#[tokio::test]
diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rs
index b03093523a1b..44d9837a09fe 100644
--- a/rust/cohort-stream-processor/src/workers/seed_path.rs
+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs
@@ -820,8 +820,8 @@ mod tests {
use tempfile::TempDir;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, ReconcileTile, SChunkMs,
- SeedTile,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, ReconcileTile,
+ RunBoundaryMs, SChunkMs, SeedTile,
};
use crate::consumers::seeds::{SeedSkipReason, SeedWork};
@@ -837,7 +837,8 @@ mod tests {
use crate::stage1::state::AppliedOffsets;
use crate::stage2::state::Stage2State;
use crate::store::{
- CohortStore, OffloadConfig, OffloadMode, Stage2Key, StoreConfig, StoreHandle, TombstoneKey,
+ CohortStore, OffloadConfig, OffloadMode, SliceCoverage, Stage2Key, StoreConfig,
+ StoreHandle, TombstoneKey,
};
use crate::sweep::EvictionQueue;
use crate::workers::event_path::{process_event_gated, EventNameGating};
@@ -1747,6 +1748,7 @@ mod tests {
CohortId(cohort_id),
ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::from_u128(run_id)),
+ RunBoundaryMs(0),
)
}
@@ -1858,6 +1860,7 @@ mod tests {
deps.reconcile.backlog.clone(),
handle.clone(),
catalog.clone(),
+ SliceCoverage::Complete,
);
Self {
_dir,
@@ -1933,6 +1936,7 @@ mod tests {
self.deps.reconcile.backlog.clone(),
self.handle.clone(),
self.catalog.clone(),
+ SliceCoverage::Complete,
);
}
diff --git a/rust/cohort-stream-processor/src/workers/seed_run.rs b/rust/cohort-stream-processor/src/workers/seed_run.rs
index 4f35274a8745..3a357294c31c 100644
--- a/rust/cohort-stream-processor/src/workers/seed_run.rs
+++ b/rust/cohort-stream-processor/src/workers/seed_run.rs
@@ -364,8 +364,8 @@ mod tests {
use std::num::NonZeroU32;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, RunId, SChunkMs,
- ScannedAtMs,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, RunBoundaryMs, RunId,
+ SChunkMs, ScannedAtMs,
};
use serde_json::{json, Value};
use uuid::Uuid;
@@ -435,6 +435,7 @@ mod tests {
CohortId(1),
ReconcileScope::Behavioral(BehavioralShapeHash::parse(BEHAVIORAL).unwrap()),
RunId(Uuid::nil()),
+ RunBoundaryMs(0),
)
}
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index 13b5b4396f71..0deb7eae4c8a 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -18,7 +18,8 @@ use std::collections::VecDeque;
use std::sync::Arc;
use std::time::{Duration, Instant};
-use metrics::{counter, histogram};
+use cohort_core::seed::CoverageStartMs;
+use metrics::{counter, gauge, histogram};
use tokio::task::JoinHandle;
use tracing::{info, warn};
use uuid::Uuid;
@@ -35,8 +36,9 @@ use crate::observability::metrics::{
CASCADE_PRODUCE_ERRORS_TOTAL, COHORT_STREAM_OFFSET_AHEAD_OF_DISPATCH,
EVICTION_QUEUE_REBUILT_KEYS_TOTAL, MERGE_REDIRECT_HOP_CAPPED_TOTAL,
MERGE_REKEY_PRODUCE_FAILURE_TOTAL, OUTPUT_MEMBERSHIP_CHANGES_EMITTED, OUTPUT_PRODUCE_ERRORS,
- STAGE1_EVENTS_PROCESSED, STAGE1_EVENTS_SKIPPED, STAGE1_EVENT_PROCESS_DURATION,
- STAGE1_STATE_DECODE_ERROR, STAGE1_TRANSITIONS,
+ SLICES_BEGUN_TOTAL, SLICE_COVERED_SINCE_SECONDS, STAGE1_EVENTS_PROCESSED,
+ STAGE1_EVENTS_SKIPPED, STAGE1_EVENT_PROCESS_DURATION, STAGE1_STATE_DECODE_ERROR,
+ STAGE1_TRANSITIONS,
};
use crate::partitions::offset_tracker::{MarkOutcome, OffsetTracker};
use crate::partitions::router::WorkerInbox;
@@ -48,7 +50,7 @@ use crate::producer::{
use crate::stage1::key::LeafStateKey;
use crate::stage1::state::{StateVariant, StatefulRecord};
use crate::stage1::transition::{LeafTransition, TransitionKind};
-use crate::store::{BehavioralKey, ReadLane, StoreHandle};
+use crate::store::{BehavioralKey, ReadLane, SliceCoverage, SliceTenure, StoreHandle};
use crate::sweep::EvictionQueue;
use crate::workers::cascade_path::handle_cascade;
use crate::workers::event_path::{
@@ -106,6 +108,7 @@ impl Stage1Worker {
merge,
restore,
EventNameGating::Disabled,
+ CoverageStartMs::now(),
)
}
@@ -120,6 +123,7 @@ impl Stage1Worker {
merge: Arc<MergeWorkerDeps>,
restore: EvictionRestore,
event_name_gating: EventNameGating,
+ assigned_at: CoverageStartMs,
) -> Self {
let handle = tokio::spawn(run_worker(
partition_id,
@@ -131,6 +135,7 @@ impl Stage1Worker {
merge,
restore,
event_name_gating,
+ assigned_at,
));
Self {
partition_id,
@@ -178,16 +183,20 @@ async fn run_worker(
merge: Arc<MergeWorkerDeps>,
restore: EvictionRestore,
event_name_gating: EventNameGating,
+ assigned_at: CoverageStartMs,
) {
info!(partition_id, "stage 1 worker started");
let mut queue = EvictionQueue::<BehavioralKey>::new();
let mut sweep = SweepSchedule::new(partition_id);
+ // Before any message, so the slice holds every event from the assignment on.
+ let coverage = resolve_slice_coverage(partition_id, assigned_at, &handle).await;
let mut reconcile_queue = ReconcileQueue::new(
partition_id,
merge.reconcile.backlog.clone(),
handle.clone(),
catalog.clone(),
+ coverage,
);
// No-op for a cold partition (bloom-filtered scan finds nothing to schedule). A failed scan logs
// and stops early, so the guard drops and the readiness gate cannot stick on a store error.
@@ -929,6 +938,45 @@ fn rewrite_to(event: &CohortStreamEvent, final_person: Uuid, origin: Uuid) -> Co
}
}
+/// The worker's slice coverage, beginning the slice at its assignment when it has no record.
+async fn resolve_slice_coverage(
+ partition_id: u16,
+ assigned_at: CoverageStartMs,
+ handle: &StoreHandle,
+) -> SliceCoverage {
+ let coverage = match handle
+ .resume_or_begin_slice(partition_id, assigned_at)
+ .await
+ {
+ Ok(SliceTenure::Resumed(coverage)) => coverage,
+ Ok(SliceTenure::Begun(since)) => {
+ counter!(SLICES_BEGUN_TOTAL).increment(1);
+ info!(
+ partition_id,
+ covered_since_ms = since.0,
+ "slice begins without earlier history; runs with an earlier boundary will be withheld",
+ );
+ SliceCoverage::Since(since)
+ }
+ Err(err) => {
+ // Fails closed: this worker certifies less, never more.
+ warn!(
+ partition_id,
+ error = %err,
+ "slice coverage unreadable; withholding runs with an earlier boundary",
+ );
+ SliceCoverage::Since(CoverageStartMs::now())
+ }
+ };
+ let covered_since_seconds = match coverage {
+ SliceCoverage::Complete => 0.0,
+ SliceCoverage::Since(since) => since.0 as f64 / 1000.0,
+ };
+ let partition: Arc<str> = Arc::from(partition_id.to_string());
+ gauge!(SLICE_COVERED_SINCE_SECONDS, "partition" => partition).set(covered_since_seconds);
+ coverage
+}
+
/// Re-seed the per-worker [`EvictionQueue`] from `cf_behavioral`, scheduling every behavioral key on
/// its stored deadline. Skips `PersonProperty` variants (no time-based eviction) and `i64::MAX`
/// deadlines (permanent). Corrupt records are counted and skipped — the event path re-derives them. A
@@ -1030,7 +1078,9 @@ mod tombstone_redirect_tests {
use tempfile::TempDir;
use tokio::sync::mpsc;
- use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
+ use cohort_core::seed::{
+ BehavioralShapeHash, ReconcileScope, ReconcileTile, RunBoundaryMs, RunId,
+ };
use crate::consumers::seeds::SeedWork;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder};
@@ -1038,7 +1088,7 @@ mod tombstone_redirect_tests {
use crate::partitions::partitioner::{partition_of, COHORT_PARTITION_COUNT};
use crate::producer::{
CaptureCascadeSink, CaptureReconcileMarkerSink, CaptureSink, CaptureStreamEventSink,
- CaptureTransferSink,
+ CaptureTransferSink, ReconcileMarker,
};
use crate::stage1::person_record::PersonRecord;
use crate::stage1::state::AppliedOffsets;
@@ -1288,6 +1338,7 @@ mod tombstone_redirect_tests {
CohortId(1),
ReconcileScope::Behavioral(BehavioralShapeHash::parse("0123456789abcdef").unwrap()),
RunId(Uuid::from_u128(1)),
+ RunBoundaryMs(0),
);
// Bypass EventDispatcher's post-send seed ceiling accounting. The worker must establish the
@@ -1323,6 +1374,8 @@ mod tombstone_redirect_tests {
CohortId(1),
ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
RunId(Uuid::from_u128(7)),
+ // After the slice begins, so the run certifies.
+ RunBoundaryMs(chrono::Utc::now().timestamp_millis() + 86_400_000),
);
// The drain tick must arrive after the tile is admitted, so the two lanes are driven by
@@ -1362,6 +1415,10 @@ mod tombstone_redirect_tests {
assert!(membership.changes().is_empty());
let markers = marker_sink.markers();
assert_eq!(markers.len(), 1);
+ assert!(
+ matches!(markers[0], ReconcileMarker::Complete(_)),
+ "{markers:?}"
+ );
assert_eq!(markers[0].partition(), 0);
assert_eq!(markers[0].run_id(), RunId(Uuid::from_u128(7)));
assert_eq!(seed_tracker.committable_offsets().get(&0), Some(&6));
diff --git a/rust/cohort-stream-processor/tests/seed_consumer.rs b/rust/cohort-stream-processor/tests/seed_consumer.rs
index ce23a4e0f79b..05a2d5ad2b7d 100644
--- a/rust/cohort-stream-processor/tests/seed_consumer.rs
+++ b/rust/cohort-stream-processor/tests/seed_consumer.rs
@@ -23,8 +23,8 @@ use std::time::{Duration, Instant};
use async_trait::async_trait;
use chrono_tz::UTC;
use cohort_core::seed::{
- BehavioralShapeHash, ClaimEpoch, ConditionHash, ReconcileScope, ReconcileTile, RunId, SChunkMs,
- SeedTile,
+ BehavioralShapeHash, ClaimEpoch, ConditionHash, CoverageStartMs, ReconcileMarker,
+ ReconcileScope, ReconcileTile, RunBoundaryMs, RunId, SChunkMs, SeedTile, WithheldReason,
};
use cohort_stream_processor::consumers::{
CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, MergeRoute,
@@ -42,8 +42,8 @@ use cohort_stream_processor::partitions::{
use cohort_stream_processor::producer::{
CascadeSink, ChangeOrigin, CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink,
KafkaReconcileMarkerSink, KafkaSeedTileSink, KafkaStreamEventSink, KafkaTransferSink,
- MembershipSink, MembershipStatus, ReconcileCompleteMarker, ReconcileMarkerSink, SeedTileSink,
- StreamEventSink, TransferSink,
+ MembershipSink, MembershipStatus, ReconcileMarkerSink, SeedTileSink, StreamEventSink,
+ TransferSink,
};
use cohort_stream_processor::stage1::bucket_tz::day_idx_in_tz;
use cohort_stream_processor::stage2::state::Stage2State;
@@ -282,13 +282,13 @@ async fn consume_all(topic: &str, expected: usize, deadline: Duration) -> Vec<(i
fn split_records(
records: Vec<(i32, Vec<u8>)>,
-) -> (Vec<CohortMembershipChange>, Vec<ReconcileCompleteMarker>) {
+) -> (Vec<CohortMembershipChange>, Vec<ReconcileMarker>) {
let mut changes = Vec::new();
let mut markers = Vec::new();
for (_, payload) in records {
let value: serde_json::Value = serde_json::from_slice(&payload).unwrap();
- if value.get("type").and_then(serde_json::Value::as_str) == Some("reconcile_complete") {
- markers.push(serde_json::from_slice::<ReconcileCompleteMarker>(&payload).unwrap());
+ if value.get("type").is_some() {
+ markers.push(serde_json::from_slice::<ReconcileMarker>(&payload).unwrap());
} else {
changes.push(serde_json::from_slice::<CohortMembershipChange>(&payload).unwrap());
}
@@ -315,14 +315,19 @@ async fn drain_membership_only(topic: &str, expected: usize) -> Vec<CohortMember
changes
}
-/// Drain `expected` completion markers off the dedicated marker topic.
-async fn drain_markers(topic: &str, expected: usize) -> Vec<ReconcileCompleteMarker> {
+/// Drain `expected` reconcile markers off the dedicated marker topic.
+async fn drain_markers(topic: &str, expected: usize) -> Vec<ReconcileMarker> {
let (changes, markers) =
split_records(consume_all(topic, expected, Duration::from_secs(30)).await);
assert!(changes.is_empty(), "the marker topic carries markers only");
markers
}
+/// A day ahead, so it follows the start of every slice in a store these tests create.
+fn boundary_after_slices_began() -> RunBoundaryMs {
+ RunBoundaryMs(chrono::Utc::now().timestamp_millis() + 86_400_000)
+}
+
async fn wait_for(what: &str, deadline: Duration, mut condition: impl FnMut() -> bool) {
let start = Instant::now();
while !condition() {
@@ -1159,6 +1164,7 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
let _monitor = manager.monitor_background();
let dir = TempDir::new().unwrap();
+ let before_store = chrono::Utc::now().timestamp_millis();
let instance = spawn_instance(
&topics,
&groups,
@@ -1203,6 +1209,7 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
CohortId(COHORT),
ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
run_id,
+ boundary_after_slices_began(),
);
let producer = murmur2_producer();
@@ -1303,6 +1310,7 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
let marker_partitions: HashSet<u16> = snapshot_markers
.iter()
.map(|marker| {
+ assert!(matches!(marker, ReconcileMarker::Complete(_)), "{marker:?}");
assert_eq!(marker.team_id(), TeamId(TEAM));
assert_eq!(marker.cohort_id(), CohortId(COHORT));
assert_eq!(marker.run_id(), run_id);
@@ -1372,6 +1380,7 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
let converged_markers = drain_markers(&topics.markers, NUM_PARTITIONS as usize * 2).await;
let mut marker_counts = HashMap::<u16, usize>::new();
for marker in &converged_markers {
+ assert!(matches!(marker, ReconcileMarker::Complete(_)), "{marker:?}");
assert_eq!(marker.team_id(), TeamId(TEAM));
assert_eq!(marker.cohort_id(), CohortId(COHORT));
assert_eq!(marker.run_id(), run_id);
@@ -1390,6 +1399,71 @@ async fn reconcile_snapshot_repairs_stale_state_and_commits_after_markers() {
&& change.run_id == Some(run_id)
}));
+ // A boundary before the store withholds every partition.
+ let early_run = RunId(Uuid::from_u128(0xB5));
+ let early = ReconcileTile::new(
+ TeamId(TEAM),
+ CohortId(COHORT),
+ ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
+ early_run,
+ RunBoundaryMs(before_store - 1),
+ );
+ for partition in 0..NUM_PARTITIONS {
+ assert_eq!(
+ produce_reconcile(&producer, &topics.seeds, partition, &early).await,
+ 2,
+ );
+ }
+ wait_for(
+ "the early run's controls to be admitted",
+ Duration::from_secs(30),
+ || instance.reconcile_backlog.len() == i64::from(NUM_PARTITIONS),
+ )
+ .await;
+ instance.dispatcher.route_reconcile_drain().await;
+ wait_for(
+ "one withheld marker per partition",
+ Duration::from_secs(60),
+ || topic_message_count(&topics.markers) == i64::from(NUM_PARTITIONS) * 3,
+ )
+ .await;
+ wait_for(
+ "every seed partition commit to advance past its withheld marker",
+ Duration::from_secs(30),
+ || {
+ let offsets = seed_group_committed_offsets(&groups.seeds, &topics.seeds);
+ (0..NUM_PARTITIONS).all(|partition| offsets.get(&partition) == Some(&3))
+ },
+ )
+ .await;
+ assert_eq!(
+ topic_message_count(&topics.shadow),
+ 2,
+ "a slice missing the run's history emits no rows for it",
+ );
+ let withheld_partitions: HashSet<u16> =
+ drain_markers(&topics.markers, NUM_PARTITIONS as usize * 3)
+ .await
+ .iter()
+ .filter(|marker| marker.run_id() == early_run)
+ .map(|marker| {
+ assert!(
+ matches!(
+ marker,
+ ReconcileMarker::Withheld(withheld)
+ if matches!(
+ withheld.reason(),
+ WithheldReason::PartialCoverage { covered_since }
+ if covered_since >= CoverageStartMs(before_store)
+ )
+ ),
+ "{marker:?}",
+ );
+ marker.partition()
+ })
+ .collect();
+ assert_eq!(withheld_partitions, expected_marker_partitions);
+
shutdown.request_shutdown();
instance.join().await;
})
@@ -1422,6 +1496,7 @@ async fn fence_holds_a_fresh_tile_until_live_consumption_passes_its_scan_point()
CohortId(COHORT),
ReconcileScope::Behavioral(BehavioralShapeHash::parse(FILTERS_HASH).unwrap()),
run_id,
+ boundary_after_slices_began(),
);
assert_eq!(
produce_reconcile(&producer, &topics.seeds, part(alice) as i32, &reconcile,).await,