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): make processor restarts lossless and retry catalog races (#114507)

Matheus Batista9b80d1a2d5ad
diff --git a/.github/workflows/ci-rust.yml b/.github/workflows/ci-rust.yml
index d04c6629f5c1..9efb6d9a5021 100644
--- a/.github/workflows/ci-rust.yml
+++ b/.github/workflows/ci-rust.yml
@@ -157,7 +157,7 @@ jobs:
"cohort-core": 22,
"cohort-event-shuffler": 25,
"cohort-seeder": 77,
- "cohort-stream-processor": 146,
+ "cohort-stream-processor": 285,
"common-alloc": 5,
"common-cache": 6,
"common-compression": 5,
@@ -403,7 +403,9 @@ jobs:
WAIT_FOR_DOCKER_LAUNCH_RETRY_DELAY: 10
run: |
../bin/ci-wait-for-docker launch --down
- ../bin/ci-wait-for-docker wait seaweedfs
+ # objectstorage reports healthy only once its `posthog` bucket and
+ # `object_storage_root_user` identity exist; the cohort processor's S3 tests use both.
+ ../bin/ci-wait-for-docker wait seaweedfs objectstorage
echo "127.0.0.1 db redis7 kafka clickhouse clickhouse-coordinator objectstorage seaweedfs temporal" | sudo tee -a /etc/hosts
@@ -561,6 +563,19 @@ jobs:
USAGE_INGESTION_E2E_LOAD_REQUESTS=2000 \
run_nextest usage-ingestion-ignored -p usage-ingestion --run-ignored only --test-threads=1 || overall_rc=1
fi
+ # cohort-stream-processor's broker and S3 tests are #[ignore]'d. This job runs Kafka
+ # and SeaweedFS (objectstorage, :19000). `kind(test)` selects the tests/ binaries,
+ # whose ignored tests all need this stack. One at a time: each joins its own
+ # consumer group and most create several 64-partition topics.
+ if [ "$pkg" = "cohort-stream-processor" ]; then
+ KAFKA_HOSTS=localhost:9092 \
+ CHECKPOINT_S3_ENDPOINT=http://localhost:19000 \
+ CHECKPOINT_S3_REGION=us-east-1 \
+ CHECKPOINT_S3_BUCKET=posthog \
+ CHECKPOINT_S3_ACCESS_KEY_ID=object_storage_root_user \
+ CHECKPOINT_S3_SECRET_ACCESS_KEY=object_storage_root_password \
+ run_nextest cohort-stream-processor-ignored -p cohort-stream-processor -E 'kind(test)' --run-ignored only --test-threads=1 || overall_rc=1
+ fi
echo "::endgroup::"
done
exit $overall_rc
diff --git a/docker-compose.base.yml b/docker-compose.base.yml
index 684a3ba1fe32..59060a994113 100644
--- a/docker-compose.base.yml
+++ b/docker-compose.base.yml
@@ -229,6 +229,13 @@ services:
- --set redpanda.empty_seed_starts_cluster=false
- --seeds kafka:33145
- --set redpanda.auto_create_topics_enabled=true
+ # Redpanda refuses new partitions past its file descriptor limit divided by
+ # `topic_fds_per_partition` (5). At a 1024 soft limit that is about 200 partitions, fewer
+ # than one cohort-stream-processor integration test creates.
+ ulimits:
+ nofile:
+ soft: 65536
+ hard: 65536
volumes:
- redpanda-data:/var/lib/redpanda/data
environment:
diff --git a/docs/internal/realtime-cohorts/backfill-coordination.md b/docs/internal/realtime-cohorts/backfill-coordination.md
index 86511361d620..75f66da49e55 100644
--- a/docs/internal/realtime-cohorts/backfill-coordination.md
+++ b/docs/internal/realtime-cohorts/backfill-coordination.md
@@ -229,7 +229,8 @@ Other cases to know:
The revert's own save schedules a fresh run.
- **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`, and then discards the cohort's reconcile requests without markers.
+ 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`.
- **A cohort re-enters the realtime set without a leaf change.**
diff --git a/docs/internal/realtime-cohorts/backfill-overview.md b/docs/internal/realtime-cohorts/backfill-overview.md
index 6fbbaeb6466a..7639d9ded006 100644
--- a/docs/internal/realtime-cohorts/backfill-overview.md
+++ b/docs/internal/realtime-cohorts/backfill-overview.md
@@ -197,7 +197,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.
+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.
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 +299,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 is discarded without a marker, and the run ends with a retryable shortfall.
+ 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.
- 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 18d4a0f7389d..0da3cc674bd5 100644
--- a/docs/internal/realtime-cohorts/completion-and-readiness.md
+++ b/docs/internal/realtime-cohorts/completion-and-readiness.md
@@ -101,7 +101,7 @@ 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, or skipped because reconcile is disabled, is committed with no marker.
+ 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.
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 +115,7 @@ 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 discarded or skipped the request, for example because reconcile was disabled on it.
+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.
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/membership-output-and-readers.md b/docs/internal/realtime-cohorts/membership-output-and-readers.md
index da726ce9a929..104a3b2c7923 100644
--- a/docs/internal/realtime-cohorts/membership-output-and-readers.md
+++ b/docs/internal/realtime-cohorts/membership-output-and-readers.md
@@ -156,7 +156,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, and it cannot take back markers it already produced.
+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.
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.
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.md
index e086a2d12c41..15316eef7308 100644
--- a/docs/internal/realtime-cohorts/processor-runtime.md
+++ b/docs/internal/realtime-cohorts/processor-runtime.md
@@ -39,7 +39,7 @@ The eviction sweep, the pending-transfer redrive, merge garbage collection and t
So while a worker runs, it is the only writer of its partition, and nothing needs a lock.
Boot recovery and revoke cleanup are the only code that touches a slice from outside its worker.
Revoke cleanup waits for the worker to exit.
-Boot recovery is meant to finish before any worker starts, but nothing enforces that, as [startup](#startup) explains.
+Boot recovery finishes before any worker starts, as [startup](#startup) explains.
## Consumers and ownership
@@ -53,10 +53,11 @@ Followers never subscribe.
Whenever the events consumer is assigned or revoked a partition, the followers are assigned or unassigned the same partition number, resuming at their group's committed offsets.
One rebalance decides ownership of partition N on every input topic at once, which is what [partition affinity](event-routing.md#partition-affinity) needs.
-The merge, transfer, cascade and seed followers start only after the first catalog load.
-The events consumer does not wait.
+The merge, transfer, cascade and seed followers start only after the first catalog load and the end of boot recovery.
+The events consumer does not wait for the catalog.
Workers spawn lazily, on the first message for an owned partition.
+With durable restore enabled, the end of boot recovery also spawns a worker for every owned partition.
A **tenure** is the time a worker owns a partition, from an assignment to the next revoke or restart.
## From a Kafka batch to a worker
@@ -142,19 +143,19 @@ Hot-path writes do not wait for the disk, so this one flush per commit is what m
Different paths make different promises.
This table is worth knowing before you debug a missing or duplicated membership change.
-| Path | Guarantee | Why |
-| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Events into Stage 1 state | At least once across restarts, applied once, except the batch described in [startup](#startup). Within a tenure, an event whose fold fails on a store error, or whose re-key to a survivor's partition fails, is skipped and later committed past | Offsets commit after the work. A redelivered event is recognized by its replay marks. Only the merge, cascade and seed paths hold a failed offset |
-| Event to membership change | At most once | State commits inside the fold, before the produce. If the produce fails, the next clean sub-batch marks past it, and a replay finds no transition to emit |
-| First-hop cascade messages | At most once from the live, merge and sweep paths. At least once from seed apply and reconcile | The live, merge and sweep paths produce them after the flip is committed. Seed apply and reconcile produce them before writing the flip, and retry on failure |
-| Sweep expiry of a single-leaf cohort | At least once while the worker runs | The sweep produces before it writes, and reschedules the keys on failure. The retry lives in the in-memory queue, so a restart keeps it only with durable restore on |
-| Sweep expiry that recomposes a cohort | At most once | The composed result is written before it is produced |
-| Cascade messages consumed | At least once | Produce before state, and a failure holds the offset |
-| Merge state | At least once, applied once | Drain and apply markers keyed by the original merge message |
-| Merge state transfer | At least once while the partition stays assigned | An outbox row survives until the transfer is acknowledged, and a timer redrives it. A revoke deletes the row with the slice, and later merges may already have committed past its merge offset |
-| Merge membership output | At most once | State commits before the produce, and a failed produce is dropped |
-| Backfill seed runs | At least once | A failure holds the run's first offset, and the seed replays on the next tenure. A redelivered seed re-emits a change that was lost |
-| Reconcile | At least once | A failed page retries on the next tick, and a deferred floor keeps the request uncommitted until the job completes |
+| Path | Guarantee | Why |
+| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Events into Stage 1 state | At least once across restarts, applied once. Within a tenure, an event whose fold fails on a store error, or whose re-key to a survivor's partition fails, is skipped and later committed past | Offsets commit after the work. A redelivered event is recognized by its replay marks. Only the merge, cascade and seed paths hold a failed offset |
+| Event to membership change | At most once | State commits inside the fold, before the produce. If the produce fails, the next clean sub-batch marks past it, and a replay finds no transition to emit |
+| First-hop cascade messages | At most once from the live, merge and sweep paths. At least once from seed apply and reconcile | The live, merge and sweep paths produce them after the flip is committed. Seed apply and reconcile produce them before writing the flip, and retry on failure |
+| Sweep expiry of a single-leaf cohort | At least once while the worker runs | The sweep produces before it writes, and reschedules the keys on failure. The retry lives in the in-memory queue, so a restart keeps it only with durable restore on |
+| Sweep expiry that recomposes a cohort | At most once | The composed result is written before it is produced |
+| Cascade messages consumed | At least once | Produce before state, and a failure holds the offset |
+| Merge state | At least once, applied once | Drain and apply markers keyed by the original merge message |
+| Merge state transfer | At least once while the partition stays assigned | An outbox row survives until the transfer is acknowledged, and a timer redrives it. A revoke deletes the row with the slice, and later merges may already have committed past its merge offset |
+| Merge membership output | At most once | State commits before the produce, and a failed produce is dropped |
+| Backfill seed runs | At least once | A failure holds the run's first offset, and the seed replays on the next tenure. A redelivered seed re-emits a change that was lost |
+| Reconcile | At least once | A failed page retries on the next tick, and a deferred floor keeps the request uncommitted until the job completes |
So live, merge, sweep-recompose and their first-hop cascade output can all lose a membership change, and nothing on those paths puts it back.
The pipeline accepts that and relies on reconcile, run as part of every backfill, to re-emit the full membership of a cohort.
@@ -192,23 +193,45 @@ At boot the processor:
2. loads the catalog once,
3. decides where the store comes from: with durable restore enabled, the live store on disk or a checkpoint, otherwise an empty store,
4. checks the partition counts of the co-partitioned topics against broker metadata,
-5. starts the timer loops, the followers once the catalog has loaded, and the events consumer.
+5. starts the timer loops and the events consumer, and starts the followers once the catalog has loaded and boot recovery has ended.
-By default the store is wiped at boot.
-With durable restore enabled, a restart reopens the same local store instead, and a worker that spawns rebuilds its in-memory eviction queue by scanning its slice of behavioral state.
+By default the store is wiped at boot, so there is nothing to recover, and the events consumer dispatches from its first poll.
+
+With durable restore enabled, a restart reopens the same local store instead, and the events consumer runs boot recovery before it dispatches anything:
+
+1. It polls until two consecutive polls report the same non-empty assignment.
+ It dispatches nothing these polls return, and records the lowest offset it polled on each partition.
+2. It deletes the slices of partitions it does not own, and re-produces every transfer waiting in the merge outbox, clearing each outbox row from outside the worker.
+3. After a checkpoint restore, it lowers each owned partition's resume point to the offset the checkpoint recorded.
+4. It seeks every owned partition back to its resume point, so every event it polled and did not dispatch is fetched again.
+ A failed seek is retried on the next poll, and nothing is dispatched until every seek succeeds.
+ The consumer reports no liveness while a seek fails, so a seek that keeps failing restarts the process.
+5. It spawns a worker for every owned partition.
+ Each worker rebuilds its in-memory eviction queue by scanning its slice of behavioral state, so a dormant member on a partition with no traffic still leaves on time.
+
+The followers start only after these steps, and the timers reach only partitions that have a worker.
+So no worker runs while boot recovery writes to the store.
[State store and durability](state-store-and-durability.md) covers the restore order.
-With durable restore enabled, the events consumer also runs boot recovery once its assignment settles.
-It deletes the slices of partitions it does not own, and re-produces every transfer waiting in the merge outbox, clearing each outbox row from outside the worker.
-The ordering has a gap.
-The events consumer dispatches polls that arrive before its assignment settles, and the followers start after the first catalog load without waiting for boot recovery.
-So a worker can already be running while the boot redrive clears outbox rows on its partition.
-The code does not prevent this, although no failure from it has been reproduced.
+## Readiness
+
+`/_ready` returns 200 only once the catalog has loaded, boot recovery has ended, and no worker is still rebuilding its eviction queue.
+Until then it returns 503, and the body names the reason.
+The startup and liveness probes use `/_health`, so a slow rebuild never restarts the pod.
+A partition that moves in after boot spawns a worker that rebuilds too, and the pod reads not ready until that rebuild ends.
+
+## Shutdown
+
+On shutdown every consumer stops polling at once, and the events consumer lets every worker finish what is already in its lanes.
+When the last worker exits, the events consumer records the partitions it owned at that moment and commits its own offsets.
+
+The merge, transfer, cascade and seed followers wait for that drain before their final commit.
+So follower work that finishes during the drain is committed, not replayed on the next boot.
+They commit only for the partitions recorded at the drain, because closing the events consumer revokes every partition from the live ownership.
+A follower that waits longer than 35 seconds commits for the partitions it owned when shutdown began.
-Boot recovery also loses events.
-The poll on which the assignment settles runs the redrive and then skips dispatching the batch it already pulled, up to a thousand events.
-Without a restore manifest, which covers every reopen of the live store and every cold start, no seek rewinds the partition.
-The next batch moves the offsets past the skipped events, so they are committed without ever reaching Stage 1 state, and reconcile cannot bring them back.
+The events consumer gets 30 seconds to drain and each follower 45 seconds, inside the process's 90-second ceiling.
+Kubernetes kills the pod when its termination grace period ends, so a grace period shorter than that ceiling can cut the drain off, and the uncommitted work replays on the next boot.
## Store access lanes
@@ -274,9 +297,11 @@ Three variations show the edges.
Only the merge, cascade and seed paths hold.
- The events consumer does not wait for the catalog.
If the first catalog load fails, events are consumed, skipped for lack of definitions, and committed.
+ The pod reads not ready meanwhile.
- A revoke does not commit.
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 timer message does not spawn a worker.
- After a restart, a partition's overdue evictions wait until its first message arrives.
+ 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 5bb61618d44f..a80f7d005fb7 100644
--- a/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
+++ b/docs/internal/realtime-cohorts/seed-apply-and-reconcile.md
@@ -161,7 +161,10 @@ A timer sends a drain message down every worker's live lane every couple of seco
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.
- Before the first catalog load, the job waits.
+ 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.
+ 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.
2. **Scanning.**
diff --git a/docs/internal/realtime-cohorts/state-store-and-durability.md b/docs/internal/realtime-cohorts/state-store-and-durability.md
index 09cf290cdd1d..6ed5b45b36b4 100644
--- a/docs/internal/realtime-cohorts/state-store-and-durability.md
+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md
@@ -135,12 +135,15 @@ With durable restore on, the processor also:
- deletes the slices of partitions it no longer owns, once its assignment settles,
- re-produces every transfer still waiting in the merge outbox,
-- rebuilds each partition's in-memory eviction queue from its behavioral rows when that partition's worker spawns,
+- 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.
+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.
+
After a checkpoint restore it also rewinds the consumers to the offsets recorded in the checkpoint.
-The events consumer retries its seek until it succeeds.
-It seeks only once its assignment settles, so a poll that arrives earlier is still dispatched, the same startup gap as the boot redrive.
+The events consumer folds this rewind into its boot seek, which it retries until it succeeds, and dispatches nothing before.
The merge, transfer, cascade and seed followers get one attempt each.
A failed attempt only logs a warning, and a checkpoint with no offsets for the topic skips the rewind silently.
Either way the follower resumes at its broker-stored offsets.
diff --git a/docs/internal/realtime-cohorts/time-and-eviction.md b/docs/internal/realtime-cohorts/time-and-eviction.md
index d475469122e2..64650904815e 100644
--- a/docs/internal/realtime-cohorts/time-and-eviction.md
+++ b/docs/internal/realtime-cohorts/time-and-eviction.md
@@ -68,13 +68,15 @@ Rows with no deadline are never queued.
The queue lives only in memory.
With durable restore enabled, a worker rebuilds it from its slice of behavioral state when it spawns, before it handles its first message.
-A worker spawns only when its partition's first message arrives, so after a restart that partition's overdue evictions wait for that message.
+Without durable restore, a worker spawns only when its partition's first message arrives, and there is nothing to evict after a restart because the store starts empty.
+With durable restore, the end of boot recovery spawns a worker for every owned partition, so overdue evictions run from boot.
[Processor runtime](processor-runtime.md) explains worker lifecycle and durable restore.
## The sweep
A timer fires every 30 seconds, after an initial delay at boot.
Each tick sends a sweep request to every running worker with a **cutoff** of `now - safety margin`.
+Ticks send nothing before the first catalog load, because a sweep against the empty catalog would drop every due key (see below).
The margin, 5 minutes by default, absorbs up to that much consumer lag.
A person whose events are still sitting in the input topic should not be evicted just because the processor is behind.
With more lag than the margin, a person can leave and then re-enter when the delayed event arrives.
@@ -111,7 +113,7 @@ Keys that share a deadline sit in the order they were scheduled, so in a midnigh
Between the two passes, Stage 2 composes against half of the person's evictions.
Take `AND[A, NOT B]` with A and B due at the same midnight: if the first pass evicts only B, the cohort emits `entered`, and the second pass then emits `left`.
-A batch drops its keys without rescheduling them when their team is missing from the catalog, including before the first catalog load, and when a key's leaf, row or encoding is gone or bad.
+A batch drops its keys without rescheduling them when their team is missing from the catalog, and when a key's leaf, row or encoding is gone or bad.
Those rows are not scheduled again until the person's next matching event, or a durable-restore rebuild.
### Delivery on the sweep
diff --git a/rust/.config/nextest.toml b/rust/.config/nextest.toml
index 37f60cbe493d..143acd3e2897 100644
--- a/rust/.config/nextest.toml
+++ b/rust/.config/nextest.toml
@@ -44,3 +44,10 @@ path = "junit.xml"
[[profile.ci.overrides]]
filter = 'package(personhog-stateright) and test(epoch_fenced_two_partitions_double_zombie_is_safe)'
threads-required = "num-cpus"
+
+# cohort-stream-processor's integration tests include broker and S3 tests that can hang on a
+# shutdown or a broker wait. Fail any of them at 2 minutes, well past the slowest one, instead of
+# letting them eat the job's timeout.
+[[profile.ci.overrides]]
+filter = 'package(cohort-stream-processor) & kind(test)'
+slow-timeout = { period = "60s", terminate-after = 2 }
diff --git a/rust/cohort-stream-processor/src/consumers/boot.rs b/rust/cohort-stream-processor/src/consumers/boot.rs
new file mode 100644
index 000000000000..a274e5b38bbc
--- /dev/null
+++ b/rust/cohort-stream-processor/src/consumers/boot.rs
@@ -0,0 +1,251 @@
+//! Boot recovery for the events consumer.
+//!
+//! With durable restore, the store reopens with state the broker's committed offsets may not
+//! match. Nothing may fold until the consumer has reclaimed unowned slices, redriven the merge
+//! outbox and sought every owned partition back to the first event it polled and did not fold. A
+//! fold before that would set per-key replay marks above offsets that are fetched again later, so
+//! the second fetch would skip those events as replays.
+
+use std::collections::{BTreeMap, HashSet};
+
+use rdkafka::error::KafkaResult;
+use rdkafka::{Offset, TopicPartitionList};
+
+use crate::consumers::events::ConsumedEvent;
+use crate::store::durability::OffsetManifest;
+
+/// The lowest offset per events partition that boot polled and did not fold. A seek there fetches
+/// every skipped event again. librdkafka discards messages it fetched before a seek, so a held-back
+/// event is delivered once more, not twice.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub(crate) struct ResumePoints(BTreeMap<i32, i64>);
+
+impl ResumePoints {
+ pub(crate) fn hold_back(&mut self, events: &[ConsumedEvent]) {
+ for event in events {
+ self.lower(event.partition, event.offset);
+ }
+ }
+
+ /// Lowers each owned partition's resume point to its manifest offset, so a restored store never
+ /// resumes past its checkpoint.
+ pub(crate) fn rewind_to(
+ &mut self,
+ manifest: &OffsetManifest,
+ topic: &str,
+ owned: &HashSet<i32>,
+ ) {
+ for &partition in owned {
+ if let Some(next_offset) = manifest.offset_for(topic, partition) {
+ self.lower(partition, next_offset);
+ }
+ }
+ }
+
+ /// The seek list for the partitions still owned, or `None` when nothing needs a seek. Fails only
+ /// on a negative offset, which neither a polled message nor a captured manifest carries.
+ pub(crate) fn seek_list(
+ &self,
+ topic: &str,
+ owned: &HashSet<i32>,
+ ) -> KafkaResult<Option<TopicPartitionList>> {
+ let mut tpl = TopicPartitionList::new();
+ for (&partition, &offset) in &self.0 {
+ if owned.contains(&partition) {
+ tpl.add_partition_offset(topic, partition, Offset::Offset(offset))?;
+ }
+ }
+ Ok((tpl.count() > 0).then_some(tpl))
+ }
+
+ fn lower(&mut self, partition: i32, offset: i64) {
+ self.0
+ .entry(partition)
+ .and_modify(|held| *held = (*held).min(offset))
+ .or_insert(offset);
+ }
+}
+
+/// Where the events consumer's boot stands. Nothing folds before [`BootPhase::Live`].
+pub(crate) enum BootPhase {
+ /// Waiting for two consecutive polls to report the same non-empty assignment.
+ Settling {
+ previous: Option<HashSet<i32>>,
+ resume: ResumePoints,
+ manifest: Option<OffsetManifest>,
+ },
+ /// Recovery ran. The owned partitions must seek before anything folds.
+ Rewinding {
+ resume: ResumePoints,
+ },
+ Live,
+}
+
+impl BootPhase {
+ pub(crate) fn settling(manifest: Option<OffsetManifest>) -> Self {
+ Self::Settling {
+ previous: None,
+ resume: ResumePoints::default(),
+ manifest,
+ }
+ }
+}
+
+/// Returns `true` once the same non-empty assignment is seen on two consecutive polls. An empty or
+/// changing assignment is not yet settled; a cooperative-incremental assign re-baselines until stable.
+pub(crate) fn boot_assignment_settled(
+ assignment: &HashSet<i32>,
+ prev: &mut Option<HashSet<i32>>,
+) -> bool {
+ if assignment.is_empty() {
+ return false;
+ }
+ if prev.as_ref() != Some(assignment) {
+ *prev = Some(assignment.clone());
+ return false;
+ }
+ true
+}
+
+#[cfg(test)]
+mod tests {
+ use chrono::Utc;
+
+ use super::*;
+ use crate::consumers::events::CohortStreamEvent;
+
+ const TOPIC: &str = "cohort_stream_events";
+
+ fn polled(partition: i32, offset: i64) -> ConsumedEvent {
+ ConsumedEvent {
+ event: CohortStreamEvent {
+ team_id: 7,
+ person_id: "p".to_string(),
+ distinct_id: "d".to_string(),
+ uuid: "u".to_string(),
+ event: "$pageview".to_string(),
+ timestamp: "2026-05-26 12:34:56.789000".to_string(),
+ properties: None,
+ person_properties: None,
+ elements_chain: None,
+ source_offset: offset,
+ source_partition: 0,
+ redirected_from: None,
+ redirect_hops: 0,
+ },
+ partition,
+ offset,
+ broker_ts_ms: None,
+ }
+ }
+
+ fn sought(seek_list: Option<TopicPartitionList>) -> Option<BTreeMap<i32, i64>> {
+ seek_list.map(|tpl| {
+ tpl.elements_for_topic(TOPIC)
+ .iter()
+ .map(|elem| match elem.offset() {
+ Offset::Offset(offset) => (elem.partition(), offset),
+ other => panic!("boot seeks an absolute offset, got {other:?}"),
+ })
+ .collect()
+ })
+ }
+
+ struct Case {
+ name: &'static str,
+ polls: &'static [&'static [(i32, i64)]],
+ manifest: Option<&'static [(i32, i64)]>,
+ owned: &'static [i32],
+ expected: Option<&'static [(i32, i64)]>,
+ }
+
+ #[test]
+ fn resume_points_seek_every_owned_partition_to_its_first_unfolded_offset() {
+ let cases = [
+ Case {
+ name: "the lowest polled offset per partition wins across polls",
+ polls: &[&[(0, 5), (1, 7)], &[(0, 3), (0, 6), (1, 8)]],
+ manifest: None,
+ owned: &[0, 1],
+ expected: Some(&[(0, 3), (1, 7)]),
+ },
+ Case {
+ name: "a manifest lowers held partitions and adds owned ones boot never polled",
+ polls: &[&[(0, 10), (1, 2)]],
+ manifest: Some(&[(0, 4), (1, 6), (2, 9), (3, 1)]),
+ owned: &[0, 1, 2],
+ expected: Some(&[(0, 4), (1, 2), (2, 9)]),
+ },
+ Case {
+ name: "a partition revoked during boot is not sought",
+ polls: &[&[(0, 3), (1, 7)]],
+ manifest: None,
+ owned: &[1],
+ expected: Some(&[(1, 7)]),
+ },
+ Case {
+ name: "nothing held needs no seek",
+ polls: &[&[]],
+ manifest: None,
+ owned: &[0, 1],
+ expected: None,
+ },
+ Case {
+ name: "only unowned partitions held needs no seek",
+ polls: &[&[(2, 4)]],
+ manifest: Some(&[(3, 1)]),
+ owned: &[0],
+ expected: None,
+ },
+ ];
+
+ for case in cases {
+ let owned: HashSet<i32> = case.owned.iter().copied().collect();
+ let mut resume = ResumePoints::default();
+ for poll in case.polls {
+ let events: Vec<ConsumedEvent> = poll
+ .iter()
+ .map(|&(partition, offset)| polled(partition, offset))
+ .collect();
+ resume.hold_back(&events);
+ }
+ if let Some(offsets) = case.manifest {
+ let manifest = OffsetManifest {
+ version: crate::store::durability::MANIFEST_VERSION,
+ captured_at: Utc::now(),
+ topics: BTreeMap::from([(
+ TOPIC.to_string(),
+ offsets.iter().copied().collect(),
+ )]),
+ };
+ resume.rewind_to(&manifest, TOPIC, &owned);
+ }
+
+ assert_eq!(
+ sought(resume.seek_list(TOPIC, &owned).unwrap()),
+ case.expected
+ .map(|offsets| offsets.iter().copied().collect()),
+ "{}",
+ case.name,
+ );
+ }
+ }
+
+ #[test]
+ fn boot_assignment_settled_requires_a_stable_non_empty_assignment() {
+ let mut prev: Option<HashSet<i32>> = None;
+
+ assert!(!boot_assignment_settled(&HashSet::new(), &mut prev));
+ assert_eq!(prev, None);
+
+ let first: HashSet<i32> = [0].into_iter().collect();
+ assert!(!boot_assignment_settled(&first, &mut prev));
+ assert_eq!(prev.as_ref(), Some(&first));
+
+ let second: HashSet<i32> = [0, 1].into_iter().collect();
+ assert!(!boot_assignment_settled(&second, &mut prev));
+ assert_eq!(prev.as_ref(), Some(&second));
+
+ assert!(boot_assignment_settled(&second, &mut prev));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index a90911d28e38..f1b805d5a85a 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -24,7 +24,9 @@ use tracing::{debug, info, warn};
pub use cohort_core::events::CohortStreamEvent;
+use crate::consumers::boot::{boot_assignment_settled, BootPhase, ResumePoints};
use crate::consumers::merges::{ConsumedCascade, ConsumedMerge, ConsumedTransfer};
+use crate::consumers::readiness::BootReadiness;
use crate::consumers::seeds::ConsumedSeed;
use crate::filters::manager::CatalogHandle;
use crate::merge::transfer::PendingTransfer;
@@ -53,14 +55,14 @@ use crate::partitions::shuffle_message::ShuffleMessage;
use crate::producer::MembershipSink;
use crate::store::durability::OffsetManifest;
use crate::store::StoreHandle;
-use crate::workers::{EventNameGating, MergeWorkerDeps, Stage1Worker};
+use crate::workers::{EventNameGating, EvictionRestore, MergeWorkerDeps, Stage1Worker};
/// Back-off after a Kafka transport error so a fast-failing `recv()` can't spin a consume loop.
pub(crate) const RECV_ERROR_BACKOFF: Duration = Duration::from_millis(500);
-/// Timeout for the one-shot restore seek of the events topic. A local fetch-position reposition, so a
-/// few seconds is ample; a timeout is a seek failure and retries (never resumes from the broker offset).
-const RESTORE_SEEK_TIMEOUT: Duration = Duration::from_secs(10);
+/// Timeout for the boot seek of the events topic. A local fetch-position reposition, so a few
+/// seconds is ample; a timeout is a seek failure and retries (never resumes from the broker offset).
+const BOOT_SEEK_TIMEOUT: Duration = Duration::from_secs(10);
/// Page size for the eager boot redrive's paginated scan of `cf_pending_transfers`. The outbox only
/// ever holds transfers stranded by inline-retry exhaustion (rare), so this large page drains a
@@ -82,6 +84,23 @@ pub struct ConsumedEvent {
pub broker_ts_ms: Option<i64>,
}
+/// The partitions this pod owned when its workers finished draining. Closing the events consumer
+/// revokes them from the live set, so followers commit against this snapshot instead. Only
+/// [`EventDispatcher::shutdown`] builds one.
+#[derive(Debug, Clone)]
+pub(crate) struct DrainedOwnership(HashSet<i32>);
+
+impl DrainedOwnership {
+ pub(crate) fn partitions(&self) -> &HashSet<i32> {
+ &self.0
+ }
+}
+
+pub(crate) enum DrainWait {
+ Drained(DrainedOwnership),
+ TimedOut,
+}
+
/// A partition entry remains present while its old worker drains. That sentinel serializes worker
/// replacement with tracker-tenure reset during a rapid revoke/reassign.
enum WorkerSlot {
@@ -113,6 +132,10 @@ pub struct EventDispatcher {
boot_assignment: OnceLock<HashSet<i32>>,
/// Event-name fan-out gating for spawned workers, set once at startup. Unset → disabled.
event_name_gating: OnceLock<EventNameGating>,
+ /// `/_ready`'s gate. Every rebuilding worker this dispatcher spawns holds it closed.
+ readiness: Arc<BootReadiness>,
+ /// Set once the shutdown drain ends, for the followers' final commits.
+ drained: tokio::sync::SetOnce<DrainedOwnership>,
}
impl EventDispatcher {
@@ -130,6 +153,7 @@ impl EventDispatcher {
workers: Arc::new(DashMap::new()),
owned: Arc::new(DashSet::new()),
handle,
+ readiness: BootReadiness::new(catalog.clone()),
catalog,
sink,
merge,
@@ -137,9 +161,14 @@ impl EventDispatcher {
durable_restore: AtomicBool::new(false),
boot_assignment: OnceLock::new(),
event_name_gating: OnceLock::new(),
+ drained: tokio::sync::SetOnce::new(),
}
}
+ pub fn readiness(&self) -> &Arc<BootReadiness> {
+ &self.readiness
+ }
+
/// Enable crash-restart durability. Must be called before any worker spawns.
pub fn enable_durable_restore(&self) {
self.durable_restore.store(true, Ordering::SeqCst);
@@ -505,6 +534,11 @@ impl EventDispatcher {
}
match self.router.add_partition(partition) {
Some(inbox) => {
+ let restore = if self.durable_restore_enabled() {
+ EvictionRestore::Rebuild(self.readiness.rebuild_started())
+ } else {
+ EvictionRestore::Skip
+ };
let worker = Stage1Worker::spawn_with_gating(
partition as u16,
inbox,
@@ -513,7 +547,7 @@ impl EventDispatcher {
self.sink.clone(),
self.tracker.clone(),
self.merge.clone(),
- self.durable_restore_enabled(),
+ restore,
self.event_name_gating(),
);
slot.insert(WorkerSlot::Running(worker));
@@ -542,6 +576,18 @@ impl EventDispatcher {
self.owned.contains(&partition)
}
+ /// End boot and open the readiness gate. Every owned partition gets its worker first, so the
+ /// gate already counts their eviction rebuilds when it opens, and an idle partition rebuilds
+ /// and sweeps from boot instead of from its first message. Returns the owned partition count.
+ pub(crate) fn finish_boot(&self) -> usize {
+ let owned = self.owned_set();
+ for &partition in &owned {
+ self.ensure_worker(partition);
+ }
+ self.readiness.mark_live();
+ owned.len()
+ }
+
/// Snapshot of the partitions currently owned by this consumer.
pub fn owned_partitions(&self) -> Vec<i32> {
self.owned.iter().map(|entry| *entry).collect()
@@ -554,7 +600,14 @@ impl EventDispatcher {
/// Route a sweep tick to each owned partition that has a live worker. Never spawns, so a revoked
/// partition is not resurrected; a worker-less owned partition has no in-memory state to evict, so
/// it is skipped rather than producing a `no_worker` drop.
+ ///
+ /// Routes nothing before the first catalog load. Every team is absent from the unloaded catalog,
+ /// and a sweep batch drops the keys it claims for an absent team without rescheduling them, so a
+ /// sweep then would lose every deadline the boot rebuild restored.
pub async fn route_sweep(&self, due_before_ms: i64) {
+ if !self.catalog.is_loaded() {
+ return;
+ }
self.route_to_owned(|| ShuffleMessage::Sweep { due_before_ms })
.await;
}
@@ -931,20 +984,45 @@ impl EventDispatcher {
.collect()
}
- /// Drain all workers and return the tracker for the caller's final sync commit.
+ /// Drain all workers, publish the ownership they drained under for the followers' final
+ /// commits, and return the tracker for the caller's final sync commit. No consumer polls during
+ /// the drain, so no rebalance callback can change `owned` while it runs.
async fn shutdown(&self) -> Arc<OffsetTracker> {
self.draining.store(true, Ordering::SeqCst);
self.router.clear();
+ let started = Instant::now();
let partitions: Vec<i32> = self.workers.iter().map(|entry| *entry.key()).collect();
+ let mut workers = 0usize;
for partition in partitions {
if let Some((_, WorkerSlot::Running(worker))) = self.workers.remove(&partition) {
+ workers += 1;
if let Err(err) = worker.join().await {
warn!(partition, error = %err, "stage 1 worker panicked during shutdown drain");
}
}
}
+ info!(
+ workers,
+ elapsed_ms = started.elapsed().as_millis() as u64,
+ "worker drain complete"
+ );
+ if self
+ .drained
+ .set(DrainedOwnership(self.owned_set()))
+ .is_err()
+ {
+ debug!("worker drain already published; keeping the first");
+ }
self.tracker.clone()
}
+
+ /// Wait up to `budget` for [`Self::shutdown`] to finish draining the workers.
+ pub(crate) async fn wait_for_worker_drain(&self, budget: Duration) -> DrainWait {
+ match tokio::time::timeout(budget, self.drained.wait()).await {
+ Ok(drained) => DrainWait::Drained(drained.clone()),
+ Err(_) => DrainWait::TimedOut,
+ }
+ }
}
#[derive(Debug, Default)]
@@ -957,19 +1035,6 @@ fn partition_to_store_id(partition: i32) -> Option<u16> {
u16::try_from(partition).ok()
}
-/// Returns `true` once the same non-empty assignment is seen on two consecutive polls. An empty or
-/// changing assignment is not yet settled; a cooperative-incremental assign re-baselines until stable.
-fn boot_assignment_settled(assignment: &HashSet<i32>, prev: &mut Option<HashSet<i32>>) -> bool {
- if assignment.is_empty() {
- return false;
- }
- if prev.as_ref() != Some(assignment) {
- *prev = Some(assignment.clone());
- return false;
- }
- true
-}
-
/// The `cohort_stream_events` group consumer: consume, route, commit.
///
/// Uses a raw `StreamConsumer` with manual commit because the per-partition `OffsetTracker`
@@ -990,8 +1055,8 @@ pub struct CohortStreamEventsConsumer {
events_partitions: usize,
#[allow(dead_code)]
consumer_command_rx: ConsumerCommandReceiver,
- /// Offset manifest from a disaster restore. When set, the consume loop runs a one-shot seek of
- /// the events topic to the manifest positions once the boot assignment settles.
+ /// Offset manifest from a disaster restore. When set, boot also rewinds every owned partition
+ /// the manifest names to its manifest position.
restore_manifest: Option<OffsetManifest>,
}
@@ -1030,8 +1095,9 @@ impl CohortStreamEventsConsumer {
///
/// Offset commit runs on its own interval task so a CPU-saturated consume loop or worker backlog
/// can't block offset advancement; it shares the shutdown signal and is awaited before the final
- /// synchronous commit. Liveness is reported inline from the non-blocking backpressure cycle.
- pub async fn process(self) {
+ /// synchronous commit. Liveness is reported after every poll without a transport error, except
+ /// while boot is still rewinding.
+ pub async fn process(mut self) {
let _guard = self.handle.process_scope();
info!(topic = %self.topic, "cohort_stream_events consume loop starting");
@@ -1049,12 +1115,17 @@ impl CohortStreamEventsConsumer {
let (pause_tx, pause_rx) = tokio::sync::mpsc::unbounded_channel::<HashSet<i32>>();
let pauser_task = tokio::spawn(run_pauser_loop(self.pauser.clone(), pause_rx));
- // One-shot guards; each pre-marked done when its gate is off, keeping the non-durable path unchanged.
- let mut boot_sweep_done = !self.dispatcher.durable_restore_enabled();
- let mut eager_redrive_done = !self.dispatcher.durable_restore_enabled();
- let mut restore_seek_done = self.restore_manifest.is_none();
- let mut prev_assignment: Option<HashSet<i32>> = None;
- // Untouched until boot recovery completes below, so nothing pauses during boot.
+ let boot_started = Instant::now();
+ // `validate_startup` refuses a checkpoint restore without durable restore, so a manifest
+ // always comes with it. Without durable restore the store started empty: nothing to recover.
+ let mut phase = match (
+ self.dispatcher.durable_restore_enabled(),
+ self.restore_manifest.take(),
+ ) {
+ (false, None) => self.go_live(boot_started, 0),
+ (_, manifest) => BootPhase::settling(manifest),
+ };
+ // Untouched until boot recovery completes, so nothing pauses during boot.
let mut backpressure = Backpressure::new();
// Last paused target sent to the pauser task: lets us send only while backpressure is active
// (plus the cycle it clears) and stay silent otherwise.
@@ -1068,36 +1139,46 @@ impl CohortStreamEventsConsumer {
break;
}
outcome = self.consume_batch() => {
- // Sweep before dispatching, so the reclaim never races a worker spawn.
- if !boot_sweep_done {
- boot_sweep_done =
- self.run_boot_staleness_sweep(&mut prev_assignment).await;
- }
- // Redrive after the boot sweep settles. Skip dispatching this batch so boot
- // recovery completes before any fold work.
- if !eager_redrive_done && boot_sweep_done {
- let owned: HashSet<i32> =
- self.dispatcher.owned_partitions().into_iter().collect();
- self.dispatcher
- .eager_redrive_pending_transfers_on_boot(&owned)
- .await;
- eager_redrive_done = true;
- continue;
- }
- // Seek after the boot sweep settles. Skip dispatching the pre-seek batch so no
- // ahead-of-seek event is folded first. Fail-stop: retry without dispatching on
- // failure; never fold from the broker-stored offset.
- if !restore_seek_done && boot_sweep_done {
- restore_seek_done = self.run_restore_seek();
- continue;
+ let transport_error = outcome.transport_error;
+ phase = match phase {
+ BootPhase::Live => {
+ self.dispatch_with_backpressure(
+ outcome,
+ &mut backpressure,
+ &mut prev_paused_target,
+ &pause_tx,
+ );
+ BootPhase::Live
+ }
+ BootPhase::Settling { mut previous, mut resume, manifest } => {
+ resume.hold_back(&outcome.events);
+ let assignment = self.assigned_partitions();
+ if boot_assignment_settled(&assignment, &mut previous) {
+ self.dispatcher
+ .reconcile_boot_assignment(&assignment, self.events_partitions)
+ .await;
+ let owned = self.dispatcher.owned_set();
+ self.dispatcher
+ .eager_redrive_pending_transfers_on_boot(&owned)
+ .await;
+ if let Some(manifest) = &manifest {
+ resume.rewind_to(manifest, &self.topic, &owned);
+ }
+ self.rewind(resume, boot_started)
+ } else {
+ BootPhase::Settling { previous, resume, manifest }
+ }
+ }
+ BootPhase::Rewinding { mut resume } => {
+ resume.hold_back(&outcome.events);
+ self.rewind(resume, boot_started)
+ }
+ };
+ if transport_error {
+ tokio::time::sleep(RECV_ERROR_BACKOFF).await;
+ } else if !matches!(phase, BootPhase::Rewinding { .. }) {
+ self.handle.report_healthy();
}
- self.dispatch_with_backpressure(
- outcome,
- &mut backpressure,
- &mut prev_paused_target,
- &pause_tx,
- )
- .await;
}
}
}
@@ -1126,71 +1207,62 @@ impl CohortStreamEventsConsumer {
info!(topic = %self.topic, "cohort_stream_events consume loop stopped");
}
- /// Returns `true` once the boot snapshot is reconciled, `false` while the assignment is unsettled.
- async fn run_boot_staleness_sweep(&self, prev: &mut Option<HashSet<i32>>) -> bool {
- let assignment = self.assigned_partitions();
- if !boot_assignment_settled(&assignment, prev) {
- return false;
- }
- self.dispatcher
- .reconcile_boot_assignment(&assignment, self.events_partitions)
- .await;
- true
- }
-
- /// Seek the owned events partitions to the manifest's committed offsets. A no-op when
- /// `restore_manifest` is `None`. Returns `true` only once every targeted partition is sought;
- /// `false` on any failure so the caller retries without dispatching. A persistent failure stalls
- /// and surfaces as consumer lag, never silent event loss.
- fn run_restore_seek(&self) -> bool {
- let Some(manifest) = self.restore_manifest.as_ref() else {
- return true;
+ /// Seek every owned partition back to its resume point, then go live. Any failure keeps boot
+ /// in `Rewinding`, so the next poll retries the seek and nothing folds from the broker offset.
+ /// `Rewinding` reports no liveness, so a persistent failure restarts the process.
+ fn rewind(&self, resume: ResumePoints, boot_started: Instant) -> BootPhase {
+ let owned = self.dispatcher.owned_set();
+ let seek_list = match resume.seek_list(&self.topic, &owned) {
+ Ok(seek_list) => seek_list,
+ Err(err) => {
+ warn!(
+ topic = %self.topic,
+ error = %err,
+ "boot seek list rejected an offset; holding off dispatch and retrying",
+ );
+ return BootPhase::Rewinding { resume };
+ }
};
- let owned = self.dispatcher.owned_partitions();
- let Some((tpl, sought)) = restore_seek_tpl(&self.topic, &owned, manifest) else {
- info!(
- topic = %self.topic,
- "restore seek: manifest carried no committed offset for any owned events partition; nothing to seek",
- );
- return true;
+ let Some(seek_list) = seek_list else {
+ return self.go_live(boot_started, 0);
};
+ let sought = seek_list.count();
- let result = match self.consumer.seek_partitions(tpl, RESTORE_SEEK_TIMEOUT) {
- Ok(result) => result,
+ let failed: Vec<i32> = match self.consumer.seek_partitions(seek_list, BOOT_SEEK_TIMEOUT) {
+ Ok(result) => result
+ .elements_for_topic(&self.topic)
+ .iter()
+ .filter(|elem| elem.error().is_err())
+ .map(|elem| elem.partition())
+ .collect(),
Err(err) => {
warn!(
topic = %self.topic,
- offsets = ?sought,
+ partitions = sought,
error = %err,
- "restore seek failed; holding off dispatch and retrying (no progress until it succeeds)",
+ "boot seek failed; holding off dispatch and retrying (no progress until it succeeds)",
);
- return false;
+ return BootPhase::Rewinding { resume };
}
};
-
- let failed: Vec<i32> = result
- .elements_for_topic(&self.topic)
- .iter()
- .filter(|elem| elem.error().is_err())
- .map(|elem| elem.partition())
- .collect();
if !failed.is_empty() {
warn!(
topic = %self.topic,
failed_partitions = ?failed,
- offsets = ?sought,
- "restore seek failed for some partitions; holding off dispatch and retrying (no progress until it succeeds)",
+ "boot seek failed for some partitions; holding off dispatch and retrying (no progress until it succeeds)",
);
- return false;
+ return BootPhase::Rewinding { resume };
}
+ self.go_live(boot_started, sought)
+ }
+ fn go_live(&self, boot_started: Instant, sought: usize) -> BootPhase {
+ let partitions = self.dispatcher.finish_boot();
info!(
- topic = %self.topic,
- partitions = sought.len(),
- offsets = ?sought,
- "restore seek: sought owned events partitions to their committed manifest offsets",
+ elapsed_ms = boot_started.elapsed().as_millis() as u64,
+ partitions, sought, "events consumer boot complete",
);
- true
+ BootPhase::Live
}
fn assigned_partitions(&self) -> HashSet<i32> {
@@ -1201,7 +1273,7 @@ impl CohortStreamEventsConsumer {
.map(|elem| elem.partition())
.collect(),
Err(err) => {
- warn!(error = %err, "failed to read consumer assignment for the boot staleness sweep");
+ warn!(error = %err, "failed to read consumer assignment for boot recovery");
HashSet::new()
}
}
@@ -1209,8 +1281,8 @@ impl CohortStreamEventsConsumer {
/// One steady-state cycle: prune revoked holdover, retry-flush held partitions, dispatch the polled
/// batch, reconcile the paused set and hand its deltas to the pauser task. Every step is
- /// non-blocking, so the heartbeat below fires each iteration regardless of downstream drain.
- async fn dispatch_with_backpressure(
+ /// non-blocking, so the loop's heartbeat fires each iteration regardless of downstream drain.
+ fn dispatch_with_backpressure(
&self,
outcome: ConsumeOutcome,
backpressure: &mut Backpressure,
@@ -1253,12 +1325,6 @@ impl CohortStreamEventsConsumer {
}
gauge!(PARTITIONS_PAUSED).set(backpressure.held_partition_count() as f64);
gauge!(PENDING_HELD_EVENTS).set(backpressure.held_message_count() as f64);
-
- if outcome.transport_error {
- tokio::time::sleep(RECV_ERROR_BACKOFF).await;
- } else {
- self.handle.report_healthy();
- }
}
async fn consume_batch(&self) -> ConsumeOutcome {
@@ -1324,29 +1390,6 @@ struct ConsumeOutcome {
transport_error: bool,
}
-/// Build the seek list for a disaster restore: owned partitions with a committed offset in
-/// `manifest`, at `Offset::Offset(next_offset)` (next-to-consume convention). Returns the TPL and
-/// logged pairs, or `None` when no owned partition has a manifest offset.
-fn restore_seek_tpl(
- topic: &str,
- owned: &[i32],
- manifest: &OffsetManifest,
-) -> Option<(TopicPartitionList, Vec<(i32, i64)>)> {
- let mut tpl = TopicPartitionList::new();
- let mut sought: Vec<(i32, i64)> = Vec::new();
- for &partition in owned {
- let Some(next_offset) = manifest.offset_for(topic, partition) else {
- continue;
- };
- if let Err(err) = tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset)) {
- warn!(topic, partition, next_offset, error = %err, "skipping partition in restore seek list");
- continue;
- }
- sought.push((partition, next_offset));
- }
- (tpl.count() > 0).then_some((tpl, sought))
-}
-
pub(crate) fn build_commit_tpl(topic: &str, offsets: &HashMap<i32, i64>) -> TopicPartitionList {
let mut tpl = TopicPartitionList::new();
for (&partition, &next_offset) in offsets {
@@ -1485,6 +1528,7 @@ mod tests {
use cohort_core::seed::{BehavioralShapeHash, ReconcileScope, ReconcileTile, RunId};
+ use crate::consumers::readiness::NotReady;
use crate::consumers::seeds::SeedWork;
use crate::filters::{CohortId, FilterCatalog, TeamFiltersBuilder, TeamId};
use crate::merge::transfer::{
@@ -1758,59 +1802,6 @@ mod tests {
assert_eq!(tpl.count(), 0);
}
- fn manifest_for(topic: &str, committed: &[(i32, i64)]) -> OffsetManifest {
- let tracker = OffsetTracker::new();
- let owned: Vec<i32> = committed.iter().map(|(p, _)| *p).collect();
- for &(partition, next) in committed {
- tracker.mark_dispatched(partition, next);
- let _ = tracker.mark_processed(partition, next);
- tracker.mark_committed(partition, next);
- }
- OffsetManifest::capture(&owned, &[(topic, &tracker)])
- }
-
- #[test]
- fn restore_seek_tpl_targets_owned_partitions_with_a_manifest_offset() {
- let manifest = manifest_for("cohort_stream_events", &[(0, 100), (3, 250)]);
- let (tpl, sought) = restore_seek_tpl("cohort_stream_events", &[0, 3, 7], &manifest)
- .expect("a non-empty seek");
- assert_eq!(tpl.count(), 2);
- assert_eq!(
- tpl.find_partition("cohort_stream_events", 0)
- .unwrap()
- .offset(),
- Offset::Offset(100),
- );
- assert_eq!(
- tpl.find_partition("cohort_stream_events", 3)
- .unwrap()
- .offset(),
- Offset::Offset(250),
- );
- assert!(tpl.find_partition("cohort_stream_events", 7).is_none());
- let mut sought_sorted = sought;
- sought_sorted.sort_unstable();
- assert_eq!(sought_sorted, vec![(0, 100), (3, 250)]);
- }
-
- #[test]
- fn restore_seek_tpl_is_none_for_an_empty_manifest_topic() {
- let empty = manifest_for("cohort_stream_events", &[]);
- assert!(restore_seek_tpl("cohort_stream_events", &[0, 1, 2], &empty).is_none());
- }
-
- #[test]
- fn restore_seek_tpl_is_none_when_no_owned_partition_matches() {
- let manifest = manifest_for("cohort_stream_events", &[(0, 100), (3, 250)]);
- assert!(restore_seek_tpl("cohort_stream_events", &[5, 9], &manifest).is_none());
- }
-
- #[test]
- fn restore_seek_tpl_is_none_for_a_missing_topic() {
- let manifest = manifest_for("cohort_stream_events", &[(0, 100)]);
- assert!(restore_seek_tpl("person_merge_events", &[0], &manifest).is_none());
- }
-
fn temp_store() -> (TempDir, CohortStore) {
let dir = TempDir::new().unwrap();
let config = StoreConfig {
@@ -2071,24 +2062,6 @@ mod tests {
dispatcher.shutdown().await;
}
- #[test]
- fn boot_assignment_settled_requires_a_stable_non_empty_assignment() {
- let mut prev: Option<HashSet<i32>> = None;
-
- assert!(!boot_assignment_settled(&HashSet::new(), &mut prev));
- assert_eq!(prev, None);
-
- let first: HashSet<i32> = [0].into_iter().collect();
- assert!(!boot_assignment_settled(&first, &mut prev));
- assert_eq!(prev.as_ref(), Some(&first));
-
- let second: HashSet<i32> = [0, 1].into_iter().collect();
- assert!(!boot_assignment_settled(&second, &mut prev));
- assert_eq!(prev.as_ref(), Some(&second));
-
- assert!(boot_assignment_settled(&second, &mut prev));
- }
-
#[tokio::test]
async fn reclaim_unassigned_partitions_on_boot_wipes_only_unassigned_slices() {
let (_dir, store) = temp_store();
@@ -2836,6 +2809,97 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn the_drain_signal_waits_for_every_worker_and_keeps_the_ownership_it_drained_under() {
+ let (_dir, store) = temp_store();
+ let sink = BlockingMembershipSink::new();
+ let dispatcher = Arc::new(EventDispatcher::new(
+ PartitionRouter::new(64),
+ Arc::new(OffsetTracker::new()),
+ test_handle(&store),
+ behavioral_catalog(),
+ sink.clone(),
+ MergeWorkerDeps::capture(),
+ ));
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ dispatcher.dispatch(vec![consumed(person(1), 0, 10)]).await;
+ sink.entered.notified().await;
+
+ let drain = tokio::spawn({
+ let dispatcher = dispatcher.clone();
+ async move { dispatcher.shutdown().await }
+ });
+ assert!(matches!(
+ dispatcher
+ .wait_for_worker_drain(Duration::from_millis(100))
+ .await,
+ DrainWait::TimedOut,
+ ));
+
+ sink.release.notify_one();
+ drain.await.unwrap();
+ // Closing the events consumer revokes every partition after the drain.
+ dispatcher.revoke_partition_sync(0);
+ dispatcher.revoke_partition_sync(1);
+ let DrainWait::Drained(drained) = dispatcher
+ .wait_for_worker_drain(Duration::from_secs(10))
+ .await
+ else {
+ panic!("the drain finished once the blocked produce was released");
+ };
+ assert_eq!(drained.partitions(), &HashSet::from([0, 1]));
+
+ let follower_tracker = OffsetTracker::new();
+ for partition in [0, 1, 2] {
+ follower_tracker.mark_dispatched(partition, 6);
+ assert_eq!(
+ follower_tracker.mark_processed(partition, 6),
+ MarkOutcome::WithinDispatch
+ );
+ }
+ assert_eq!(
+ crate::consumers::merges::committable_after_drain(
+ &follower_tracker,
+ &dispatcher,
+ HashSet::new(),
+ "follower_topic",
+ )
+ .await,
+ HashMap::from([(0, 6), (1, 6)]),
+ "a follower commits for the partitions drained, not the emptied live set",
+ );
+ }
+
+ #[tokio::test]
+ async fn finishing_boot_rebuilds_every_owned_partition_before_the_gate_opens() {
+ let (_dir, store) = temp_store();
+ let dispatcher = dispatcher_with(&store, behavioral_catalog());
+ dispatcher.enable_durable_restore();
+ dispatcher.assign_partition(0);
+ dispatcher.assign_partition(1);
+ let readiness = dispatcher.readiness().clone();
+ assert_eq!(readiness.check(), Err(NotReady::Booting));
+
+ assert_eq!(dispatcher.finish_boot(), 2);
+ assert_eq!(
+ readiness.check(),
+ Err(NotReady::Rebuilding { partitions: 2 }),
+ "both partitions rebuild although neither received a message",
+ );
+
+ let start = Instant::now();
+ while readiness.check().is_err() {
+ assert!(
+ start.elapsed() < Duration::from_secs(10),
+ "each rebuild releases the gate when its scan ends, got {:?}",
+ readiness.check(),
+ );
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ dispatcher.shutdown().await;
+ }
+
#[tokio::test]
async fn revoke_partition_drain_forgets_the_offset_so_it_is_not_recommitted() {
let (_dir, store) = temp_store();
@@ -2916,9 +2980,10 @@ mod tests {
}
#[tokio::test]
- async fn route_sweep_delivers_the_cutoff_to_each_owned_worker() {
+ async fn route_sweep_delivers_the_cutoff_to_each_owned_worker_once_the_catalog_loads() {
let (_dir, store) = temp_store();
- let dispatcher = dispatcher_with(&store, behavioral_catalog());
+ let catalog = Arc::new(CatalogHandle::new());
+ let dispatcher = dispatcher_with(&store, catalog.clone());
dispatcher.assign_partition(0);
dispatcher.assign_partition(1);
@@ -2927,6 +2992,15 @@ mod tests {
let cutoff = 1_700_000_000_000;
dispatcher.route_sweep(cutoff).await;
+ for rx in [&mut rx0, &mut rx1] {
+ assert!(
+ rx.live.try_recv().is_err(),
+ "a sweep before the first catalog load would drop every restored deadline",
+ );
+ }
+
+ catalog.publish(FilterCatalog::new());
+ dispatcher.route_sweep(cutoff).await;
for rx in [&mut rx0, &mut rx1] {
let batch = rx.live.recv().await.expect("a sweep was routed");
diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rs
index 70e2cdace5ca..95aa5a323db0 100644
--- a/rust/cohort-stream-processor/src/consumers/merges.rs
+++ b/rust/cohort-stream-processor/src/consumers/merges.rs
@@ -17,7 +17,7 @@ use rdkafka::message::Message;
use tracing::{debug, info, warn};
use crate::cascade::CascadeMessage;
-use crate::consumers::events::{fsync_then_commit, EventDispatcher, RECV_ERROR_BACKOFF};
+use crate::consumers::events::{fsync_then_commit, DrainWait, EventDispatcher, RECV_ERROR_BACKOFF};
use crate::merge::transfer::{MergeStateTransfer, PersonMergeEvent};
use crate::observability::metrics::{
COHORT_STREAM_CASCADES_CONSUMED, COHORT_STREAM_CASCADES_CONSUME_BATCH_SIZE,
@@ -218,12 +218,12 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;
- loop {
+ let owned_at_shutdown = loop {
tokio::select! {
biased;
_ = self.handle.shutdown_recv() => {
info!(topic = %self.topic, "shutdown signal received, stopping follower consume loop");
- break;
+ break self.dispatcher.owned_set();
}
outcome = self.consume_batch() => {
self.handle_outcome(outcome).await;
@@ -242,15 +242,20 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
}
}
}
- }
+ };
- // Final sync commit runs before the events consumer's shutdown; workers may still be marking
- // offsets at this point, but follower offsets are independent.
+ let offsets = committable_after_drain(
+ self.tracker(),
+ &self.dispatcher,
+ owned_at_shutdown,
+ &self.topic,
+ )
+ .await;
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
self.tracker(),
- self.owned_committable_offsets(),
+ offsets,
&self.topic,
CommitMode::Sync,
)
@@ -339,19 +344,43 @@ struct FollowerOutcome<T> {
transport_error: bool,
}
+/// Bounds a follower's final wait for the events consumer's worker drain. It exceeds the
+/// consumer's 30 s shutdown window and stays inside each follower's 45 s window (both in
+/// `main.rs`), so a follower outlives the drain and still has time to commit.
+pub(crate) const FOLLOWER_DRAIN_WAIT: Duration = Duration::from_secs(35);
+
/// A tracker's committable offsets restricted to the partitions this pod currently owns.
pub(crate) fn owned_committable_offsets(
tracker: &OffsetTracker,
dispatcher: &EventDispatcher,
) -> HashMap<i32, i64> {
- restrict_to_owned(
- tracker.committable_offsets(),
- &dispatcher.owned_partitions(),
- )
+ restrict_to_owned(tracker.committable_offsets(), &dispatcher.owned_set())
+}
+
+/// A follower's final commit: what the workers finished, including during the shutdown drain, for
+/// the partitions this pod owned when that drain ended. A drain that outlasts
+/// [`FOLLOWER_DRAIN_WAIT`] falls back to the ownership the follower saw when shutdown began.
+pub(crate) async fn committable_after_drain(
+ tracker: &OffsetTracker,
+ dispatcher: &EventDispatcher,
+ owned_at_shutdown: HashSet<i32>,
+ topic: &str,
+) -> HashMap<i32, i64> {
+ match dispatcher.wait_for_worker_drain(FOLLOWER_DRAIN_WAIT).await {
+ DrainWait::Drained(drained) => {
+ restrict_to_owned(tracker.committable_offsets(), drained.partitions())
+ }
+ DrainWait::TimedOut => {
+ warn!(
+ topic,
+ "worker drain outlasted the follower's wait; committing against the ownership seen at shutdown",
+ );
+ restrict_to_owned(tracker.committable_offsets(), &owned_at_shutdown)
+ }
+ }
}
-fn restrict_to_owned(offsets: HashMap<i32, i64>, owned: &[i32]) -> HashMap<i32, i64> {
- let owned: HashSet<i32> = owned.iter().copied().collect();
+fn restrict_to_owned(offsets: HashMap<i32, i64>, owned: &HashSet<i32>) -> HashMap<i32, i64> {
offsets
.into_iter()
.filter(|(partition, _)| owned.contains(partition))
@@ -480,7 +509,7 @@ mod tests {
fn restrict_to_owned_keeps_only_owned_partitions() {
let offsets: HashMap<i32, i64> = [(0, 10), (3, 30), (7, 70)].into_iter().collect();
- let restricted = restrict_to_owned(offsets, &[3, 7]);
+ let restricted = restrict_to_owned(offsets, &HashSet::from([3, 7]));
assert_eq!(restricted.len(), 2);
assert_eq!(restricted.get(&0), None, "revoked partition is dropped");
@@ -491,6 +520,6 @@ mod tests {
#[test]
fn restrict_to_owned_with_no_owned_partitions_is_empty() {
let offsets: HashMap<i32, i64> = [(0, 10)].into_iter().collect();
- assert!(restrict_to_owned(offsets, &[]).is_empty());
+ assert!(restrict_to_owned(offsets, &HashSet::new()).is_empty());
}
}
diff --git a/rust/cohort-stream-processor/src/consumers/mod.rs b/rust/cohort-stream-processor/src/consumers/mod.rs
index 32f725e500e9..3b93aa3abdd9 100644
--- a/rust/cohort-stream-processor/src/consumers/mod.rs
+++ b/rust/cohort-stream-processor/src/consumers/mod.rs
@@ -1,9 +1,11 @@
//! Kafka consumers — one rdkafka `StreamConsumer` per input topic. The `events` submodule covers
//! `cohort_stream_events`, the hot path; `merges` carries the merge-protocol follower consumers;
-//! `seeds` carries the backfill seed follower.
+//! `seeds` carries the backfill seed follower; `readiness` is the gate behind `/_ready`.
+mod boot;
pub mod events;
pub mod merges;
+pub mod readiness;
pub mod seeds;
pub use events::{CohortStreamEvent, CohortStreamEventsConsumer, ConsumedEvent, EventDispatcher};
@@ -11,4 +13,5 @@ pub use merges::{
CascadeRoute, ConsumedCascade, ConsumedMerge, ConsumedTransfer, FollowerConsumer,
FollowerRoute, MergeRoute, TransferRoute,
};
+pub use readiness::{BootReadiness, NotReady, RebuildGuard};
pub use seeds::{ConsumedSeed, SeedFollowerConsumer, SeedSkipReason, SeedWork};
diff --git a/rust/cohort-stream-processor/src/consumers/readiness.rs b/rust/cohort-stream-processor/src/consumers/readiness.rs
new file mode 100644
index 000000000000..2a3d5a19b269
--- /dev/null
+++ b/rust/cohort-stream-processor/src/consumers/readiness.rs
@@ -0,0 +1,136 @@
+//! The processor's readiness gate, the answer behind `/_ready`.
+//!
+//! The pod can carry live traffic once three things hold: the filter catalog has loaded, the events
+//! consumer has finished boot recovery, and no worker is still rebuilding its eviction queue. A
+//! StatefulSet rolling update moves to the next pod as soon as this one reads ready, so an early
+//! answer would put two pods into catch-up at once.
+
+use std::fmt;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use tokio::sync::SetOnce;
+
+use crate::filters::manager::CatalogHandle;
+
+/// Why the processor cannot carry live traffic yet. `Display` is the `/_ready` 503 body.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NotReady {
+ CatalogNotLoaded,
+ Booting,
+ Rebuilding { partitions: usize },
+}
+
+impl fmt::Display for NotReady {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::CatalogNotLoaded => f.write_str("filter catalog not loaded"),
+ Self::Booting => f.write_str("events consumer boot recovery in progress"),
+ Self::Rebuilding { partitions } => {
+ write!(
+ f,
+ "eviction queue rebuild in progress on {partitions} partitions"
+ )
+ }
+ }
+ }
+}
+
+pub struct BootReadiness {
+ catalog: Arc<CatalogHandle>,
+ live: SetOnce<()>,
+ rebuilding: AtomicUsize,
+}
+
+impl BootReadiness {
+ pub fn new(catalog: Arc<CatalogHandle>) -> Arc<Self> {
+ Arc::new(Self {
+ catalog,
+ live: SetOnce::new(),
+ rebuilding: AtomicUsize::new(0),
+ })
+ }
+
+ pub fn check(&self) -> Result<(), NotReady> {
+ if !self.catalog.is_loaded() {
+ return Err(NotReady::CatalogNotLoaded);
+ }
+ if !self.live.initialized() {
+ return Err(NotReady::Booting);
+ }
+ match self.rebuilding.load(Ordering::Acquire) {
+ 0 => Ok(()),
+ partitions => Err(NotReady::Rebuilding { partitions }),
+ }
+ }
+
+ /// Boot recovery has ended, so consumers may dispatch. The events consumer calls this once.
+ pub(crate) fn mark_live(&self) {
+ // Setting it twice is harmless: the gate is open either way.
+ let _ = self.live.set(());
+ }
+
+ /// Resolve once the catalog has loaded and boot recovery has ended, so no worker a consumer
+ /// spawns runs while boot recovery writes to the store.
+ pub async fn wait_until_dispatchable(&self) {
+ self.catalog.wait_until_loaded().await;
+ self.live.wait().await;
+ }
+
+ pub fn rebuild_started(self: &Arc<Self>) -> RebuildGuard {
+ self.rebuilding.fetch_add(1, Ordering::AcqRel);
+ RebuildGuard(self.clone())
+ }
+}
+
+/// One eviction-queue rebuild in flight. Dropping it, also by a panic, ends the count.
+#[must_use = "the rebuild counts as running until this guard drops"]
+pub struct RebuildGuard(Arc<BootReadiness>);
+
+impl Drop for RebuildGuard {
+ fn drop(&mut self) {
+ self.0.rebuilding.fetch_sub(1, Ordering::AcqRel);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::filters::FilterCatalog;
+
+ #[test]
+ fn an_unloaded_catalog_keeps_the_gate_closed_even_after_boot() {
+ let readiness = BootReadiness::new(Arc::new(CatalogHandle::new()));
+ readiness.mark_live();
+
+ assert_eq!(readiness.check(), Err(NotReady::CatalogNotLoaded));
+ }
+
+ #[tokio::test]
+ async fn the_gate_opens_only_after_boot_and_every_rebuild_including_a_panicked_one() {
+ let readiness =
+ BootReadiness::new(Arc::new(CatalogHandle::from_catalog(FilterCatalog::new())));
+ assert_eq!(readiness.check(), Err(NotReady::Booting));
+
+ let finished = readiness.rebuild_started();
+ let panicked = readiness.rebuild_started();
+ readiness.mark_live();
+ assert_eq!(
+ readiness.check(),
+ Err(NotReady::Rebuilding { partitions: 2 })
+ );
+
+ drop(finished);
+ assert_eq!(
+ readiness.check(),
+ Err(NotReady::Rebuilding { partitions: 1 })
+ );
+
+ let rebuild = tokio::spawn(async move {
+ let _guard = panicked;
+ panic!("rebuild scan panicked");
+ });
+ assert!(rebuild.await.unwrap_err().is_panic());
+ assert_eq!(readiness.check(), Ok(()));
+ }
+}
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index 8cffc70a9a83..9d6d4cc62379 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -25,7 +25,7 @@ use rdkafka::{Offset, TopicPartitionList};
use tracing::{debug, info, warn};
use crate::consumers::events::{fsync_then_commit, run_pauser_loop, EventDispatcher};
-use crate::consumers::merges::owned_committable_offsets;
+use crate::consumers::merges::{committable_after_drain, owned_committable_offsets};
use crate::observability::disk::{DiskUtilization, SharedDiskUtilization};
use crate::observability::metrics::{
COHORT_STREAM_KAFKA_RECV_ERRORS, COHORT_STREAM_SEEDS_CONSUMED,
@@ -527,12 +527,12 @@ impl SeedFollowerConsumer {
let mut prev_paused_target: HashSet<i32> = HashSet::new();
let mut commit_deadline = tokio::time::Instant::now() + self.offset_commit_interval;
- loop {
+ let owned_at_shutdown = loop {
tokio::select! {
biased;
_ = self.handle.shutdown_recv() => {
info!(topic = %self.topic, "shutdown signal received, stopping seed consume loop");
- break;
+ break self.dispatcher.owned_set();
}
outcome = self.consume_batch() => {
self.cycle(outcome, &mut holdover, &mut pacing, &mut prev_paused_target, &pause_tx).await;
@@ -551,7 +551,7 @@ impl SeedFollowerConsumer {
}
}
}
- }
+ };
drop(pause_tx);
if let Err(err) = pauser_task.await {
@@ -561,11 +561,18 @@ impl SeedFollowerConsumer {
warn!(error = %err, "seed idle-probe task did not exit cleanly");
}
+ let offsets = committable_after_drain(
+ &self.dispatcher.merge_deps().seed_tracker,
+ &self.dispatcher,
+ owned_at_shutdown,
+ &self.topic,
+ )
+ .await;
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
&self.dispatcher.merge_deps().seed_tracker,
- self.owned_committable_offsets(),
+ offsets,
&self.topic,
CommitMode::Sync,
)
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 56041dc20d61..febdbcd3b897 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -1,8 +1,9 @@
//! `FilterCatalog` + atomic swap + jittered periodic refresh loop.
use std::collections::hash_map::DefaultHasher;
+use std::future::Future;
use std::hash::{Hash, Hasher};
-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
@@ -40,11 +41,35 @@ pub enum CatalogRefreshError {
Build(#[from] JoinError),
}
+/// Ordinal of a catalog refresh, taken when the refresh starts. A snapshot published by refresh `n`
+/// read Postgres after `n` began. Only [`CatalogHandle`] mints one.
+///
+/// "Read after it began" also assumes the database the refresh reads is current. When the catalog
+/// reads a read replica, a reconcile job relies on replica lag staying below the delay from
+/// Django's commit to the job's admission, which spans the seeder, Kafka and the seed consumer.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub(crate) struct RefreshSeq(u64);
+
+/// One consistent read of the handle: the snapshot and the refresh that published it.
+pub(crate) enum CatalogView {
+ NotLoaded,
+ Loaded {
+ published: RefreshSeq,
+ catalog: Arc<FilterCatalog>,
+ },
+}
+
/// Lock-free, atomically-swapped catalog handle. Starts empty and unloaded; the pipeline fails
/// closed until the first successful refresh.
+///
+/// The refresh loop is its only writer after boot, and the boot refresh ends before the loop
+/// starts, so refreshes never overlap.
pub struct CatalogHandle {
catalog: ArcSwap<FilterCatalog>,
- loaded: AtomicBool,
+ /// Refreshes started. Refresh `n` takes `n` when it starts.
+ begun: AtomicU64,
+ /// Sequence of the published snapshot, 0 before the first store.
+ published: AtomicU64,
loaded_notify: Notify,
/// Cohorts for teams outside this allowlist never enter the catalog.
allowlist: TeamAllowlist,
@@ -64,7 +89,8 @@ impl CatalogHandle {
pub fn with_allowlist(allowlist: TeamAllowlist, cascade_enabled: bool) -> Self {
Self {
catalog: ArcSwap::from_pointee(FilterCatalog::new()),
- loaded: AtomicBool::new(false),
+ begun: AtomicU64::new(0),
+ published: AtomicU64::new(0),
loaded_notify: Notify::new(),
allowlist,
cascade_enabled,
@@ -88,7 +114,28 @@ impl CatalogHandle {
/// True once the first refresh has succeeded. Before that the catalog is empty and consumers
/// should treat every team as having no realtime cohorts.
pub fn is_loaded(&self) -> bool {
- self.loaded.load(Ordering::Acquire)
+ self.published.load(Ordering::Acquire) > 0
+ }
+
+ /// The newest refresh that has started. An admitted reconcile job records it.
+ pub(crate) fn last_begun(&self) -> RefreshSeq {
+ RefreshSeq(self.begun.load(Ordering::SeqCst))
+ }
+
+ /// Reads `published` before the snapshot, so the snapshot is at least as new as the sequence it
+ /// reports.
+ pub(crate) fn view(&self) -> CatalogView {
+ match self.published.load(Ordering::Acquire) {
+ 0 => CatalogView::NotLoaded,
+ published => CatalogView::Loaded {
+ published: RefreshSeq(published),
+ catalog: self.catalog.load_full(),
+ },
+ }
+ }
+
+ fn begin(&self) -> RefreshSeq {
+ RefreshSeq(self.begun.fetch_add(1, Ordering::SeqCst) + 1)
}
/// Resolve once the first refresh has succeeded; immediate if it already has.
@@ -107,11 +154,32 @@ impl CatalogHandle {
/// Build an already-loaded handle from a prebuilt catalog (test seam).
pub fn from_catalog(catalog: FilterCatalog) -> Self {
let handle = Self::new();
- handle.store(catalog);
+ handle.store(catalog, handle.begin());
handle
}
- fn store(&self, catalog: FilterCatalog) {
+ /// A refresh that begins now and publishes `catalog`, for tests that need a refresh after some
+ /// event.
+ #[cfg(test)]
+ pub(crate) fn publish(&self, catalog: FilterCatalog) {
+ self.begin_refresh().publish(catalog);
+ }
+
+ /// A refresh that begins now and publishes later, for tests of a refresh in flight across some
+ /// event.
+ #[cfg(test)]
+ pub(crate) fn begin_refresh(&self) -> PendingRefresh<'_> {
+ PendingRefresh {
+ handle: self,
+ seq: self.begin(),
+ }
+ }
+
+ fn store(&self, catalog: FilterCatalog, seq: RefreshSeq) {
+ debug_assert!(
+ seq.0 > self.published.load(Ordering::Acquire),
+ "catalog refreshes overlapped: refresh {seq:?} stores after a newer one",
+ );
// Advance the generation only on a content change (`INITIAL` is the first store); a no-op
// refresh reuses it so memo entries stay valid.
let signature = catalog_signature(&catalog);
@@ -130,7 +198,7 @@ impl CatalogHandle {
gauge!(FILTER_CATALOG_TEAMS).set(catalog.team_count() as f64);
gauge!(FILTER_CATALOG_UNIQUE_CONDITIONS).set(catalog.total_unique_conditions() as f64);
self.catalog.store(Arc::new(catalog));
- self.loaded.store(true, Ordering::Release);
+ self.published.fetch_max(seq.0, Ordering::Release);
self.loaded_notify.notify_waiters();
}
@@ -140,7 +208,7 @@ impl CatalogHandle {
/// in `main` counts too — otherwise a pod that booted fine and then lost its refresh loop would
/// look identical to one that never loaded.
pub async fn refresh(&self, pool: &PgPool) -> Result<CatalogStats, CatalogRefreshError> {
- match self.refresh_inner(pool).await {
+ match self.refresh_from(|| load_realtime_cohorts(pool)).await {
Ok(stats) => {
gauge!(FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS).set(now_unix_seconds());
counter!(FILTER_CATALOG_REFRESH_TOTAL, "result" => "success").increment(1);
@@ -153,8 +221,17 @@ impl CatalogHandle {
}
}
- async fn refresh_inner(&self, pool: &PgPool) -> Result<CatalogStats, CatalogRefreshError> {
- let mut rows = load_realtime_cohorts(pool).await?;
+ /// `load` reads the cohort rows. The refresh begins before it runs, so every write committed
+ /// before the read is in what it returns.
+ async fn refresh_from<Rows>(
+ &self,
+ load: impl FnOnce() -> Rows,
+ ) -> Result<CatalogStats, CatalogRefreshError>
+ where
+ Rows: Future<Output = Result<Vec<CohortRow>, FilterError>>,
+ {
+ let seq = self.begin();
+ let mut rows = load().await?;
let fetched_rows = rows.len();
retain_allowlisted(&mut rows, &self.allowlist);
if rows.len() != fetched_rows {
@@ -165,12 +242,13 @@ impl CatalogHandle {
);
}
let cascade_enabled = self.cascade_enabled;
- self.build_and_store(move || build_catalog_from_rows(rows, cascade_enabled))
+ self.build_and_store(seq, move || build_catalog_from_rows(rows, cascade_enabled))
.await
}
async fn build_and_store(
&self,
+ seq: RefreshSeq,
build: impl FnOnce() -> FilterCatalog + Send + 'static,
) -> Result<CatalogStats, CatalogRefreshError> {
let catalog = tokio::task::spawn_blocking(move || {
@@ -185,7 +263,7 @@ impl CatalogHandle {
teams: catalog.team_count(),
unique_conditions: catalog.total_unique_conditions(),
};
- self.store(catalog);
+ self.store(catalog, seq);
Ok(stats)
}
}
@@ -203,6 +281,21 @@ fn retain_allowlisted(rows: &mut Vec<CohortRow>, allowlist: &TeamAllowlist) {
rows.retain(|row| allowlist.includes(row.team_id));
}
+/// A refresh that has begun and not yet published (test seam).
+#[cfg(test)]
+#[must_use = "a pending refresh publishes nothing until `publish` is called"]
+pub(crate) struct PendingRefresh<'a> {
+ handle: &'a CatalogHandle,
+ seq: RefreshSeq,
+}
+
+#[cfg(test)]
+impl PendingRefresh<'_> {
+ pub(crate) fn publish(self, catalog: FilterCatalog) {
+ self.handle.store(catalog, self.seq);
+ }
+}
+
impl Default for CatalogHandle {
fn default() -> Self {
Self::new()
@@ -348,7 +441,7 @@ mod tests {
let handle = CatalogHandle::new();
let runtime_thread = std::thread::current().id();
let stats = handle
- .build_and_store(move || {
+ .build_and_store(handle.begin(), move || {
assert_ne!(std::thread::current().id(), runtime_thread);
FilterCatalog::from_teams([(TeamId(7), team_with_one_behavioral())])
})
@@ -360,7 +453,7 @@ mod tests {
let snapshot = handle.load_full();
let error = handle
- .build_and_store(|| panic!("catalog build failed"))
+ .build_and_store(handle.begin(), || panic!("catalog build failed"))
.await
.unwrap_err();
assert!(matches!(error, CatalogRefreshError::Build(error) if error.is_panic()));
@@ -380,7 +473,7 @@ mod tests {
tokio::task::yield_now().await;
assert!(!waiter.is_finished());
- handle.store(FilterCatalog::from_teams([(
+ handle.publish(FilterCatalog::from_teams([(
TeamId(7),
team_with_one_behavioral(),
)]));
@@ -390,11 +483,31 @@ mod tests {
handle.wait_until_loaded().await;
}
+ #[tokio::test]
+ async fn a_refresh_begins_before_it_reads_the_cohort_rows() {
+ let handle = CatalogHandle::new();
+ let before_refresh = handle.last_begun();
+ let begun_at_read = std::cell::Cell::new(before_refresh);
+
+ handle
+ .refresh_from(|| async {
+ begun_at_read.set(handle.last_begun());
+ Ok(Vec::new())
+ })
+ .await
+ .unwrap();
+
+ assert!(
+ begun_at_read.get() > before_refresh,
+ "a job admitted during the read must not count the refresh as begun after it",
+ );
+ }
+
#[test]
fn first_store_advances_past_the_initial_generation() {
let handle = CatalogHandle::new();
assert_eq!(handle.load().generation(), Generation::INITIAL);
- handle.store(FilterCatalog::from_teams([(
+ handle.publish(FilterCatalog::from_teams([(
TeamId(7),
team_with_one_behavioral(),
)]));
@@ -412,14 +525,14 @@ mod tests {
#[test]
fn no_op_refresh_keeps_the_generation_and_a_content_change_bumps_it() {
let handle = CatalogHandle::new();
- handle.store(FilterCatalog::from_teams([(
+ handle.publish(FilterCatalog::from_teams([(
TeamId(7),
team_with_one_behavioral(),
)]));
let gen1 = handle.load().generation();
// Same condition set → same signature → generation unchanged (the memo survives the refresh).
- handle.store(FilterCatalog::from_teams([(
+ handle.publish(FilterCatalog::from_teams([(
TeamId(7),
team_with_one_behavioral(),
)]));
@@ -430,7 +543,7 @@ mod tests {
);
// A different condition hash → signature changes → generation advances (memo invalidates).
- handle.store(FilterCatalog::from_teams([(
+ handle.publish(FilterCatalog::from_teams([(
TeamId(7),
team_with_one_person(),
)]));
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index fecebabaff4e..ed3b81bd297b 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -17,8 +17,8 @@ use tracing_subscriber::{fmt, EnvFilter, Layer};
use cohort_stream_processor::config::Config;
use cohort_stream_processor::consumers::{
- CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer, FollowerRoute,
- MergeRoute, SeedFollowerConsumer, TransferRoute,
+ BootReadiness, CascadeRoute, CohortStreamEventsConsumer, EventDispatcher, FollowerConsumer,
+ FollowerRoute, MergeRoute, SeedFollowerConsumer, TransferRoute,
};
use cohort_stream_processor::filters::{run_refresh_loop, CatalogHandle};
use cohort_stream_processor::merge::gc::MergeGcSweeper;
@@ -92,26 +92,29 @@ async fn async_main(config: Config) -> Result<()> {
.with_liveness_deadline(Duration::from_secs(60))
.with_stall_threshold(3),
);
+ // Followers make their final commit after the consumer's worker drain. So each 45 s window
+ // outlasts the consumer's 30 s one, and the 10 s past `FOLLOWER_DRAIN_WAIT` (35 s) is for the
+ // commit itself.
let merge_follower_handle = manager.register(
"merge-follower",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(45)),
);
let transfer_follower_handle = manager.register(
"transfer-follower",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(45)),
);
// Registered only when the gate is on — a dormant deploy must not wait on a component that never
// starts.
let cascade_follower_handle = config.cohort_cascade_enabled.then(|| {
manager.register(
"cascade-follower",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(45)),
)
});
let seed_follower_handle = config.cohort_seed_consumer_enabled.then(|| {
manager.register(
"seed-follower",
- ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(30)),
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(45)),
)
});
// Short graceful window: it holds no state and its next tick is disposable.
@@ -297,6 +300,7 @@ async fn async_main(config: Config) -> Result<()> {
}
// Event-name fan-out gating, likewise set before any worker spawns.
dispatcher.set_event_name_gating(config.event_name_gating());
+ let boot_readiness = dispatcher.readiness().clone();
let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
let stream_consumer: StreamConsumer<CohortConsumerContext> = config
@@ -625,7 +629,11 @@ async fn async_main(config: Config) -> Result<()> {
config.recv_batch_timeout(),
config.offset_commit_interval(),
);
- spawn_follower_after_catalog_load(catalog.clone(), merge_follower, merge_follower_handle);
+ spawn_follower_after_boot(
+ boot_readiness.clone(),
+ merge_follower,
+ merge_follower_handle,
+ );
let transfer_follower = FollowerConsumer::<TransferRoute>::new(
transfers_follower_consumer,
@@ -636,7 +644,11 @@ async fn async_main(config: Config) -> Result<()> {
config.recv_batch_timeout(),
config.offset_commit_interval(),
);
- spawn_follower_after_catalog_load(catalog.clone(), transfer_follower, transfer_follower_handle);
+ spawn_follower_after_boot(
+ boot_readiness.clone(),
+ transfer_follower,
+ transfer_follower_handle,
+ );
if let (Some(cascade_consumer), Some(cascade_handle)) =
(cascade_follower_consumer, cascade_follower_handle)
@@ -650,7 +662,7 @@ async fn async_main(config: Config) -> Result<()> {
config.recv_batch_timeout(),
config.offset_commit_interval(),
);
- spawn_follower_after_catalog_load(catalog.clone(), cascade_follower, cascade_handle);
+ spawn_follower_after_boot(boot_readiness.clone(), cascade_follower, cascade_handle);
}
if let (Some(seed_consumer), Some(seed_handle)) = (seed_follower_consumer, seed_follower_handle)
@@ -676,12 +688,12 @@ async fn async_main(config: Config) -> Result<()> {
config.seed_pacing_config()?,
disk_state.clone(),
);
- let seed_catalog = catalog.clone();
+ let seed_readiness = boot_readiness.clone();
tokio::spawn(async move {
tokio::select! {
biased;
_ = seed_handle.shutdown_recv() => {}
- _ = seed_catalog.wait_until_loaded() => seed_follower.process().await,
+ _ = seed_readiness.wait_until_dispatchable() => seed_follower.process().await,
}
});
}
@@ -696,13 +708,19 @@ async fn async_main(config: Config) -> Result<()> {
config.offset_commit_interval(),
events_partitions,
consumer_command_rx,
- // Events-topic seek positions for the restore-and-seek step; `None` on the no-seek paths
- // (reopen-live / cold-start).
+ // Events-topic positions a checkpoint restore rewinds to; `None` on the paths with no
+ // checkpoint (reopen-live / cold-start), where boot rewinds only what it polled.
restore.manifest,
);
tokio::spawn(events_consumer.process());
- let app = observability::health::router(SERVICE_NAME, readiness, liveness, recorder_handle);
+ let app = observability::health::router(
+ SERVICE_NAME,
+ readiness,
+ boot_readiness,
+ liveness,
+ recorder_handle,
+ );
let bind = config.bind_address();
info!(address = %bind, "observability server starting");
@@ -795,8 +813,8 @@ fn manifest_commit_tpl(topic: &str, manifest: &OffsetManifest) -> Option<TopicPa
(tpl.count() > 0).then_some(tpl)
}
-fn spawn_follower_after_catalog_load<R: FollowerRoute>(
- catalog: Arc<CatalogHandle>,
+fn spawn_follower_after_boot<R: FollowerRoute>(
+ readiness: Arc<BootReadiness>,
follower: FollowerConsumer<R>,
handle: Handle,
) {
@@ -804,7 +822,7 @@ fn spawn_follower_after_catalog_load<R: FollowerRoute>(
tokio::select! {
biased;
_ = handle.shutdown_recv() => {}
- _ = catalog.wait_until_loaded() => follower.process().await,
+ _ = readiness.wait_until_dispatchable() => follower.process().await,
}
});
}
diff --git a/rust/cohort-stream-processor/src/observability/health.rs b/rust/cohort-stream-processor/src/observability/health.rs
index a951e2bae5c0..4a5eecf0efdd 100644
--- a/rust/cohort-stream-processor/src/observability/health.rs
+++ b/rust/cohort-stream-processor/src/observability/health.rs
@@ -1,20 +1,26 @@
//! Observability HTTP surface: `/_health`, `/_ready`, `/metrics`, `/`.
//!
//! `/_health` always returns 200: the `lifecycle` monitor owns health internally and triggers
-//! coordinated shutdown on stall, rather than relying on K8s liveness kills.
+//! coordinated shutdown on stall, rather than relying on K8s liveness kills. So the startup and
+//! liveness probes stay on it, and a slow boot only holds `/_ready` closed.
use std::future::ready;
+use std::sync::Arc;
-use axum::response::IntoResponse;
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::Router;
use lifecycle::{LivenessHandler, ReadinessHandler};
use metrics_exporter_prometheus::PrometheusHandle;
+use crate::consumers::readiness::BootReadiness;
+
/// Build the observability router. Pass `metrics = None` to omit `/metrics`.
pub fn router(
service_name: &'static str,
readiness: ReadinessHandler,
+ boot: Arc<BootReadiness>,
liveness: LivenessHandler,
metrics: Option<PrometheusHandle>,
) -> Router {
@@ -31,7 +37,8 @@ pub fn router(
"/_ready",
get(move || {
let readiness = readiness.clone();
- async move { readiness.check().await }
+ let boot = boot.clone();
+ async move { ready_response(&readiness, &boot).await }
}),
);
@@ -41,3 +48,54 @@ pub fn router(
app
}
+
+/// 503 while lifecycle is shutting down, then 503 with the reason while the pod cannot carry live
+/// traffic yet, else 200.
+async fn ready_response(readiness: &ReadinessHandler, boot: &BootReadiness) -> Response {
+ let lifecycle = readiness.check().await;
+ if lifecycle != StatusCode::OK {
+ return lifecycle.into_response();
+ }
+ match boot.check() {
+ Ok(()) => StatusCode::OK.into_response(),
+ Err(not_ready) => (StatusCode::SERVICE_UNAVAILABLE, not_ready.to_string()).into_response(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::filters::manager::CatalogHandle;
+ use crate::filters::FilterCatalog;
+
+ async fn status_and_body(response: Response) -> (StatusCode, String) {
+ let status = response.status();
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ (status, String::from_utf8(body.to_vec()).unwrap())
+ }
+
+ #[tokio::test]
+ async fn ready_is_503_with_the_reason_until_boot_recovery_ends() {
+ let manager = lifecycle::Manager::builder("health-test")
+ .with_trap_signals(false)
+ .build();
+ let readiness = manager.readiness_handler();
+ let boot = BootReadiness::new(Arc::new(CatalogHandle::from_catalog(FilterCatalog::new())));
+
+ assert_eq!(
+ status_and_body(ready_response(&readiness, &boot).await).await,
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ "events consumer boot recovery in progress".to_string()
+ ),
+ );
+
+ boot.mark_live();
+ assert_eq!(
+ ready_response(&readiness, &boot).await.status(),
+ StatusCode::OK
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 7dfbed8aafee..8a8e2039ec09 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -658,6 +658,10 @@ pub const RECONCILE_JOBS_SUPERSEDED_TOTAL: &str = "cohort_reconcile_jobs_superse
/// Reconcile jobs invalidated by a drain-time guard, labelled by bounded `reason` and `kind`
/// (counter).
pub const RECONCILE_JOBS_DISCARDED_TOTAL: &str = "cohort_reconcile_jobs_discarded_total";
+/// 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.
+pub const RECONCILE_JOBS_DEFERRED_TOTAL: &str = "cohort_reconcile_jobs_deferred_total";
/// Stage 2 rows read by reconcile and durably settled, counted once per committed page (counter). A
/// page that fails its produce or commit and retries is not double-counted.
pub const RECONCILE_ROWS_SCANNED_TOTAL: &str = "cohort_reconcile_rows_scanned_total";
@@ -1087,6 +1091,10 @@ mod tests {
RECONCILE_JOBS_DISCARDED_TOTAL,
"cohort_reconcile_jobs_discarded_total",
);
+ assert_eq!(
+ RECONCILE_JOBS_DEFERRED_TOTAL,
+ "cohort_reconcile_jobs_deferred_total",
+ );
assert_eq!(
RECONCILE_ROWS_SCANNED_TOTAL,
"cohort_reconcile_rows_scanned_total",
diff --git a/rust/cohort-stream-processor/src/store/durability/recovery.rs b/rust/cohort-stream-processor/src/store/durability/recovery.rs
index c37bec202d3d..36bab1ed8f4f 100644
--- a/rust/cohort-stream-processor/src/store/durability/recovery.rs
+++ b/rust/cohort-stream-processor/src/store/durability/recovery.rs
@@ -61,8 +61,8 @@ impl RestoreSource {
}
/// The result of [`run_boot_restore`]: the chosen source plus the offset manifest that the events
-/// consumer seeks to. `manifest` is `None` for the no-seek paths (`ReopenLive`, `ColdStart`) and
-/// `Some` for the disaster paths (`PvcCheckpoint`, `S3`).
+/// consumer seeks to. `manifest` is `None` for the paths with no checkpoint (`ReopenLive`,
+/// `ColdStart`) and `Some` for the disaster paths (`PvcCheckpoint`, `S3`).
#[derive(Debug)]
pub struct RestoreOutcome {
pub source: RestoreSource,
diff --git a/rust/cohort-stream-processor/src/sweep/reconcile.rs b/rust/cohort-stream-processor/src/sweep/reconcile.rs
index 090411a9cd75..5ae739615b0c 100644
--- a/rust/cohort-stream-processor/src/sweep/reconcile.rs
+++ b/rust/cohort-stream-processor/src/sweep/reconcile.rs
@@ -92,7 +92,7 @@ mod tests {
let tracker = OffsetTracker::new();
tracker.mark_dispatched(0, 6);
- let mut queue = ReconcileQueue::new(0, backlog, handle);
+ let mut queue = ReconcileQueue::new(0, backlog, handle, Arc::new(CatalogHandle::new()));
queue.enqueue(
ReconcileTile::new(
TeamId(7),
diff --git a/rust/cohort-stream-processor/src/workers/mod.rs b/rust/cohort-stream-processor/src/workers/mod.rs
index 41e76d1c79c6..9d3111eff926 100644
--- a/rust/cohort-stream-processor/src/workers/mod.rs
+++ b/rust/cohort-stream-processor/src/workers/mod.rs
@@ -29,4 +29,4 @@ pub use person_seed_path::PersonSeedDeps;
pub use reconcile::{ReconcileBacklog, ReconcileDeps, DEFAULT_RECONCILE_SCAN_PAGE};
pub use stage2_gc::{handle_stage2_orphan_gc, Stage2GcCursor};
pub use stage2_path::compose_stage2;
-pub use worker::Stage1Worker;
+pub use worker::{EvictionRestore, Stage1Worker};
diff --git a/rust/cohort-stream-processor/src/workers/reconcile.rs b/rust/cohort-stream-processor/src/workers/reconcile.rs
index 9ca530922ae5..cfa437b50728 100644
--- a/rust/cohort-stream-processor/src/workers/reconcile.rs
+++ b/rust/cohort-stream-processor/src/workers/reconcile.rs
@@ -17,12 +17,13 @@ use cohort_core::filters::{CohortId, TeamId};
#[cfg(test)]
use cohort_core::seed::RunId;
use cohort_core::seed::{ReconcileScope, ReconcileTile, ScopeKind};
+use cohort_core::CohortEligibility;
-use crate::filters::manager::CatalogHandle;
+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_DISCARDED_TOTAL,
+ RECONCILE_JOBS_COMPLETED_TOTAL, RECONCILE_JOBS_DEFERRED_TOTAL, RECONCILE_JOBS_DISCARDED_TOTAL,
RECONCILE_MARKERS_EMITTED_TOTAL, RECONCILE_MARKER_PRODUCE_ERRORS,
RECONCILE_PAGE_DURATION_SECONDS, RECONCILE_QUEUE_DEPTH, RECONCILE_ROWS_EMITTED_TOTAL,
RECONCILE_ROWS_SCANNED_TOTAL,
@@ -123,6 +124,11 @@ enum ScanPhase {
struct ReconcileJob {
tile: ReconcileTile,
offset: DeferredOffset,
+ /// The newest catalog refresh that had begun when the job was admitted. Only a snapshot from a
+ /// later refresh can discard it.
+ admitted_after: RefreshSeq,
+ /// Set the first time the job waits for that refresh, so the wait counts and logs once.
+ deferral_counted: bool,
dirty_tracking: Option<crate::store::Stage2DirtyTrackingGuard>,
phase: ScanPhase,
rows_scanned: u64,
@@ -141,6 +147,9 @@ pub(crate) struct ReconcileQueue {
backlog: Arc<ReconcileBacklog>,
partition_label: Arc<str>,
handle: StoreHandle,
+ /// `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>,
}
impl ReconcileQueue {
@@ -148,12 +157,14 @@ impl ReconcileQueue {
partition_id: u16,
backlog: Arc<ReconcileBacklog>,
handle: StoreHandle,
+ catalog: Arc<CatalogHandle>,
) -> Self {
let queue = Self {
jobs: VecDeque::new(),
backlog,
partition_label: Arc::from(partition_id.to_string()),
handle,
+ catalog,
};
queue.record_depth();
queue
@@ -163,6 +174,8 @@ impl ReconcileQueue {
self.jobs.push_back(ReconcileJob {
tile,
offset,
+ admitted_after: self.catalog.last_begun(),
+ deferral_counted: false,
dirty_tracking: None,
phase: ScanPhase::Scanning { cursor: None },
rows_scanned: 0,
@@ -263,6 +276,8 @@ impl Drop for ReconcileQueue {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
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)]
@@ -286,32 +301,34 @@ impl ReconcileDiscardReason {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug)]
enum ReconcileGuard {
- Proceed,
+ /// Carries the team filters and eligibility the guard found, so the drain does not look them up
+ /// again.
+ Proceed {
+ filters: Arc<TeamFilters>,
+ eligibility: CohortEligibility,
+ },
Retry(ReconcileRetryReason),
Discard(ReconcileDiscardReason),
}
-fn evaluate_guard(
- catalog_loaded: bool,
- filters: Option<&TeamFilters>,
+/// The catalog's answer alone, with no view of how fresh the catalog is.
+fn catalog_verdict(
+ filters: Option<&Arc<TeamFilters>>,
tile: &ReconcileTile,
-) -> ReconcileGuard {
- if !catalog_loaded {
- return ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded);
- }
+) -> Result<(Arc<TeamFilters>, CohortEligibility), ReconcileDiscardReason> {
let Some(filters) = filters else {
- return ReconcileGuard::Discard(ReconcileDiscardReason::TeamAbsent);
+ return Err(ReconcileDiscardReason::TeamAbsent);
};
if !filters.cohorts.contains_key(&tile.cohort_id()) {
- return ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent);
+ return Err(ReconcileDiscardReason::CohortAbsent);
}
- let Some(eligibility) = filters.eligibility.get(&tile.cohort_id()) else {
- return ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent);
+ let Some(&eligibility) = filters.eligibility.get(&tile.cohort_id()) else {
+ return Err(ReconcileDiscardReason::CohortAbsent);
};
if !eligibility.registers_membership() {
- return ReconcileGuard::Discard(ReconcileDiscardReason::NotEmitting);
+ return Err(ReconcileDiscardReason::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
@@ -328,9 +345,34 @@ fn evaluate_guard(
.map(|current| current == pinned),
};
match matches {
- None => ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
- Some(false) => ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch),
- Some(true) => ReconcileGuard::Proceed,
+ None => Err(ReconcileDiscardReason::HashUnknown),
+ Some(false) => Err(ReconcileDiscardReason::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
+/// 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.
+fn evaluate_guard(
+ view: &CatalogView,
+ admitted_after: RefreshSeq,
+ tile: &ReconcileTile,
+) -> ReconcileGuard {
+ let (published, catalog) = match view {
+ CatalogView::NotLoaded => {
+ return ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded)
+ }
+ CatalogView::Loaded { published, catalog } => (*published, catalog),
+ };
+ match catalog_verdict(catalog.team(tile.team_id()), tile) {
+ Ok((filters, eligibility)) => ReconcileGuard::Proceed {
+ filters,
+ eligibility,
+ },
+ Err(reason) if published > admitted_after => ReconcileGuard::Discard(reason),
+ Err(reason) => ReconcileGuard::Retry(ReconcileRetryReason::AwaitingRefresh(reason)),
}
}
@@ -341,7 +383,6 @@ fn evaluate_guard(
pub(crate) async fn handle_reconcile_drain(
partition_id: u16,
handle: &StoreHandle,
- catalog: &CatalogHandle,
sink: &Arc<dyn MembershipSink>,
merge: &MergeWorkerDeps,
queue: &mut ReconcileQueue,
@@ -355,58 +396,75 @@ pub(crate) async fn handle_reconcile_drain(
let phase = job.phase.clone();
let source_offset = job.offset.offset();
- // Read the release-published loaded flag before the ArcSwap. On the first refresh, that
- // ordering prevents observing `loaded = true` alongside the pre-refresh empty snapshot.
- let catalog_loaded = catalog.is_loaded();
- let catalog_snapshot = catalog.load_full();
- let filters = catalog_snapshot.team(tile.team_id());
- match evaluate_guard(catalog_loaded, filters.map(Arc::as_ref), &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::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",
- );
- counter!(
- RECONCILE_JOBS_DISCARDED_TOTAL,
- "reason" => reason.as_str(),
- "kind" => tile.scope().kind().as_str(),
- )
- .increment(1);
- warn_job!(
- tile,
- partition_id,
- reason = reason.as_str(),
- kind = tile.scope().kind().as_str(),
- "discarding reconcile job without a completion marker",
- );
- continue;
- }
- ReconcileGuard::Proceed => {}
- }
+ 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",
+ );
+ counter!(
+ RECONCILE_JOBS_DISCARDED_TOTAL,
+ "reason" => reason.as_str(),
+ "kind" => tile.scope().kind().as_str(),
+ )
+ .increment(1);
+ warn_job!(
+ tile,
+ partition_id,
+ reason = reason.as_str(),
+ kind = tile.scope().kind().as_str(),
+ "discarding reconcile job without a completion marker",
+ );
+ continue;
+ }
+ ReconcileGuard::Proceed {
+ filters,
+ eligibility,
+ } => (filters, eligibility),
+ };
- let filters = filters.expect("the proceed guard proved the team exists");
// Only flipped bits of a full-tree cohort cascade to referrers; single-leaf fixes never do.
- let cascades_flips = filters
- .eligibility
- .get(&tile.cohort_id())
- .copied()
- .expect("the proceed guard proved eligibility exists")
- .writes_cf_stage2();
+ let cascades_flips = eligibility.writes_cf_stage2();
let prefix = Stage2CohortPrefix {
partition_id,
@@ -424,7 +482,7 @@ pub(crate) async fn handle_reconcile_drain(
merge,
queue,
&tile,
- filters,
+ &filters,
cascades_flips,
prefix,
source_offset,
@@ -441,7 +499,7 @@ pub(crate) async fn handle_reconcile_drain(
merge,
queue,
&tile,
- filters,
+ &filters,
cascades_flips,
prefix,
source_offset,
@@ -1081,7 +1139,9 @@ mod tests {
})
}
- fn catalog(single_leaf: bool) -> (CatalogHandle, LeafStateKey) {
+ /// `behavioral_hash` is the catalog's behavioral shape hash for the cohort, `None` for one it
+ /// has not read yet.
+ fn cohort_filters(single_leaf: bool, behavioral_hash: Option<&str>) -> TeamFilters {
let values = if single_leaf {
vec![behavioral_leaf()]
} else {
@@ -1092,10 +1152,12 @@ mod tests {
builder
.add_cohort(CohortId(COHORT), TeamId(TEAM), &cohort)
.unwrap();
- builder.set_behavioral_shape_hash(
- CohortId(COHORT),
- BehavioralShapeHash::parse(SHAPE_HASH).unwrap(),
- );
+ if let Some(hash) = behavioral_hash {
+ builder.set_behavioral_shape_hash(
+ CohortId(COHORT),
+ BehavioralShapeHash::parse(hash).unwrap(),
+ );
+ }
if !single_leaf {
// A mixed cohort carries both guards, so either kind of run can reconcile it.
builder.set_person_shape_hash(
@@ -1103,13 +1165,20 @@ mod tests {
PersonShapeHash::parse(SHAPE_HASH).unwrap(),
);
}
- let filters = builder.freeze(UTC);
+ builder.freeze(UTC)
+ }
+
+ fn catalog(single_leaf: bool) -> (Arc<CatalogHandle>, LeafStateKey) {
+ catalog_over(cohort_filters(single_leaf, Some(SHAPE_HASH)))
+ }
+
+ fn catalog_over(filters: TeamFilters) -> (Arc<CatalogHandle>, LeafStateKey) {
let lsk = filters.by_condition_to_lsk[&BEHAVIORAL_HASH][0];
(handle_for(filters), lsk)
}
/// A person-only cohort: no behavioral leaf, so only the person guard fences its reconcile.
- fn person_catalog() -> (CatalogHandle, LeafStateKey) {
+ fn person_catalog() -> (Arc<CatalogHandle>, LeafStateKey) {
let cohort = json!({ "properties": { "type": "AND", "values": [person_leaf()] } });
let mut builder = TeamFiltersBuilder::default();
builder
@@ -1125,15 +1194,23 @@ mod tests {
)
}
- fn handle_for(filters: TeamFilters) -> CatalogHandle {
- CatalogHandle::from_catalog(FilterCatalog::from_teams([(TeamId(TEAM), filters)]))
+ fn unloaded() -> Arc<CatalogHandle> {
+ Arc::new(CatalogHandle::new())
+ }
+
+ fn team_catalog(filters: TeamFilters) -> FilterCatalog {
+ FilterCatalog::from_teams([(TeamId(TEAM), filters)])
+ }
+
+ fn handle_for(filters: TeamFilters) -> Arc<CatalogHandle> {
+ Arc::new(CatalogHandle::from_catalog(team_catalog(filters)))
}
struct DrainShell {
_dir: TempDir,
store: CohortStore,
handle: StoreHandle,
- catalog: CatalogHandle,
+ catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
markers: CaptureReconcileMarkerSink,
deps: MergeWorkerDeps,
@@ -1160,7 +1237,7 @@ mod tests {
}
fn over(
- (catalog, lsk): (CatalogHandle, LeafStateKey),
+ (catalog, lsk): (Arc<CatalogHandle>, LeafStateKey),
sink: Arc<dyn MembershipSink>,
cascade_sink: CaptureCascadeSink,
scan_page: usize,
@@ -1175,8 +1252,12 @@ mod tests {
deps.cascade_sink = Arc::new(cascade_sink);
let markers = CaptureReconcileMarkerSink::new();
deps.reconcile.marker_sink = Arc::new(markers.clone());
- let queue =
- ReconcileQueue::new(PARTITION, deps.reconcile.backlog.clone(), handle.clone());
+ let queue = ReconcileQueue::new(
+ PARTITION,
+ deps.reconcile.backlog.clone(),
+ handle.clone(),
+ catalog.clone(),
+ );
Self {
_dir,
store,
@@ -1287,7 +1368,6 @@ mod tests {
handle_reconcile_drain(
PARTITION,
&self.handle,
- &self.catalog,
&self.sink,
&self.deps,
&mut self.queue,
@@ -1326,7 +1406,8 @@ mod tests {
tracker.mark_dispatched(3, 11);
{
- let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store));
+ let mut queue =
+ ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
queue.enqueue(tile(1, 7, 1), tracker.defer(3, 10));
assert_eq!(queue.len(), 1);
assert_eq!(backlog.len(), 1);
@@ -1350,7 +1431,7 @@ 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));
+ let mut queue = ReconcileQueue::new(PARTITION, backlog, store_handle(&store), unloaded());
queue.enqueue(tile(TEAM, COHORT, 1), tracker.defer(PARTITION as i32, 10));
queue.enqueue(
tile(TEAM, COHORT + 1, 2),
@@ -1415,7 +1496,7 @@ 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));
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
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));
@@ -1445,7 +1526,7 @@ 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));
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
queue.enqueue(
scoped_tile(TEAM, COHORT, 1, ScopeKind::Behavioral),
tracker.defer(3, 10),
@@ -1494,7 +1575,7 @@ 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));
+ let mut queue = ReconcileQueue::new(3, backlog.clone(), store_handle(&store), unloaded());
queue.enqueue(tile(1, 7, 2), tracker.defer(3, 15));
for replayed_offset in [10, 15] {
@@ -1618,36 +1699,38 @@ mod tests {
filters
}
+ fn verdict(
+ filters: TeamFilters,
+ tile: &ReconcileTile,
+ ) -> Result<CohortEligibility, ReconcileDiscardReason> {
+ catalog_verdict(Some(&Arc::new(filters)), tile).map(|(_, eligibility)| eligibility)
+ }
+
#[test]
- fn drain_guard_classifies_every_retry_discard_and_proceed_state() {
+ fn catalog_verdict_names_every_discard_reason_and_proves_what_proceeds() {
let reconcile = tile(TEAM, COHORT, 1);
assert_eq!(
- evaluate_guard(false, None, &reconcile),
- ReconcileGuard::Retry(ReconcileRetryReason::CatalogNotLoaded),
+ catalog_verdict(None, &reconcile).map(|(_, eligibility)| eligibility),
+ Err(ReconcileDiscardReason::TeamAbsent),
);
assert_eq!(
- evaluate_guard(true, None, &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::TeamAbsent),
- );
- assert_eq!(
- evaluate_guard(true, Some(&TeamFilters::default()), &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent),
+ verdict(TeamFilters::default(), &reconcile),
+ Err(ReconcileDiscardReason::CohortAbsent),
);
let behavioral_guard = &[(ScopeKind::Behavioral, SHAPE_HASH)];
- let missing_eligibility = guard_filters(None, behavioral_guard);
assert_eq!(
- evaluate_guard(true, Some(&missing_eligibility), &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::CohortAbsent),
+ verdict(guard_filters(None, behavioral_guard), &reconcile),
+ Err(ReconcileDiscardReason::CohortAbsent),
);
let excluded = guard_filters(
Some(CohortEligibility::Excluded(ExcludedReason::HasDroppedLeaf)),
behavioral_guard,
);
assert_eq!(
- evaluate_guard(true, Some(&excluded), &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::NotEmitting),
+ verdict(excluded, &reconcile),
+ Err(ReconcileDiscardReason::NotEmitting),
);
for eligibility in [
@@ -1655,10 +1738,12 @@ mod tests {
CohortEligibility::Stage2Composable,
CohortEligibility::Stage2ComposableRef,
] {
- let filters = guard_filters(Some(eligibility), behavioral_guard);
assert_eq!(
- evaluate_guard(true, Some(&filters), &reconcile),
- ReconcileGuard::Proceed,
+ verdict(
+ guard_filters(Some(eligibility), behavioral_guard),
+ &reconcile
+ ),
+ Ok(eligibility),
"{eligibility:?} registers membership",
);
}
@@ -1673,41 +1758,206 @@ mod tests {
] {
let reconcile = scoped_tile(TEAM, COHORT, 1, guard);
assert_eq!(
- evaluate_guard(
- true,
- Some(&guard_filters(emitting, &[(guard, SHAPE_HASH)])),
- &reconcile,
- ),
- ReconcileGuard::Proceed,
+ verdict(guard_filters(emitting, &[(guard, SHAPE_HASH)]), &reconcile),
+ Ok(CohortEligibility::Stage2Composable),
"{guard} matches its own map",
);
assert_eq!(
- evaluate_guard(
- true,
- Some(&guard_filters(emitting, &[(guard, "shape-v2")])),
- &reconcile,
- ),
- ReconcileGuard::Discard(ReconcileDiscardReason::HashMismatch),
+ verdict(guard_filters(emitting, &[(guard, "shape-v2")]), &reconcile),
+ Err(ReconcileDiscardReason::HashMismatch),
"{guard} diverged",
);
assert_eq!(
- evaluate_guard(true, Some(&guard_filters(emitting, &[])), &reconcile),
- ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
+ verdict(guard_filters(emitting, &[]), &reconcile),
+ Err(ReconcileDiscardReason::HashUnknown),
"{guard} has no persisted hash",
);
// The catalog carries only the *other* kind's hash, at the very value the tile pins.
assert_eq!(
- evaluate_guard(
- true,
- Some(&guard_filters(emitting, &[(other, SHAPE_HASH)])),
- &reconcile,
- ),
- ReconcileGuard::Discard(ReconcileDiscardReason::HashUnknown),
+ verdict(guard_filters(emitting, &[(other, SHAPE_HASH)]), &reconcile),
+ Err(ReconcileDiscardReason::HashUnknown),
"{guard} must not be satisfied by the {other} map",
);
}
}
+ /// The guard's decision without the filters it carries, so cases compare by value.
+ #[derive(Debug, PartialEq, Eq)]
+ enum Fate {
+ Proceed(CohortEligibility),
+ Retry(ReconcileRetryReason),
+ Discard(ReconcileDiscardReason),
+ }
+
+ impl From<ReconcileGuard> for Fate {
+ fn from(guard: ReconcileGuard) -> Self {
+ match guard {
+ ReconcileGuard::Proceed { eligibility, .. } => Self::Proceed(eligibility),
+ ReconcileGuard::Retry(reason) => Self::Retry(reason),
+ ReconcileGuard::Discard(reason) => Self::Discard(reason),
+ }
+ }
+ }
+
+ #[derive(Debug, Clone, Copy)]
+ enum Freshness {
+ NotLoaded,
+ RefreshedBeforeAdmission,
+ RefreshedAfterAdmission,
+ }
+
+ /// What the refresh the case publishes holds for the job's cohort.
+ #[derive(Debug, Clone, Copy)]
+ enum Snapshot {
+ Emitting,
+ MissingTeam,
+ }
+
+ impl Snapshot {
+ fn catalog(self) -> FilterCatalog {
+ match self {
+ Self::Emitting => team_catalog(guard_filters(
+ Some(CohortEligibility::Stage2Composable),
+ &[(ScopeKind::Behavioral, SHAPE_HASH)],
+ )),
+ Self::MissingTeam => FilterCatalog::from_teams([]),
+ }
+ }
+ }
+
+ #[test]
+ fn a_catalog_miss_discards_only_against_a_refresh_begun_after_admission() {
+ let reconcile = tile(TEAM, COHORT, 1);
+ let team_absent = ReconcileDiscardReason::TeamAbsent;
+ let cases = [
+ // Nothing is published before the first load, so the snapshot kind does not matter.
+ (
+ Freshness::NotLoaded,
+ Snapshot::MissingTeam,
+ Fate::Retry(ReconcileRetryReason::CatalogNotLoaded),
+ ),
+ (
+ Freshness::RefreshedBeforeAdmission,
+ Snapshot::Emitting,
+ Fate::Proceed(CohortEligibility::Stage2Composable),
+ ),
+ (
+ Freshness::RefreshedBeforeAdmission,
+ Snapshot::MissingTeam,
+ Fate::Retry(ReconcileRetryReason::AwaitingRefresh(team_absent)),
+ ),
+ (
+ Freshness::RefreshedAfterAdmission,
+ Snapshot::Emitting,
+ Fate::Proceed(CohortEligibility::Stage2Composable),
+ ),
+ (
+ Freshness::RefreshedAfterAdmission,
+ Snapshot::MissingTeam,
+ Fate::Discard(team_absent),
+ ),
+ ];
+
+ for (freshness, snapshot, expected) in cases {
+ let catalog = CatalogHandle::new();
+ let admitted_after = match freshness {
+ Freshness::NotLoaded => catalog.last_begun(),
+ Freshness::RefreshedBeforeAdmission => {
+ catalog.publish(snapshot.catalog());
+ catalog.last_begun()
+ }
+ Freshness::RefreshedAfterAdmission => {
+ let admitted_after = catalog.last_begun();
+ catalog.publish(snapshot.catalog());
+ admitted_after
+ }
+ };
+
+ assert_eq!(
+ Fate::from(evaluate_guard(&catalog.view(), admitted_after, &reconcile)),
+ expected,
+ "{freshness:?} with {snapshot:?}",
+ );
+ }
+ }
+
+ fn counted(metrics: &metrics_exporter_prometheus::PrometheusHandle, series: &str) -> u64 {
+ metrics
+ .render()
+ .lines()
+ .filter(|line| !line.starts_with('#'))
+ .find(|line| series.split(',').all(|part| line.contains(part)))
+ .and_then(|line| line.rsplit(' ').next())
+ .map_or(0, |count| count.parse().unwrap())
+ }
+
+ /// A run's reconcile can reach the processor before the catalog refresh that reads the run's
+ /// pinned hash. The job waits with its seed offset held, and the next refresh decides it.
+ #[tokio::test]
+ async fn a_reconcile_that_beats_its_catalog_refresh_waits_for_the_next_one() {
+ for (refreshed_hash, completes) in [(SHAPE_HASH, true), ("shape-v2", false)] {
+ let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder();
+ let metrics = recorder.handle();
+ let _local = metrics::set_default_local_recorder(&recorder);
+ let mut shell = DrainShell::over(
+ catalog_over(cohort_filters(true, None)),
+ Arc::new(CaptureSink::new()),
+ CaptureCascadeSink::new(),
+ 8,
+ );
+ // A refresh in flight at admission may have read Postgres before the run's write, so
+ // its snapshot cannot discard the job either.
+ let catalog = shell.catalog.clone();
+ let in_flight = catalog.begin_refresh();
+ shell.enqueue(tile(TEAM, COHORT, 1), 5);
+ in_flight.publish(team_catalog(cohort_filters(true, None)));
+
+ shell.tick().await;
+ shell.tick().await;
+ assert!(shell.markers.markers().is_empty(), "{refreshed_hash}");
+ assert_eq!(shell.queue.len(), 1, "the job waits for the next refresh");
+ assert_eq!(
+ shell.committable(),
+ Some(5),
+ "its seed offset stays deferred"
+ );
+ assert_eq!(
+ counted(
+ &metrics,
+ "cohort_reconcile_jobs_deferred_total,reason=\"hash_unknown\""
+ ),
+ 1,
+ "a wait over several ticks counts once",
+ );
+
+ shell
+ .catalog
+ .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();
+ if completes {
+ assert_eq!(markers, vec![RunId(Uuid::from_u128(1))]);
+ } else {
+ assert!(markers.is_empty(), "a superseded run still fails closed");
+ assert_eq!(
+ counted(
+ &metrics,
+ "cohort_reconcile_jobs_discarded_total,reason=\"hash_mismatch\""
+ ),
+ 1,
+ );
+ }
+ assert!(shell.queue.front().is_none(), "{refreshed_hash}");
+ assert_eq!(shell.committable(), Some(6), "{refreshed_hash}");
+ }
+ }
+
#[tokio::test]
async fn drain_emits_the_full_snapshot_fixes_only_flips_and_paginates() {
let sink = CaptureSink::new();
@@ -2006,6 +2256,9 @@ mod tests {
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.tick().await;
diff --git a/rust/cohort-stream-processor/src/workers/seed_path.rs b/rust/cohort-stream-processor/src/workers/seed_path.rs
index cccd1fad95b6..b03093523a1b 100644
--- a/rust/cohort-stream-processor/src/workers/seed_path.rs
+++ b/rust/cohort-stream-processor/src/workers/seed_path.rs
@@ -1777,11 +1777,11 @@ mod tests {
/// The same cohort shape under two teams, so a run can span them.
fn with_two_teams(cohorts: Vec<(i32, Value)>) -> Self {
- let mut shell = Self::new(cohorts.clone());
- shell.catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([
+ let shell = Self::new(cohorts.clone());
+ shell.catalog.publish(FilterCatalog::from_teams([
(TEAM, build_filters_for(TEAM, cohorts.clone(), UTC)),
(OTHER_TEAM, build_filters_for(OTHER_TEAM, cohorts, New_York)),
- ])));
+ ]));
shell
}
@@ -1853,8 +1853,12 @@ mod tests {
person_seed: crate::workers::PersonSeedDeps::default(),
seed_budget: crate::workers::seed_run::RunBudget::default(),
};
- let reconcile_queue =
- ReconcileQueue::new(0, deps.reconcile.backlog.clone(), handle.clone());
+ let reconcile_queue = ReconcileQueue::new(
+ 0,
+ deps.reconcile.backlog.clone(),
+ handle.clone(),
+ catalog.clone(),
+ );
Self {
_dir,
store,
@@ -1924,8 +1928,12 @@ mod tests {
self.deps.transfer_tracker = Arc::new(OffsetTracker::new());
self.deps.cascade_tracker = Arc::new(OffsetTracker::new());
self.queue = EvictionQueue::new();
- self.reconcile_queue =
- ReconcileQueue::new(0, self.deps.reconcile.backlog.clone(), self.handle.clone());
+ self.reconcile_queue = ReconcileQueue::new(
+ 0,
+ self.deps.reconcile.backlog.clone(),
+ self.handle.clone(),
+ self.catalog.clone(),
+ );
}
/// Drain the queued reconcile to completion, one page per tick, the way the worker does.
@@ -1939,7 +1947,6 @@ mod tests {
crate::workers::reconcile::handle_reconcile_drain(
partition_id,
&self.handle,
- &self.catalog,
&sink,
&self.deps,
&mut self.reconcile_queue,
@@ -3242,10 +3249,9 @@ mod tests {
CohortId(1),
BehavioralShapeHash::parse("0123456789abcdef").unwrap(),
);
- shell.catalog = Arc::new(CatalogHandle::from_catalog(FilterCatalog::from_teams([(
- TEAM,
- builder.freeze(UTC),
- )])));
+ shell
+ .catalog
+ .publish(FilterCatalog::from_teams([(TEAM, builder.freeze(UTC))]));
let tile = tile_for(person, today(), 1);
shell
diff --git a/rust/cohort-stream-processor/src/workers/worker.rs b/rust/cohort-stream-processor/src/workers/worker.rs
index d0d63034be84..13b5b4396f71 100644
--- a/rust/cohort-stream-processor/src/workers/worker.rs
+++ b/rust/cohort-stream-processor/src/workers/worker.rs
@@ -25,6 +25,7 @@ use uuid::Uuid;
use crate::cascade::{first_cascade, CascadeMessage};
use crate::consumers::events::CohortStreamEvent;
+use crate::consumers::readiness::RebuildGuard;
use crate::consumers::seeds::{ConsumedSeed, SeedWork};
use crate::filters::manager::CatalogHandle;
use crate::filters::reverse_index::TeamFilters;
@@ -74,6 +75,14 @@ pub struct Stage1Worker {
handle: JoinHandle<()>,
}
+/// Whether a spawning worker rebuilds its `EvictionQueue` from `cf_behavioral`, so a dormant
+/// person's `Left` still fires after a restart. A rebuild needs a [`RebuildGuard`], so the readiness
+/// gate counts every rebuild that runs.
+pub enum EvictionRestore {
+ Skip,
+ Rebuild(RebuildGuard),
+}
+
impl Stage1Worker {
/// Spawn with event-name gating disabled. The gating-aware variant is [`Self::spawn_with_gating`].
#[allow(clippy::too_many_arguments)]
@@ -85,7 +94,7 @@ impl Stage1Worker {
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
merge: Arc<MergeWorkerDeps>,
- durable_restore: bool,
+ restore: EvictionRestore,
) -> Self {
Self::spawn_with_gating(
partition_id,
@@ -95,13 +104,11 @@ impl Stage1Worker {
sink,
tracker,
merge,
- durable_restore,
+ restore,
EventNameGating::Disabled,
)
}
- /// When `durable_restore` is on, re-seeds the `EvictionQueue` from `cf_behavioral` on spawn so a
- /// dormant person's `Left` still fires after a crash-restart.
#[allow(clippy::too_many_arguments)]
pub fn spawn_with_gating(
partition_id: u16,
@@ -111,7 +118,7 @@ impl Stage1Worker {
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
merge: Arc<MergeWorkerDeps>,
- durable_restore: bool,
+ restore: EvictionRestore,
event_name_gating: EventNameGating,
) -> Self {
let handle = tokio::spawn(run_worker(
@@ -122,7 +129,7 @@ impl Stage1Worker {
sink,
tracker,
merge,
- durable_restore,
+ restore,
event_name_gating,
));
Self {
@@ -169,7 +176,7 @@ async fn run_worker(
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
merge: Arc<MergeWorkerDeps>,
- durable_restore: bool,
+ restore: EvictionRestore,
event_name_gating: EventNameGating,
) {
info!(partition_id, "stage 1 worker started");
@@ -180,10 +187,16 @@ async fn run_worker(
partition_id,
merge.reconcile.backlog.clone(),
handle.clone(),
+ catalog.clone(),
);
- // No-op for a cold partition (bloom-filtered scan finds nothing to schedule).
- if durable_restore {
- rebuild_eviction_queue(partition_id, &handle, &mut queue).await;
+ // 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.
+ match restore {
+ EvictionRestore::Skip => {}
+ EvictionRestore::Rebuild(rebuilding) => {
+ rebuild_eviction_queue(partition_id, &handle, &mut queue).await;
+ drop(rebuilding);
+ }
}
// In-memory resume cursors; loss on rebalance is benign (GC re-scans from the start).
let mut gc_cursor = MergeGcCursor::default();
@@ -490,7 +503,6 @@ async fn run_worker(
handle_reconcile_drain(
partition_id,
&handle,
- &catalog,
&sink,
&merge,
&mut reconcile_queue,
@@ -1326,7 +1338,7 @@ mod tombstone_redirect_tests {
Arc::new(membership.clone()),
events_tracker.clone(),
merge,
- false,
+ EvictionRestore::Skip,
);
seed_tx.send(consumed_reconcile(tile, 5)).await.unwrap();
drop(seed_tx);
@@ -1502,7 +1514,7 @@ mod tombstone_redirect_tests {
Arc::new(membership.clone()),
tracker.clone(),
merge,
- false,
+ EvictionRestore::Skip,
);
tracker.mark_dispatched(partition_id as i32, dispatched);
for seed in seeds {
diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rs
index e0ca292507e4..b01d54960896 100644
--- a/rust/cohort-stream-processor/tests/events_consumer.rs
+++ b/rust/cohort-stream-processor/tests/events_consumer.rs
@@ -10,14 +10,15 @@
//!
//! The S3/PVC disaster-recovery e2e
//! ([`s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant_left`]) additionally
-//! needs an S3-compatible store (MinIO / SeaweedFS). Point it at one with:
+//! needs an S3-compatible store. The compose stack's SeaweedFS (`objectstorage`) serves one:
//!
//! ```sh
//! export KAFKA_HOSTS=localhost:9092
-//! export CHECKPOINT_S3_ENDPOINT=http://localhost:19000 # MinIO; or :8333 for SeaweedFS
-//! export CHECKPOINT_S3_BUCKET=cohort-checkpoints # must already exist
-//! export CHECKPOINT_S3_ACCESS_KEY_ID=... # MinIO/SeaweedFS creds
-//! export CHECKPOINT_S3_SECRET_ACCESS_KEY=...
+//! export CHECKPOINT_S3_ENDPOINT=http://localhost:19000
+//! export CHECKPOINT_S3_REGION=us-east-1
+//! export CHECKPOINT_S3_BUCKET=posthog
+//! export CHECKPOINT_S3_ACCESS_KEY_ID=object_storage_root_user
+//! export CHECKPOINT_S3_SECRET_ACCESS_KEY=object_storage_root_password
//! cargo test -p cohort-stream-processor --test events_consumer -- --ignored s3_restore
//! ```
//!
@@ -35,7 +36,9 @@ use std::time::{Duration, Instant};
use async_trait::async_trait;
use chrono_tz::UTC;
use cohort_stream_processor::config::Config;
-use cohort_stream_processor::consumers::{CohortStreamEventsConsumer, EventDispatcher};
+use cohort_stream_processor::consumers::{
+ BootReadiness, CohortStreamEventsConsumer, EventDispatcher,
+};
use cohort_stream_processor::filters::{
CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
};
@@ -48,8 +51,8 @@ use cohort_stream_processor::producer::{
};
use cohort_stream_processor::stage1::{Stage1State, StatefulRecord};
use cohort_stream_processor::store::durability::{
- run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,
- RestoreSource, S3Uploader,
+ run_boot_restore, store_hash_prefix, upload_cadence, CheckpointExporter, CheckpointSweeper,
+ OffsetManifest, RestoreSource, S3Uploader,
};
use cohort_stream_processor::store::{
BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,
@@ -66,7 +69,7 @@ fn test_handle(store: &CohortStore) -> StoreHandle {
},
)
}
-use cohort_stream_processor::workers::{MergeWorkerDeps, Stage1Worker};
+use cohort_stream_processor::workers::{EvictionRestore, MergeWorkerDeps, Stage1Worker};
use common_kafka::config::KafkaConfig;
use common_kafka::kafka_producer::KafkaProduceError;
use envconfig::Envconfig;
@@ -208,6 +211,33 @@ async fn produce_events(topic: &str) -> usize {
total
}
+/// Persons that first appear after a restart, in the durable-restart test.
+const NEW_PERSONS: u128 = 50;
+
+/// One matching `$pageview` each for `count` persons after the [`PERSONS`] that [`produce_events`]
+/// writes, at source offsets past its own. Returns the total produced.
+async fn produce_new_persons(topic: &str, count: u128) -> usize {
+ let producer: FutureProducer = ClientConfig::new()
+ .set("bootstrap.servers", bootstrap_servers())
+ .set("message.timeout.ms", "10000")
+ .create()
+ .expect("create producer");
+ let first_offset = (PERSONS as usize * EVENTS_PER_PERSON) as i64;
+ for n in 1..=count {
+ let p = person(PERSONS + n);
+ let key = format!("{TEAM}:{p}");
+ let payload = envelope(p, 0, first_offset + n as i64);
+ producer
+ .send(
+ FutureRecord::to(topic).key(&key).payload(&payload),
+ Timeout::After(Duration::from_secs(10)),
+ )
+ .await
+ .expect("produce event");
+ }
+ count as usize
+}
+
struct NoopMirror;
impl PartitionMirror for NoopMirror {
@@ -224,7 +254,7 @@ fn build_consumer(
sink: Arc<dyn MembershipSink>,
offset_commit_interval: Duration,
) -> CohortStreamEventsConsumer {
- build_consumer_with_restore(
+ let (consumer, _dispatcher) = build_consumer_with_restore(
topic,
group,
store,
@@ -233,7 +263,9 @@ fn build_consumer(
sink,
offset_commit_interval,
false,
- )
+ 100,
+ );
+ consumer
}
#[allow(clippy::too_many_arguments)]
@@ -246,7 +278,8 @@ fn build_consumer_with_restore(
sink: Arc<dyn MembershipSink>,
offset_commit_interval: Duration,
durable_restore: bool,
-) -> CohortStreamEventsConsumer {
+ recv_batch_size: usize,
+) -> (CohortStreamEventsConsumer, Arc<EventDispatcher>) {
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
Arc::new(OffsetTracker::new()),
@@ -281,18 +314,19 @@ fn build_consumer_with_restore(
handle.shutdown_token(),
));
- CohortStreamEventsConsumer::new(
+ let events_consumer = CohortStreamEventsConsumer::new(
Arc::new(consumer),
topic.to_string(),
- dispatcher,
+ dispatcher.clone(),
handle,
- 100,
+ recv_batch_size,
Duration::from_millis(200),
offset_commit_interval,
NUM_PARTITIONS as usize,
consumer_command_rx,
None,
- )
+ );
+ (events_consumer, dispatcher)
}
/// The `murmur2_random` partitioner must match production for keyed co-partitioning.
@@ -925,7 +959,7 @@ async fn cooperative_sticky_migration_preserves_offsets_and_partition_colocation
// Batch 1: only A is up.
let batch1 = produce_events(&topic).await;
- let consumer_a = build_consumer(
+ let (consumer_a, dispatcher_a) = build_consumer_with_restore(
&topic,
&group,
store_a.clone(),
@@ -933,12 +967,14 @@ async fn cooperative_sticky_migration_preserves_offsets_and_partition_colocation
handle_a,
sink_a.clone(),
Duration::from_millis(250),
+ false,
+ 100,
);
let task_a = tokio::spawn(consumer_a.process());
wait_for_committed(&verifier, &topic, batch1 as i64, Duration::from_secs(60)).await;
// B joins → cooperative-sticky moves ~half the partitions off A.
- let consumer_b = build_consumer(
+ let (consumer_b, dispatcher_b) = build_consumer_with_restore(
&topic,
&group,
store_b.clone(),
@@ -946,9 +982,33 @@ async fn cooperative_sticky_migration_preserves_offsets_and_partition_colocation
handle_b,
sink_b.clone(),
Duration::from_millis(250),
+ false,
+ 100,
);
let task_b = tokio::spawn(consumer_b.process());
+ // A revoke deletes the slice and hands nothing over. If A folds and commits a batch-2 event
+ // before its partition moves to B, neither pod holds that person afterwards. So batch 2 waits
+ // for a stable, disjoint, full split, and each event lands on its final owner.
+ let start = Instant::now();
+ loop {
+ let a = dispatcher_a.owned_set();
+ let b = dispatcher_b.owned_set();
+ if !b.is_empty() && a.is_disjoint(&b) && a.len() + b.len() == NUM_PARTITIONS as usize {
+ tokio::time::sleep(Duration::from_millis(750)).await;
+ if dispatcher_a.owned_set() == a && dispatcher_b.owned_set() == b {
+ break;
+ }
+ }
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "timed out waiting for the cooperative split to settle (a={}, b={})",
+ a.len(),
+ b.len(),
+ );
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+
// Batch 2: split across both pods.
let batch2 = produce_events(&topic).await;
let total = (batch1 + batch2) as i64;
@@ -1013,7 +1073,9 @@ async fn reopen_store_live(path: std::path::PathBuf) -> CohortStore {
/// End-to-end through a real broker: a durable-restore consumer folds every person in and
/// fsync-commits; the store is reopened live (no wipe) and must (i) lose no Kafka offsets, (ii)
/// preserve every member's state — a wipe+replay would be empty, since the committed offset already
-/// covers every event — and (iii) fire each now-dormant member's `Left` from the rebuilt queue.
+/// covers every event — (iii) fold every event that arrived while it was down, including the ones
+/// polled during boot recovery, and (iv) fire each now-dormant member's `Left` from the rebuilt
+/// queue.
///
/// This is the graceful-restart shape. The hard-crash hazard (a committed offset ahead of un-fsync'd
/// state) needs a separately killed process to observe `committed > durable`; a graceful in-process
@@ -1056,7 +1118,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
);
let shutdown_handle = handle.clone();
let _monitor = manager.monitor_background();
- let consumer = build_consumer_with_restore(
+ let (consumer, _dispatcher) = build_consumer_with_restore(
&topic,
&group,
store.clone(),
@@ -1065,6 +1127,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
Arc::new(CaptureSink::new()),
Duration::from_millis(250),
true,
+ 100,
);
let task = tokio::spawn(consumer.process());
@@ -1098,9 +1161,47 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
"no Kafka loss: committed offsets are unchanged across the restart",
);
+ // --- Tenure 2: events that arrived while the pod was down. A 10-event batch makes boot
+ // recovery span several polls, so the polls it holds back carry events that must fold later. ---
+ let total = total + produce_new_persons(&topic, NEW_PERSONS).await;
+ {
+ let mut manager = Manager::builder("durable-itest-2")
+ .with_trap_signals(false)
+ .build();
+ let handle = manager.register(
+ "consumer",
+ ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(15)),
+ );
+ let shutdown_handle = handle.clone();
+ let _monitor = manager.monitor_background();
+ let (consumer, _dispatcher) = build_consumer_with_restore(
+ &topic,
+ &group,
+ store2.clone(),
+ behavioral_catalog(),
+ handle,
+ Arc::new(CaptureSink::new()),
+ Duration::from_millis(250),
+ true,
+ 10,
+ );
+ let task = tokio::spawn(consumer.process());
+ wait_for_committed(&verifier, &topic, total as i64, Duration::from_secs(60)).await;
+ shutdown_handle.request_shutdown();
+ task.await.expect("tenure-2 consumer panicked");
+ }
+ let persons = (PERSONS + NEW_PERSONS) as usize;
+ assert_eq!(
+ entered_persons_range(&store2, lsk, persons),
+ persons,
+ "tenure 2 folded every event that arrived during the downtime",
+ );
+ assert_eq!(committed_sum(&verifier, &topic), total as i64);
+
// --- Dormant Left: durable workers re-seed queues from cf_behavioral; a sweep past the window
// evicts each member with no new events. ---
let catalog = Arc::new(behavioral_catalog());
+ let readiness = BootReadiness::new(catalog.clone());
let sink = Arc::new(CaptureSink::new());
let far_future = 4_000_000_000_000i64; // ~year 2096, well past every BASE_TS + 7d deadline
for partition in 0..NUM_PARTITIONS {
@@ -1114,7 +1215,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
sink.clone(),
Arc::new(OffsetTracker::new()),
MergeWorkerDeps::capture(),
- true,
+ EvictionRestore::Rebuild(readiness.rebuild_started()),
);
tx.send(vec![ShuffleMessage::Sweep {
due_before_ms: far_future,
@@ -1130,7 +1231,7 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
.filter(|change| change.status == MembershipStatus::Left)
.count();
assert_eq!(
- lefts, PERSONS as usize,
+ lefts, persons,
"every restored-then-dormant member emits a Left from the rebuilt eviction queue",
);
@@ -1294,11 +1395,15 @@ async fn delete_s3_prefix(config: &Config) {
Ok(store) => store,
Err(_) => return,
};
- let prefix = ObjPath::from(d.s3_key_prefix.as_str());
- let mut stream = store.list(Some(&prefix));
- while let Some(entry) = stream.next().await {
- if let Ok(meta) = entry {
- let _result = store.delete(&meta.location).await;
+ // Checkpoint SSTs are keyed under `<hash>/<s3_key_prefix>/…`; metadata.json at the bare prefix.
+ let hashed = format!("{}/{}", store_hash_prefix(), d.s3_key_prefix);
+ for raw_prefix in [d.s3_key_prefix.as_str(), hashed.as_str()] {
+ let prefix = ObjPath::from(raw_prefix);
+ let mut stream = store.list(Some(&prefix));
+ while let Some(entry) = stream.next().await {
+ if let Ok(meta) = entry {
+ let _result = store.delete(&meta.location).await;
+ }
}
}
}
@@ -1347,7 +1452,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
);
let shutdown_handle = handle.clone();
let _monitor = manager.monitor_background();
- let consumer = build_consumer_with_restore(
+ let (consumer, _dispatcher) = build_consumer_with_restore(
&topic,
&group,
store.clone(),
@@ -1356,6 +1461,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
Arc::new(CaptureSink::new()),
Duration::from_millis(250),
true,
+ 100,
);
let task = tokio::spawn(consumer.process());
@@ -1483,6 +1589,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
// (c) Dormant Left: workers re-seed the eviction queue from the restored cf_behavioral, then a sweep
// past the window evicts every now-dormant member.
let catalog = Arc::new(behavioral_catalog());
+ let readiness = BootReadiness::new(catalog.clone());
let left_sink = Arc::new(CaptureSink::new());
let far_future = 4_000_000_000_000i64; // ~year 2096, past every BASE_TS + 7d deadline
for partition in 0..NUM_PARTITIONS {
@@ -1496,7 +1603,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
left_sink.clone(),
Arc::new(OffsetTracker::new()),
MergeWorkerDeps::capture(),
- true,
+ EvictionRestore::Rebuild(readiness.rebuild_started()),
);
tx.send(vec![ShuffleMessage::Sweep {
due_before_ms: far_future,
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
index 46ee59d06b9d..17244b0aae0f 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -1,16 +1,18 @@
//! End-to-end durability test: the four merge CFs (`cf_pending_transfers`, `cf_merge_drains_applied`,
//! `cf_merge_applied`, `cf_merge_tombstones`) plus the cascade's `cf_stage2` state survive a whole-DB
//! checkpoint → S3 disaster restore, against a real Kafka/Redpanda broker + S3-compatible store
-//! (MinIO / SeaweedFS), with the cascade gate on and a single-pod static-membership deploy.
+//! (the compose stack's SeaweedFS), with the cascade gate on and a single-pod static-membership
+//! deploy.
//!
//! `#[ignore]`d by default: needs a running broker + an S3-compatible store. Run serially:
//!
//! ```sh
//! export KAFKA_HOSTS=localhost:9092
-//! export CHECKPOINT_S3_ENDPOINT=http://localhost:19000 # MinIO; or :8333 for SeaweedFS
-//! export CHECKPOINT_S3_BUCKET=cohort-checkpoints # must already exist
-//! export CHECKPOINT_S3_ACCESS_KEY_ID=... # MinIO/SeaweedFS creds
-//! export CHECKPOINT_S3_SECRET_ACCESS_KEY=...
+//! export CHECKPOINT_S3_ENDPOINT=http://localhost:19000
+//! export CHECKPOINT_S3_REGION=us-east-1
+//! export CHECKPOINT_S3_BUCKET=posthog
+//! export CHECKPOINT_S3_ACCESS_KEY_ID=object_storage_root_user
+//! export CHECKPOINT_S3_SECRET_ACCESS_KEY=object_storage_root_password
//! cargo test -p cohort-stream-processor --test merge_durability -- --ignored --test-threads=1
//! ```
@@ -791,8 +793,6 @@ async fn spawn_instance(
RECV_TIMEOUT,
COMMIT_INTERVAL,
);
- tasks.push(tokio::spawn(merge_follower.process()));
-
let transfer_follower = FollowerConsumer::<TransferRoute>::new(
transfers_consumer,
topics.transfers.clone(),
@@ -802,8 +802,6 @@ async fn spawn_instance(
RECV_TIMEOUT,
COMMIT_INTERVAL,
);
- tasks.push(tokio::spawn(transfer_follower.process()));
-
let cascade_follower = FollowerConsumer::<CascadeRoute>::new(
cascade_consumer,
topics.cascade.clone(),
@@ -813,7 +811,16 @@ async fn spawn_instance(
RECV_TIMEOUT,
COMMIT_INTERVAL,
);
- tasks.push(tokio::spawn(cascade_follower.process()));
+ // The followers wait for boot recovery, as in the binary.
+ let readiness = dispatcher.readiness().clone();
+ tasks.push(tokio::spawn(async move {
+ readiness.wait_until_dispatchable().await;
+ tokio::join!(
+ merge_follower.process(),
+ transfer_follower.process(),
+ cascade_follower.process(),
+ );
+ }));
let events_consumer = CohortStreamEventsConsumer::new(
Arc::new(events_client),
@@ -1053,7 +1060,7 @@ async fn complete_cross_partition_merge(
}
#[tokio::test(flavor = "multi_thread")]
-#[ignore = "requires Kafka + MinIO; run with --ignored --test-threads=1"]
+#[ignore = "requires Kafka + an S3-compatible store (CHECKPOINT_S3_*); run with --ignored --test-threads=1"]
async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {
let suffix = Uuid::new_v4();
let topics = Topics::unique(&suffix);
diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rs
index 3a38631c2d16..765dc96ae57d 100644
--- a/rust/cohort-stream-processor/tests/stage1_worker.rs
+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs
@@ -37,7 +37,9 @@ use cohort_stream_processor::store::{
PersonRecordKey, PersonRecords, Stage2Key, StoreConfig, StoreHandle,
};
use cohort_stream_processor::workers::seed_run::RunBudget;
-use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, SkipReason, Stage1Worker};
+use cohort_stream_processor::workers::{
+ process_event, EvictionRestore, MergeWorkerDeps, SkipReason, Stage1Worker,
+};
use common_kafka::kafka_producer::KafkaProduceError;
use serde_json::{json, Value};
use tempfile::TempDir;
@@ -1181,7 +1183,7 @@ async fn spawned_worker_drains_a_batch_and_commits_state() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
dispatch_to_worker(&tracker, &tx, event(alice, 1, 0), 0).await;
@@ -1237,7 +1239,7 @@ async fn sub_batch_read_your_writes_survives_offload() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
// Same source coordinates (5, 0) make the second event an exact replay of the first; shipping
@@ -1298,7 +1300,7 @@ async fn spawned_worker_composes_two_leaf_cohort_and_emits_single_leaf_independe
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
// Event A flips only the behavioral leaf (non-matching email): the single-leaf cohort 2 enters,
@@ -1366,7 +1368,7 @@ async fn spawned_worker_skips_events_for_unknown_teams() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
// Skipped before touching the store, but the offset must still advance (no partition wedge).
@@ -1413,7 +1415,7 @@ async fn worker_produces_changes_and_advances_offset() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
dispatch_to_worker(&tracker, &tx, event(person(1), 1, 0), 5).await;
@@ -1456,7 +1458,7 @@ async fn worker_advances_offset_on_empty_transition_subbatch() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
let non_match = CohortStreamEvent {
@@ -1491,7 +1493,7 @@ async fn worker_holds_offset_when_the_only_flush_fails() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
dispatch_to_worker(&tracker, &tx, event(person(1), 1, 0), 10).await;
@@ -1522,7 +1524,7 @@ async fn worker_keeps_processing_after_a_produce_failure() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
dispatch_to_worker(&tracker, &tx, event(person(1), 1, 0), 10).await;
@@ -1961,7 +1963,7 @@ async fn daily_multiple_single_leaf_cohort_emits_entered_then_left_to_the_sink()
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
let alice = person(1);
@@ -2302,7 +2304,7 @@ async fn compressed_sweep_deletes_then_a_late_event_recreates_the_state() {
Arc::new(sink.clone()),
tracker.clone(),
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
let alice = person(1);
@@ -2587,7 +2589,7 @@ async fn every_queued_live_batch_is_served_before_a_waiting_seed_turn() {
Arc::new(sink.clone()),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
worker.join().await.unwrap();
@@ -2686,7 +2688,7 @@ async fn a_seed_backlog_is_served_in_run_sized_quanta() {
Arc::new(sink.clone()),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
worker.join().await.unwrap();
@@ -2760,7 +2762,7 @@ async fn a_live_batch_arriving_during_a_seed_backlog_is_served_before_the_next_s
Arc::new(sink),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
worker.join().await.unwrap();
@@ -2850,7 +2852,7 @@ async fn a_live_batch_arriving_mid_quantum_is_served_before_the_next_run() {
Arc::new(sink),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
worker.join().await.unwrap();
@@ -2900,7 +2902,7 @@ async fn a_closed_seed_lane_does_not_stall_the_live_lane() {
Arc::new(sink.clone()),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
// Let the worker observe the closed seed lane while the live lane is still open.
@@ -2965,7 +2967,7 @@ async fn both_lanes_drain_before_the_worker_exits() {
Arc::new(sink.clone()),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
worker.join().await.unwrap();
@@ -3014,7 +3016,7 @@ async fn a_failed_composed_seed_produce_replays_from_the_row_it_never_wrote() {
Arc::new(sink.clone()),
Arc::new(OffsetTracker::new()),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
deps.seed_tracker.mark_dispatched(PARTITION_ID as i32, 8);
seed_tx
@@ -3058,7 +3060,7 @@ async fn a_failed_composed_seed_produce_replays_from_the_row_it_never_wrote() {
Arc::new(replay_sink.clone()),
Arc::new(OffsetTracker::new()),
replay_deps.clone(),
- false,
+ EvictionRestore::Skip,
);
replay_deps
.seed_tracker
@@ -3125,7 +3127,7 @@ async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_
Arc::new(sink.clone()),
tracker.clone(),
deps.clone(),
- false,
+ EvictionRestore::Skip,
);
tracker.mark_dispatched(PARTITION_ID as i32, 1);
@@ -3187,7 +3189,7 @@ async fn seed_produce_failure_holds_only_the_seed_tracker_and_the_redelivery_re_
Arc::new(replay_sink.clone()),
replay_tracker.clone(),
replay_deps.clone(),
- false,
+ EvictionRestore::Skip,
);
replay_deps
.seed_tracker
@@ -3253,7 +3255,7 @@ async fn watermark_advances_only_after_a_successful_mark() {
Arc::new(sink),
tracker.clone(),
deps,
- false,
+ EvictionRestore::Skip,
);
tracker.mark_dispatched(PARTITION_ID as i32, 1);
tx.send(batch).await.unwrap();
diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rs
index e27246b75135..9d567fc65224 100644
--- a/rust/cohort-stream-processor/tests/sweep_worker.rs
+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs
@@ -20,7 +20,7 @@ use async_trait::async_trait;
use chrono_tz::America::New_York;
use chrono_tz::Asia::Kolkata;
use chrono_tz::{Tz, UTC};
-use cohort_stream_processor::consumers::{CohortStreamEvent, EventDispatcher};
+use cohort_stream_processor::consumers::{BootReadiness, CohortStreamEvent, EventDispatcher};
use cohort_stream_processor::filters::{
CatalogHandle, CohortId, FilterCatalog, TeamFilters, TeamFiltersBuilder, TeamId,
};
@@ -39,7 +39,9 @@ use cohort_stream_processor::store::{
BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, PersonRecordKey,
Stage2Key, StoreConfig, StoreHandle,
};
-use cohort_stream_processor::workers::{process_event, MergeWorkerDeps, Stage1Worker};
+use cohort_stream_processor::workers::{
+ process_event, EvictionRestore, MergeWorkerDeps, Stage1Worker,
+};
use common_kafka::kafka_producer::KafkaProduceError;
use serde_json::{json, Value};
use tempfile::TempDir;
@@ -288,7 +290,7 @@ fn spawn_worker(
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
- spawn_worker_with_restore(store, catalog, sink, tracker, false)
+ spawn_worker_with_restore(store, catalog, sink, tracker, EvictionRestore::Skip)
}
/// Like [`spawn_worker`] but with the durable-restart `EvictionQueue` rebuild on: the worker re-seeds
@@ -299,7 +301,14 @@ fn spawn_worker_durable(
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
- spawn_worker_with_restore(store, catalog, sink, tracker, true)
+ let rebuild = BootReadiness::new(catalog.clone()).rebuild_started();
+ spawn_worker_with_restore(
+ store,
+ catalog,
+ sink,
+ tracker,
+ EvictionRestore::Rebuild(rebuild),
+ )
}
/// Like [`spawn_worker`] but pinned to a given offload mode instead of the default `All`.
@@ -320,7 +329,7 @@ fn spawn_worker_with_mode(
sink,
tracker,
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
);
(tx, worker)
}
@@ -330,7 +339,7 @@ fn spawn_worker_with_restore(
catalog: Arc<CatalogHandle>,
sink: Arc<dyn MembershipSink>,
tracker: Arc<OffsetTracker>,
- durable_restore: bool,
+ restore: EvictionRestore,
) -> (mpsc::Sender<Vec<ShuffleMessage>>, Stage1Worker) {
let (tx, rx) = mpsc::channel(16);
let rx = WorkerInbox::live_only(rx);
@@ -342,7 +351,7 @@ fn spawn_worker_with_restore(
sink,
tracker,
MergeWorkerDeps::capture(),
- durable_restore,
+ restore,
);
(tx, worker)
}
@@ -371,7 +380,7 @@ fn spawn_worker_prefilled(
sink,
tracker,
MergeWorkerDeps::capture(),
- false,
+ EvictionRestore::Skip,
)
}