:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cohorts): record the split in checkpoints and restore by cover (#118892)
Matheus Batistab163637c325c
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.mdindex 8a2fe43ec5df..0f19693ff0c3 100644--- a/docs/internal/realtime-cohorts/processor-runtime.md+++ b/docs/internal/realtime-cohorts/processor-runtime.md@@ -185,7 +185,9 @@ State never moves between pods.A pod's store holds the slices of the partitions it owns, and nothing hands a slice to another pod.The store records the split it was written under in `cf_meta[pod_partitions]`: the pod count, the ordinal and the partition count.A store from before that record takes the configured split as its own the first time it opens.-A store written under another split refuses to open, so the pod crash-loops instead of reading slices that another pod may have changed since.+A split covers another when it owns every partition the other owns.+A store written under a split that covers the pod's opens and records the pod's split.+A store written under any other split refuses to open, so the pod crash-loops instead of reading slices that another pod may have changed since.With durable restore enabled, boot deletes the slices of partitions the pod does not own, so a single pod deletes nothing.The store record cannot stop a pod on an empty volume, so the **ownership fence** keeps a second record on the broker.@@ -209,13 +211,12 @@ Builds from before stamps commit without one, so the fence cannot see them eitheChange `COHORT_POD_COUNT` only after every pod runs a build with stamps.So changing `COHORT_POD_COUNT` requires wiping every store, including the volume of an ordinal that a scale-down removed.-That volume keeps its old record, so when a later change brings that split back, it opens with slices another pod has moved past.-With checkpoints enabled, also delete every pod's checkpoints, local and in S3.-A checkpoint from the old split restores and then refuses to open, so every boot fails the same way.+That volume keeps its old record, so when a later change brings back that split or one it covers, it opens with slices another pod has moved past.+With checkpoints enabled, keep the checkpoints: a restore passes over one whose split does not cover the pod.The old split's stamps also hold every pod of the new split at boot.An offset reset of each input group to its current offsets clears them, because it commits without a stamp.Run it only after every pod of the old split has stopped, or the fence admits the new split while the old one still commits.-Each slice then begins again behind the coverage fence and holds no history until a backfill runs.+Each slice without a covering checkpoint then begins again behind the coverage fence and holds no history until a backfill runs.Nothing moves a slice between pods yet, so one pod that owns every partition is the supported deployment.## Startup@@ -229,7 +230,7 @@ At boot the processor:5. waits until the [ownership fence](#ownership-and-the-single-pod-deployment) admits its split,6. decides where the store comes from: with durable restore enabled, the live store on disk or a checkpoint, otherwise an empty store.A checkpoint restore that cannot finish blocks here and retries, as [a blocked restore](state-store-and-durability.md#a-blocked-restore) describes.- A store written under another split of the partitions refuses to open, as [ownership](#ownership-and-the-single-pod-deployment) explains,+ A store written under a split that does not cover the pod's refuses to open, as [ownership](#ownership-and-the-single-pod-deployment) explains,7. stamps every owned partition on every input group, and reads the stamps back,8. starts the timer loops and the events consumer, and starts the followers and the checkpoint loop once the catalog has loaded and boot recovery has ended.diff --git a/docs/internal/realtime-cohorts/state-store-and-durability.md b/docs/internal/realtime-cohorts/state-store-and-durability.mdindex a789345f9678..a558e54c952e 100644--- a/docs/internal/realtime-cohorts/state-store-and-durability.md+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md@@ -143,7 +143,7 @@ Nothing is dispatched to a worker, from the events consumer or a follower, untilA pod owns its partitions for as long as it runs, so no slice changes owner while the pod runs.State never moves between pods, which is why one pod that owns every partition is the supported deployment.-The store records the split of the partitions it was written under and refuses to open under another.+The store records the split of the partitions it was written under, and refuses to open under a split that the recorded one does not cover.[Processor runtime](processor-runtime.md#ownership-and-the-single-pod-deployment) explains that constraint.### Choosing a checkpoint@@ -151,13 +151,14 @@ The store records the split of the partitions it was written under and refuses tThe restore tries the freshest local checkpoint, then up to `CHECKPOINT_IMPORT_ATTEMPT_DEPTH` remote ones from the last `CHECKPOINT_IMPORT_WINDOW_HOURS`, newest first.A checkpoint counts only once its `metadata.json` exists, because the sweeper and the upload both write it last.A local attempt without one is passed over for the attempt before it, and a remote attempt without one is unusable and does not count toward the depth.+A remote checkpoint whose split does not cover this pod is unusable and does not count toward the depth either.The restore judges each candidate from its `metadata.json` and `offsets.json` before the bulk download:- its store schema must be this build's,- its metadata and manifest formats must be ones this build reads,-- its manifest must belong to this pod's ordinal,+- its manifest's split must cover this pod's, which means it owns every partition this pod owns,- its manifest must record a position on the events topic,-- the broker must still hold the events the checkpoint lacks on at least one partition (see [the replay window](#the-replay-window)).+- the broker must still hold the events the checkpoint lacks on at least one partition this pod owns (see [the replay window](#the-replay-window)).A candidate that passes is materialized in `<STORE_PATH>.restore`, a sibling of the store on the same mount.A local checkpoint is hard-linked there, SSTs only, with every other file copied.@@ -176,7 +177,7 @@ When none publishes:| None, or only unusable ones | The store is created empty, behind the coverage fence || Any that failed | The boot blocks and retries |-Unusable means an upload that never finished, a metadata or manifest format this build does not read, a schema mismatch while `COHORT_WIPE_ON_SCHEMA_MISMATCH` is on, or a checkpoint whose replay expired on every partition.+Unusable means an upload that never finished, a metadata or manifest format this build does not read, a schema mismatch while `COHORT_WIPE_ON_SCHEMA_MISMATCH` is on, a split that does not cover this pod, or a checkpoint whose replay expired on every partition this pod owns.Older candidates are no better, so a retry cannot help.A failed candidate is one that could restore after a fix: a download error, a local attempt whose files cannot be read, a stage that fails validation, a schema mismatch without the wipe flag.A failed listing, a failed Kafka read and a local file error also block.@@ -354,7 +355,7 @@ A lint rule denies direct calls to most store I/O methods, and the synchronous sWith checkpoints enabled, the boot deletes it and restores.- A store directory that holds `restore.json` is a checkpoint restore in progress, not a live store.An image from before that marker ignores it and reopens the store at the broker's old offsets, so do not roll back while a restore is pending.-- Changing `COHORT_POD_COUNT` makes every store written under another split refuse to open, because each records the split it was written under.+- Changing `COHORT_POD_COUNT` makes every store whose split does not cover its pod's new one refuse to open, because each records the split it was written under.[Ownership](processor-runtime.md#ownership-and-the-single-pod-deployment) lists what to wipe.Wiping a store deletes every slice, including merge transfers not yet sent, whose merge offsets may already be committed.- Person records grow with every person seen on a team with person-property conditions, including those that match nothing, unless a time-to-live is configured.diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rsindex 5a24f17b36f3..45e266151ead 100644--- a/rust/cohort-stream-processor/src/main.rs+++ b/rust/cohort-stream-processor/src/main.rs@@ -574,12 +574,12 @@ async fn async_main(config: Config) -> Result<()> {// Whole-DB checkpoints to the local volume and S3, from boot to the final one on a graceful stop.// The loop waits for boot: a capture before the events rewind would record the broker's old// offsets of a pending restore.- if let (Some(lineage), Some(checkpoint_handle)) = (lineage, checkpoint_handle) {+ if let Some(checkpoint_handle) = checkpoint_handle {let sweeper = Arc::new(CheckpointSweeper::new(store_for_checkpoint,dispatcher.clone(),groups,- lineage,+ claimed.clone(),config.durability_config(),upload_cadence(config.checkpoint_interval_ms,diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rsindex bab45a934bd3..a15ad35ef605 100644--- a/rust/cohort-stream-processor/src/observability/metrics.rs+++ b/rust/cohort-stream-processor/src/observability/metrics.rs@@ -115,8 +115,8 @@ pub const CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS: &str =/// `full_upload_at` of the newest upload: when its chain of incrementals began (gauge, seconds).pub const CHECKPOINT_LAST_FULL_UPLOAD_TIMESTAMP_SECONDS: &str ="checkpoint_last_full_upload_timestamp_seconds";-/// Checkpoint ticks skipped before the checkpoint, labelled by `reason` (`positions`|`incomplete`)-/// (counter).+/// Checkpoint ticks skipped before the checkpoint, labelled by `reason`+/// (`positions`|`foreign`|`incomplete`) (counter). `foreign` is a position another split stamped.pub const CHECKPOINT_CAPTURE_FAILURES_TOTAL: &str = "checkpoint_capture_failures_total";/// Wall-clock duration of one checkpoint S3 upload, labelled by `result` (histogram, seconds).pub const CHECKPOINT_UPLOAD_DURATION_SECONDS: &str = "checkpoint_upload_duration_seconds";diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rsindex cb6c75043589..bd1c2124e40f 100644--- a/rust/cohort-stream-processor/src/partitions/mod.rs+++ b/rust/cohort-stream-processor/src/partitions/mod.rs@@ -39,7 +39,8 @@ pub use partitioner::{};pub use pause::{ConsumerPauser, PartitionPauser};pub use positions::{- list_offsets, FollowerGroup, InputGroups, InputPositions, InputTopic, ResumeOffset,+ list_offsets, FollowerGroup, InputGroups, InputPositions, InputTopic, OwnedPositions,+ PositionsError, ResumeOffset,};pub use rebalance::CohortConsumerContext;pub use router::{diff --git a/rust/cohort-stream-processor/src/partitions/ownership.rs b/rust/cohort-stream-processor/src/partitions/ownership.rsindex e74d3c79d721..825e7dfdc826 100644--- a/rust/cohort-stream-processor/src/partitions/ownership.rs+++ b/rust/cohort-stream-processor/src/partitions/ownership.rs@@ -8,12 +8,14 @@ use std::num::NonZeroU16;use rdkafka::error::KafkaResult;use rdkafka::{Offset, TopicPartitionList};+use serde::{Deserialize, Serialize};use crate::store::durability::PodOrdinal;/// The partitions one pod owns. Only [`Self::new`] splits the partitions between more than one/// pod, so `pods` divides the partition count and the ordinal is below `pods`.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(try_from = "SplitWire", into = "SplitWire")]pub struct PartitionOwnership {pods: NonZeroU16,ordinal: PodOrdinal,@@ -36,6 +38,33 @@ pub enum OwnershipError {const ENCODED_LEN: usize = 6;+/// The JSON shape, decoded through [`PartitionOwnership::new`].+#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct SplitWire {+ pods: NonZeroU16,+ ordinal: PodOrdinal,+ partitions: u16,+}++impl TryFrom<SplitWire> for PartitionOwnership {+ type Error = OwnershipError;++ fn try_from(wire: SplitWire) -> Result<Self, Self::Error> {+ Self::new(wire.pods, wire.ordinal, wire.partitions)+ }+}++impl From<PartitionOwnership> for SplitWire {+ fn from(ownership: PartitionOwnership) -> Self {+ Self {+ pods: ownership.pods,+ ordinal: ownership.ordinal,+ partitions: ownership.partition_count,+ }+ }+}+impl PartitionOwnership {/// One pod owns every partition.pub const fn single(partition_count: u16) -> Self {@@ -84,6 +113,15 @@ impl PartitionOwnership {partition < self.partition_count && partition % self.pods.get() == self.ordinal.get()}+ /// True when every partition `other` owns is one this split owns. That holds when `self.pods`+ /// divides `other.pods` and `other.ordinal % self.pods == self.ordinal`: every `p` with+ /// `p % other.pods == other.ordinal` then has `p % self.pods == self.ordinal`.+ pub fn covers(&self, other: &Self) -> bool {+ self.partition_count == other.partition_count+ && other.pods.get().is_multiple_of(self.pods.get())+ && other.ordinal.get() % self.pods.get() == self.ordinal.get()+ }+/// The owned partitions in ascending order.pub fn partitions(&self) -> impl Iterator<Item = u16> {(self.ordinal.get()..self.partition_count).step_by(usize::from(self.pods.get()))@@ -194,6 +232,33 @@ mod tests {}}+ #[test]+ fn a_split_covers_another_exactly_when_it_owns_every_partition_the_other_owns() {+ // Over 64 partitions every pod count is a power of two, so one count of a pair always+ // divides the other. 12 has counts that do not, such as 2 and 3.+ for partitions in [64u16, 12] {+ let splits: Vec<PartitionOwnership> = (1..=partitions)+ .filter(|pods| partitions.is_multiple_of(*pods))+ .flat_map(|pods| {+ let pods = NonZeroU16::new(pods).unwrap();+ (0..pods.get()).map(move |ordinal| {+ PartitionOwnership::new(pods, PodOrdinal::from(ordinal), partitions)+ .unwrap()+ })+ })+ .collect();+ for a in &splits {+ for b in &splits {+ let inclusion = b.partitions().all(|partition| a.owns(partition));+ assert_eq!(a.covers(b), inclusion, "{a} covers {b}");+ }+ }+ }++ let over_32 = PartitionOwnership::single(32);+ assert!(!PartitionOwnership::single(64).covers(&over_32));+ }+#[test]fn the_assignment_resumes_each_owned_partition_at_its_committed_offset() {let ownership =diff --git a/rust/cohort-stream-processor/src/partitions/positions.rs b/rust/cohort-stream-processor/src/partitions/positions.rsindex e6e17a421003..5996cf390604 100644--- a/rust/cohort-stream-processor/src/partitions/positions.rs+++ b/rust/cohort-stream-processor/src/partitions/positions.rs@@ -3,8 +3,8 @@//!//! Every commit the processor makes follows a WAL fsync, so a group's committed offset is at or//! below the durable state, and a checkpoint taken after reading it contains at least that state.-//! That holds only while this pod is the one committer for the partitions it checkpoints, which a-//! single pod guarantees and static ownership must keep.+//! That holds only for this pod's own commits, so a checkpoint takes no position another split+//! stamped (see [`super::fence`]).use std::collections::{BTreeMap, BTreeSet};use std::fmt;@@ -16,8 +16,9 @@ use rdkafka::types::RDKafkaErrorCode;use rdkafka::{ClientConfig, Offset, TopicPartitionList};use serde::{Deserialize, Serialize};-use super::fence::{CommitLedger, Committed, InputCommits};+use super::fence::{ClaimedSplit, CommitLedger, Committed, InputCommits};use super::stamp::{CommitStamp, Stamp};+use super::PartitionOwnership;use crate::config::Config;const FETCH_TIMEOUT: Duration = Duration::from_secs(10);@@ -163,6 +164,36 @@ pub enum PositionsError {Kafka(#[from] KafkaError),#[error(transparent)]Negative(#[from] NegativeOffset),+ #[error("{topic} partition {partition} was last committed by {stamp}, not this pod")]+ Foreign {+ topic: InputTopic,+ partition: u16,+ stamp: Stamp,+ },+}++/// Every input's resume positions on partitions of a claimed split, none of them stamped by+/// another split. Only [`InputGroups::owned_positions`] builds one, so a manifest never records a+/// position another split stamped. An unstamped commit, such as an offset reset, passes.+#[derive(Debug)]+pub struct OwnedPositions {+ split: PartitionOwnership,+ inputs: Vec<InputPositions>,+}++impl OwnedPositions {+ #[cfg(test)]+ pub(crate) fn for_test(split: PartitionOwnership, inputs: Vec<InputPositions>) -> Self {+ Self { split, inputs }+ }++ pub fn split(&self) -> PartitionOwnership {+ self.split+ }++ pub fn inputs(&self) -> &[InputPositions] {+ &self.inputs+ }}/// Reads and commits one input's consumer-group positions without joining the group. Every method@@ -249,9 +280,23 @@ impl GroupReader {Ok(positions)}- fn positions(&self, partitions: &BTreeSet<u16>) -> Result<InputPositions, PositionsError> {+ /// Refuses a position another split stamped.+ fn owned_positions(+ &self,+ owner: &PartitionOwnership,+ partitions: &BTreeSet<u16>,+ ) -> Result<InputPositions, PositionsError> {let client = self.client()?;let commits = self.commits(&client, partitions)?;+ for (&partition, committed) in commits.commits() {+ if let Some(stamp) = committed.stamp().filter(|stamp| stamp.is_foreign_to(owner)) {+ return Err(PositionsError::Foreign {+ topic: self.topic.clone(),+ partition,+ stamp: stamp.clone(),+ });+ }+ }let positions = self.resume_positions(&client, &commits)?;Ok(InputPositions::new(self.topic.clone(), positions))}@@ -391,14 +436,18 @@ impl InputGroups {})}- /// Every input's resume positions on `partitions`.- pub fn resume_positions(+ /// Every input's resume positions on `partitions`, as long as no other split stamped them.+ pub fn owned_positions(&self,+ claimed: &ClaimedSplit,partitions: &BTreeSet<u16>,- ) -> Result<Vec<InputPositions>, PositionsError> {- self.readers()- .map(|reader| reader.positions(partitions))- .collect()+ ) -> Result<OwnedPositions, PositionsError> {+ let split = claimed.ownership();+ let inputs = self+ .readers()+ .map(|reader| reader.owned_positions(&split, partitions))+ .collect::<Result<_, _>>()?;+ Ok(OwnedPositions { split, inputs })}/// `topic`'s watermarks on partitions `0..partition_count`.diff --git a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs b/rust/cohort-stream-processor/src/store/durability/checkpoint.rsindex 46e8be8aa669..1fbf61bfebc4 100644--- a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs+++ b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs@@ -53,7 +53,7 @@ use crate::observability::metrics::{CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS, CHECKPOINT_SIZE_BYTES,CHECKPOINT_UPLOADED_BYTES_TOTAL, CHECKPOINT_UPLOADS_TOTAL,};-use crate::partitions::InputGroups;+use crate::partitions::{ClaimedSplit, InputGroups, PositionsError};use crate::store::{CohortStore, DbIdentity};use crate::sweep::{run_sweep_loop, Sweeper};@@ -229,6 +229,7 @@ pub struct CheckpointSweeper {store: CohortStore,dispatcher: Arc<EventDispatcher>,groups: Arc<InputGroups>,+ claimed: ClaimedSplit,lineage: CheckpointLineage,config: DurabilityConfig,/// Built on the first upload, so an S3 outage never stops a pod that has its store.@@ -248,11 +249,12 @@ impl CheckpointSweeper {store: CohortStore,dispatcher: Arc<EventDispatcher>,groups: Arc<InputGroups>,- lineage: CheckpointLineage,+ claimed: ClaimedSplit,config: DurabilityConfig,upload_every_n: u64,stop: CancellationToken,) -> Self {+ let lineage = CheckpointLineage::new(claimed.ownership().ordinal());let baseline = UploadBaseline::load(&lineage.local_dir(Path::new(&config.local_checkpoint_dir))@@ -266,6 +268,7 @@ impl CheckpointSweeper {store,dispatcher,groups,+ claimed,lineage,config,exporter: OnceCell::new(),@@ -320,9 +323,7 @@ impl CheckpointSweeper {}}- // 2. The slices to capture. A revoke after this point leaves a slice the manifest names but- // the checkpoint lacks, which a restore resumes as empty; an assign leaves one the- // checkpoint holds but the manifest lacks, which a restore resets. Both are safe.+ // 2. The slices to capture.let owned = trigger.owned(|| self.dispatcher.owned_partitions());if owned.is_empty() {info!(@@ -332,18 +333,24 @@ impl CheckpointSweeper {return;}- // 3. Every input's resume positions, from its consumer group on the broker.+ // 3. Every input's resume positions, from its consumer group on the broker. A position+ // another split stamped lies past what this store holds, so the tick skips.let groups = self.groups.clone();+ let claimed = self.claimed.clone();let partitions = owned.clone();let positions = match tokio::task::spawn_blocking(move || {- groups.resume_positions(&partitions)+ groups.owned_positions(&claimed, &partitions)}).await{Ok(Ok(positions)) => positions,Ok(Err(e)) => {+ let reason = match e {+ PositionsError::Foreign { .. } => "foreign",+ PositionsError::Kafka(_) | PositionsError::Negative(_) => "positions",+ };warn!(error = %e, "checkpoint tick: reading input positions failed; skipping tick");- metrics::counter!(CHECKPOINT_CAPTURE_FAILURES_TOTAL, "reason" => "positions")+ metrics::counter!(CHECKPOINT_CAPTURE_FAILURES_TOTAL, "reason" => reason).increment(1);return;}@@ -356,7 +363,7 @@ impl CheckpointSweeper {};// 4. The manifest refuses a slice that lacks a position on any input.- let manifest = match OffsetManifest::capture(self.lineage.ordinal(), &owned, positions) {+ let manifest = match OffsetManifest::capture(&owned, positions) {Ok(manifest) => manifest,Err(e) => {warn!(error = %e, "checkpoint tick: incomplete manifest; skipping tick");diff --git a/rust/cohort-stream-processor/src/store/durability/manifest.rs b/rust/cohort-stream-processor/src/store/durability/manifest.rsindex a347f7303e07..46ea2a454a2a 100644--- a/rust/cohort-stream-processor/src/store/durability/manifest.rs+++ b/rust/cohort-stream-processor/src/store/durability/manifest.rs@@ -6,7 +6,12 @@//!//! The positions are the consumer groups' committed offsets, read from the broker just before the//! checkpoint. Every commit follows a WAL fsync, so the checkpoint holds at least the state up to-//! them, and replay from them re-folds only what per-key `AppliedOffsets` already skips.+//! them, and replay from them re-folds only what per-key `AppliedOffsets` already skips. That+//! holds only for this pod's own commits, so a manifest is built only from positions no other split+//! stamped.+//!+//! The manifest records the split it was captured under. A restore accepts it on any pod whose+//! partitions that split covers.use std::collections::{BTreeMap, BTreeSet};use std::path::Path;@@ -15,8 +20,7 @@ use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use super::format_version;-use super::lineage::PodOrdinal;-use crate::partitions::{InputPositions, InputTopic, ResumeOffset};+use crate::partitions::{InputTopic, OwnedPositions, PartitionOwnership, ResumeOffset};/// Filename of the offset manifest, written as a sibling of the RocksDB checkpoint files and tracked/// by the planner like any other file, so it rides the S3 upload/restore.@@ -24,7 +28,7 @@ pub const MANIFEST_FILENAME: &str = "offsets.json";/// Current on-disk shape version. Decode refuses any other, so a restore can tell a manifest written/// by another build from a corrupt one.-pub const MANIFEST_VERSION: u32 = 2;+pub const MANIFEST_VERSION: u32 = 3;/// Fields are private: the only constructors are [`Self::capture`] and decoding, and both refuse a/// slice that lacks a position on any input.@@ -32,7 +36,7 @@ pub const MANIFEST_VERSION: u32 = 2;#[serde(try_from = "ManifestWire", into = "ManifestWire")]pub struct OffsetManifest {captured_at: DateTime<Utc>,- ordinal: PodOrdinal,+ split: PartitionOwnership,inputs: BTreeSet<InputTopic>,slices: BTreeMap<u16, BTreeMap<InputTopic, ResumeOffset>>,}@@ -57,7 +61,7 @@ pub enum ManifestError {struct ManifestWire {version: u32,captured_at: DateTime<Utc>,- ordinal: PodOrdinal,+ split: PartitionOwnership,inputs: BTreeSet<InputTopic>,slices: BTreeMap<u16, BTreeMap<InputTopic, ResumeOffset>>,}@@ -84,7 +88,7 @@ impl TryFrom<ManifestWire> for OffsetManifest {}Ok(Self {captured_at: wire.captured_at,- ordinal: wire.ordinal,+ split: wire.split,inputs: wire.inputs,slices: wire.slices,})@@ -96,7 +100,7 @@ impl From<OffsetManifest> for ManifestWire {Self {version: MANIFEST_VERSION,captured_at: manifest.captured_at,- ordinal: manifest.ordinal,+ split: manifest.split,inputs: manifest.inputs,slices: manifest.slices,}@@ -104,17 +108,17 @@ impl From<OffsetManifest> for ManifestWire {}impl OffsetManifest {- /// Record `positions` for every owned slice. Refuses an owned slice missing from any input's- /// positions, and an empty `owned`.+ /// Record `positions` for every owned slice, under the split that read them. Refuses an owned+ /// slice missing from any input's positions, and an empty `owned`.pub fn capture(- ordinal: PodOrdinal,owned: &BTreeSet<u16>,- positions: Vec<InputPositions>,+ positions: OwnedPositions,) -> Result<Self, ManifestError> {let slices = owned.iter().map(|&partition| {let offsets = positions+ .inputs().iter().filter_map(|input| {let offset = input.offsets().get(&partition)?;@@ -127,8 +131,9 @@ impl OffsetManifest {ManifestWire {version: MANIFEST_VERSION,captured_at: Utc::now(),- ordinal,+ split: positions.split(),inputs: positions+ .inputs().iter().map(|input| input.topic().clone()).collect(),@@ -165,8 +170,8 @@ impl OffsetManifest {self.captured_at}- pub fn ordinal(&self) -> PodOrdinal {- self.ordinal+ pub fn split(&self) -> PartitionOwnership {+ self.split}pub fn inputs(&self) -> &BTreeSet<InputTopic> {@@ -185,9 +190,15 @@ mod tests {use serde_json::json;use tempfile::TempDir;+ use crate::partitions::InputPositions;+const EVENTS: &str = "cohort_stream_events";const MERGES: &str = "person_merge_events";+ fn owned(inputs: Vec<InputPositions>) -> OwnedPositions {+ OwnedPositions::for_test(PartitionOwnership::single(4), inputs)+ }+fn positions(topic: &str, offsets: &[(u16, i64)]) -> InputPositions {InputPositions::new(InputTopic::new(topic),@@ -200,20 +211,20 @@ mod tests {#[test]fn capture_round_trips_and_refuses_an_owned_slice_one_input_lacks() {- let owned = BTreeSet::from([0, 3]);+ let slices = BTreeSet::from([0, 3]);let manifest = OffsetManifest::capture(- PodOrdinal::STANDALONE,- &owned,- vec![+ &slices,+ owned(vec![positions(EVENTS, &[(0, 100), (3, 250)]),positions(MERGES, &[(0, 0), (3, 7)]),- ],+ ]),).unwrap();let dir = TempDir::new().unwrap();manifest.write_to_dir(dir.path()).unwrap();let loaded = OffsetManifest::load_from_dir(dir.path()).unwrap();assert_eq!(loaded, manifest);+ assert_eq!(loaded.split(), PartitionOwnership::single(4));assert_eq!(loaded.slice(3).unwrap()[&InputTopic::new(MERGES)],ResumeOffset::try_from(7).unwrap(),@@ -221,12 +232,11 @@ mod tests {assert_eq!(loaded.slice(1), None);let err = OffsetManifest::capture(- PodOrdinal::STANDALONE,- &owned,- vec![+ &slices,+ owned(vec![positions(EVENTS, &[(0, 100), (3, 250)]),positions(MERGES, &[(0, 0)]),- ],+ ]),).unwrap_err();assert!(@@ -234,27 +244,33 @@ mod tests {"{err:?}",);assert!(matches!(- OffsetManifest::capture(- PodOrdinal::STANDALONE,- &BTreeSet::new(),- vec![positions(EVENTS, &[])]- ),+ OffsetManifest::capture(&BTreeSet::new(), owned(vec![positions(EVENTS, &[])])),Err(ManifestError::Empty),));}#[test]- fn decode_refuses_another_format_an_incomplete_slice_a_negative_offset_and_no_slices() {- let wire = |version: u32, slices: serde_json::Value| {+ fn decode_refuses_another_format_an_invalid_split_an_incomplete_slice_a_negative_offset_and_no_slices(+ ) {+ let split = json!({ "pods": 2, "ordinal": 1, "partitions": 4 });+ let wire = |version: u32, split: &serde_json::Value, slices: serde_json::Value| {json!({"version": version,"captured_at": "2026-10-09T16:00:00Z",- "ordinal": 0,+ "split": split,"inputs": [EVENTS, MERGES],"slices": slices,}).to_string()};+ let format_two = json!({+ "version": 2,+ "captured_at": "2026-10-09T16:00:00Z",+ "ordinal": 0,+ "inputs": [EVENTS, MERGES],+ "slices": { "0": { EVENTS: 1, MERGES: 2 } },+ })+ .to_string();let format_one = json!({"version": 1,"captured_at": "2026-10-09T16:00:00Z",@@ -262,24 +278,45 @@ mod tests {}).to_string();- assert!(OffsetManifest::decode(- wire(2, json!({ "0": { EVENTS: 1, MERGES: 2 } })).as_bytes()- )- .is_ok());+ let slice = || json!({ "1": { EVENTS: 1, MERGES: 2 } });++ let decoded =+ OffsetManifest::decode(wire(3, &split, slice()).as_bytes()).expect("format 3 decodes");+ assert_eq!(+ decoded.split(),+ PartitionOwnership::new(+ std::num::NonZeroU16::new(2).unwrap(),+ crate::store::durability::PodOrdinal::from(1),+ 4+ )+ .unwrap(),+ );+ for (format, found) in [(&format_one, 1), (&format_two, 2)] {+ assert!(+ matches!(+ OffsetManifest::decode(format.as_bytes()),+ Err(ManifestError::UnsupportedFormat { found: f }) if f == found,+ ),+ "format {found}",+ );+ }+ let uneven = json!({ "pods": 3, "ordinal": 0, "partitions": 4 });assert!(matches!(- OffsetManifest::decode(format_one.as_bytes()),- Err(ManifestError::UnsupportedFormat { found: 1 }),+ OffsetManifest::decode(wire(3, &uneven, slice()).as_bytes()),+ Err(ManifestError::Decode(_)),));assert!(matches!(- OffsetManifest::decode(wire(2, json!({ "0": { EVENTS: 1 } })).as_bytes()),- Err(ManifestError::Incomplete { partition: 0, .. }),+ OffsetManifest::decode(wire(3, &split, json!({ "1": { EVENTS: 1 } })).as_bytes()),+ Err(ManifestError::Incomplete { partition: 1, .. }),));assert!(matches!(- OffsetManifest::decode(wire(2, json!({ "0": { EVENTS: -1, MERGES: 2 } })).as_bytes()),+ OffsetManifest::decode(+ wire(3, &split, json!({ "1": { EVENTS: -1, MERGES: 2 } })).as_bytes()+ ),Err(ManifestError::Decode(_)),));assert!(matches!(- OffsetManifest::decode(wire(2, json!({})).as_bytes()),+ OffsetManifest::decode(wire(3, &split, json!({})).as_bytes()),Err(ManifestError::Empty),));}diff --git a/rust/cohort-stream-processor/src/store/durability/recovery.rs b/rust/cohort-stream-processor/src/store/durability/recovery.rsindex 0d99a94657b5..a27e7d4263b8 100644--- a/rust/cohort-stream-processor/src/store/durability/recovery.rs+++ b/rust/cohort-stream-processor/src/store/durability/recovery.rs@@ -6,7 +6,8 @@//! 2. **Reopened.** An intact live store reopens. If it carries a restore marker, the restore it//! published is still pending and resumes instead.//! 3. With checkpoints enabled, candidates are tried newest first, the freshest local checkpoint-//! before S3. The first one that publishes wins.+//! before S3. A candidate restores on any pod whose partitions its split covers. The first one+//! that publishes wins.//! 4. **Created.** Nothing is restorable: no candidate, or only unusable ones. Every slice then//! begins when its worker spawns, behind the coverage fence.//!@@ -42,7 +43,7 @@ use crate::observability::metrics::{CHECKPOINT_RESTORE_BLOCKED, CHECKPOINT_RESTORE_CANDIDATES_TOTAL,CHECKPOINT_RESTORE_DURATION_SECONDS, CHECKPOINT_RESTORE_TOTAL,};-use crate::partitions::{AdmittedSplit, InputGroups, InputTopic};+use crate::partitions::{AdmittedSplit, InputGroups, InputTopic, PartitionOwnership};use crate::store::{CohortStore, StoreError, STORE_SCHEMA_VERSION};pub(crate) const RETRY_START: Duration = Duration::from_secs(30);@@ -108,8 +109,10 @@ enum Unusable {MetadataFormat { found: u32 },#[error("manifest format {found}")]ManifestFormat { found: u32 },- #[error("the broker no longer holds what it lacks on any partition")]+ #[error("the broker no longer holds what it lacks on any partition this pod owns")]NothingToReplay,+ #[error("its manifest's split, {found}, does not cover this pod's partitions")]+ OtherSplit { found: PartitionOwnership },}/// A candidate whose stage failed validation, so later rounds fail it without downloading it@@ -198,7 +201,7 @@ impl Search {////// A restore that cannot finish blocks here, retrying with backoff, until the operator fixes the/// cause or turns checkpoints off. `lineage` is `None` when checkpoints are disabled. The store-/// refuses to open when it was written under another split than the one `admitted`.+/// refuses to open when it was written under a split that does not cover the one `admitted`.pub async fn open_store(config: &Config,admitted: &AdmittedSplit,@@ -254,6 +257,7 @@ async fn restore_until_ready(let started = Instant::now();let attempt = match prepare_store(&config,+ admitted.ownership(),lineage,groups.as_ref(),searched_at,@@ -307,6 +311,7 @@ async fn restore_until_ready(/// Blocks on file and Kafka I/O; see [`restore_until_ready`].async fn prepare_store(config: &Config,+ ownership: PartitionOwnership,lineage: Option<CheckpointLineage>,window: &impl ReplayWindow,searched_at: DateTime<Utc>,@@ -352,10 +357,9 @@ async fn prepare_store(stage,uploaded: local_dir.join(UPLOADED_FILENAME),s3_bucket: &durability.s3_bucket,- lineage,+ ownership,events_topic: InputTopic::new(&config.cohort_stream_events_topic),window,- partition_count: config.partition_count(),wipe_on_schema_mismatch: config.cohort_wipe_on_schema_mismatch,rejected,};@@ -427,10 +431,10 @@ struct Restore<'a, W> {/// The lineage's `uploaded.json`, which a publish rewrites.uploaded: PathBuf,s3_bucket: &'a str,- lineage: CheckpointLineage,+ /// This pod's split. A candidate restores only when its split covers it.+ ownership: PartitionOwnership,events_topic: InputTopic,window: &'a W,- partition_count: u16,wipe_on_schema_mismatch: bool,rejected: &'a mut HashSet<Rejected>,}@@ -467,6 +471,8 @@ impl<W: ReplayWindow> Restore<'_, W> {/// Tries the S3 candidates newest first, up to `depth` of them. An unfinished upload does not/// count toward the depth, so a run of failed uploads cannot hide a complete one behind it.+ /// Neither does a candidate whose split does not cover this pod, so checkpoints of another+ /// split cannot hide a covering one behind them.async fn search_s3(&mut self,importer: &CheckpointImporter,@@ -484,7 +490,10 @@ impl<W: ReplayWindow> Restore<'_, W> {break;}let verdict = self.s3(importer, metadata_key).await?;- if !matches!(verdict, Verdict::Unusable(Unusable::Unfinished)) {+ if !matches!(+ verdict,+ Verdict::Unusable(Unusable::Unfinished | Unusable::OtherSplit { .. })+ ) {tried += 1;}let timed_out = matches!(verdict, Verdict::TimedOut(_));@@ -557,6 +566,13 @@ impl<W: ReplayWindow> Restore<'_, W> {store_schema: u32,manifest: &OffsetManifest,) -> Result<Option<Verdict>, RestoreBlocked> {+ // Before the schema check: a candidate of another split never restores on this pod, so a+ // schema mismatch must not fail it and block the boot.+ if !manifest.split().covers(&self.ownership) {+ return Ok(Some(Verdict::Unusable(Unusable::OtherSplit {+ found: manifest.split(),+ })));+ }if store_schema != STORE_SCHEMA_VERSION {return Ok(Some(schema_mismatch(checkpoint_id,@@ -564,16 +580,6 @@ impl<W: ReplayWindow> Restore<'_, W> {self.wipe_on_schema_mismatch,)));}- if manifest.ordinal() != self.lineage.ordinal() {- return Ok(Some(failed(- checkpoint_id,- format_args!(- "its manifest belongs to ordinal {}, not {}",- manifest.ordinal(),- self.lineage.ordinal()- ),- )));- }// An input the manifest lacks resumes from its group's commit. For the events group that// commit lies past the checkpoint, so the restore would skip the events between.if !manifest.inputs().contains(&self.events_topic) {@@ -592,9 +598,9 @@ impl<W: ReplayWindow> Restore<'_, W> {/// The window check.fn replay_plan(&self, manifest: &OffsetManifest) -> Result<Admission, RestoreBlocked> {- let plan = RestorePlan::check(manifest, self.window, self.partition_count)+ let plan = RestorePlan::check(manifest, self.window, self.ownership.partition_count()).map_err(RestoreBlocked::Positions)?;- if !plan.resumes_any() {+ if !plan.resumes_any(&self.ownership) {// Older candidates hold older positions, which the broker deletes first, so retrying// cannot help.return Ok(Admission::Rejected(Unusable::NothingToReplay));@@ -750,7 +756,7 @@ mod tests {use tempfile::TempDir;use tokio_util::sync::CancellationToken;- use crate::partitions::{InputPositions, InputTopic, ResumeOffset};+ use crate::partitions::{InputPositions, InputTopic, OwnedPositions, ResumeOffset};use crate::store::durability::lineage::PodOrdinal;use crate::store::durability::stage::MARKER_FILENAME;use crate::store::durability::{CheckpointDownloader, CheckpointInfo};@@ -792,6 +798,16 @@ mod tests {window_at(Some(0))}+ /// Pod `ordinal` of `pods`, over two partitions.+ fn split(pods: u16, ordinal: u16) -> PartitionOwnership {+ PartitionOwnership::new(+ std::num::NonZeroU16::new(pods).unwrap(),+ PodOrdinal::from(ordinal),+ 2,+ )+ .unwrap()+ }+fn failure() -> Verdict {failed("2026-10-09T16-00-00-000Z", "download failed")}@@ -848,6 +864,7 @@ mod tests {struct Boot {root: TempDir,config: Config,+ ownership: PartitionOwnership,}impl Boot {@@ -860,7 +877,18 @@ mod tests {config.cohort_partition_count = 1;config.store_path = root.path().join("store").to_string_lossy().into_owned();config.checkpoint_local_dir = root.path().join("ckpt").to_string_lossy().into_owned();- Self { root, config }+ Self {+ root,+ config,+ ownership: PartitionOwnership::single(1),+ }+ }++ fn of(ownership: PartitionOwnership) -> Self {+ let mut boot = Self::new();+ boot.config.cohort_partition_count = u32::from(ownership.partition_count());+ boot.ownership = ownership;+ boot}fn live(&self) -> PathBuf {@@ -872,61 +900,78 @@ mod tests {.local_dir(Path::new(&self.config.checkpoint_local_dir))}- /// A fresh checkpoint attempt under `parent`, laid out as the sweeper lays it out: the- /// RocksDB files, `offsets.json`, then `metadata.json`. Returns its metadata.- fn checkpoint_attempt(&self, parent: &Path) -> CheckpointMetadata {+ /// A checkpoint attempt under `parent`, captured at `at` by `split`, laid out as the+ /// sweeper lays it out: the RocksDB files, `offsets.json`, then `metadata.json`. Every slice+ /// the split owns resumes the events at 42. Returns its metadata.+ fn checkpoint_attempt(+ &self,+ parent: &Path,+ split: PartitionOwnership,+ at: DateTime<Utc>,+ ) -> CheckpointMetadata {let store = CohortStore::open(&StoreConfig {path: self.root.path().join("source"),..StoreConfig::default()}).unwrap();std::fs::create_dir_all(parent).unwrap();- let metadata = CheckpointMetadata::new(- PodOrdinal::STANDALONE,- Utc::now(),- store.db_identity().unwrap(),- );+ let metadata =+ CheckpointMetadata::new(split.ordinal(), at, store.db_identity().unwrap());let dir = parent.join(&metadata.id);store.create_checkpoint(&dir).unwrap();- OffsetManifest::capture(- PodOrdinal::STANDALONE,- &BTreeSet::from([0]),- vec![InputPositions::new(- InputTopic::new(EVENTS),- BTreeMap::from([(0, ResumeOffset::try_from(42).unwrap())]),- )],- )- .unwrap()- .write_to_dir(&dir)- .unwrap();+ let slices: BTreeSet<u16> = split.partitions().collect();+ let events = InputPositions::new(+ InputTopic::new(EVENTS),+ slices+ .iter()+ .map(|&partition| (partition, ResumeOffset::try_from(42).unwrap()))+ .collect(),+ );+ OffsetManifest::capture(&slices, OwnedPositions::for_test(split, vec![events]))+ .unwrap()+ .write_to_dir(&dir)+ .unwrap();metadata.save(&dir.join(METADATA_FILENAME)).unwrap();metadata}fn local_checkpoint(&self) -> CheckpointMetadata {- self.checkpoint_attempt(&self.lineage_dir())+ self.checkpoint_attempt(&self.lineage_dir(), self.ownership, Utc::now())}- /// An uploaded checkpoint, listed after a newer attempt whose upload never finished.- fn uploaded_checkpoint(&self) -> (FakeS3, String) {+ /// A checkpoint by `split` at `at`, uploaded to the objects of `s3`. Returns its id and+ /// metadata key.+ fn upload(+ &self,+ s3: &mut HashMap<String, PathBuf>,+ split: PartitionOwnership,+ at: DateTime<Utc>,+ ) -> (String, String) {let parent = self.root.path().join("uploaded");- let mut metadata = self.checkpoint_attempt(&parent);+ let mut metadata = self.checkpoint_attempt(&parent, split, at);let dir = parent.join(&metadata.id);let mut info = CheckpointInfo::new(metadata.clone(), "checkpoints".to_string());- let mut objects = HashMap::new();for entry in std::fs::read_dir(&dir).unwrap() {let path = entry.unwrap().path();let name = path.file_name().unwrap().to_string_lossy().into_owned();if name != METADATA_FILENAME {info.metadata.track_file(info.get_file_key(&name), String::new());- objects.insert(info.get_file_key(&name), path);+ s3.insert(info.get_file_key(&name), path);}}metadata.files = info.metadata.files.clone();- let metadata_file = parent.join("uploaded-metadata.json");+ let metadata_file = parent.join(format!("{}-metadata.json", metadata.id));metadata.save(&metadata_file).unwrap();- objects.insert(info.get_metadata_key(), metadata_file);+ s3.insert(info.get_metadata_key(), metadata_file);+ (metadata.id, info.get_metadata_key())+ }++ /// An uploaded checkpoint, listed after a newer attempt whose upload never finished.+ fn uploaded_checkpoint(&self) -> (FakeS3, String) {+ let mut objects = HashMap::new();+ let (id, key) = self.upload(&mut objects, self.ownership, Utc::now());+ let metadata = CheckpointMetadata::load(&objects[&key]).unwrap();let unfinished = CheckpointInfo::new(CheckpointMetadata::new(@@ -936,13 +981,13 @@ mod tests {),"checkpoints".to_string(),);- let listing = vec![unfinished.get_metadata_key(), info.get_metadata_key()];+ let listing = vec![unfinished.get_metadata_key(), key];let s3 = FakeS3 {listing,objects,stalled: false,};- (s3, metadata.id)+ (s3, id)}fn restore<'a, W: ReplayWindow>(@@ -955,10 +1000,9 @@ mod tests {stage: staging_path(Path::new(&self.config.store_path)),uploaded: self.lineage_dir().join(UPLOADED_FILENAME),s3_bucket: &self.config.checkpoint_s3_bucket,- lineage: CheckpointLineage::new(PodOrdinal::STANDALONE),+ ownership: self.ownership,events_topic: InputTopic::new(EVENTS),window,- partition_count: 1,wipe_on_schema_mismatch: false,rejected,}@@ -967,6 +1011,7 @@ mod tests {async fn prepare(&self, window: &impl ReplayWindow) -> Result<BootStore, RestoreBlocked> {prepare_store(&self.config,+ self.ownership,Some(CheckpointLineage::new(PodOrdinal::STANDALONE)),window,Utc::now(),@@ -1069,6 +1114,44 @@ mod tests {);}+ #[tokio::test]+ async fn a_candidate_of_a_split_that_does_not_cover_this_pod_is_passed_over_outside_the_depth()+ {+ // The newest checkpoint is of pod 0 of 2, which does not cover pod 1 of 2, and the one+ // before is of pod 0 of 1, which does.+ let boot = Boot::of(split(2, 1));+ let mut objects = HashMap::new();+ let now = Utc::now();+ let (_, after_reshard) = boot.upload(&mut objects, split(2, 0), now);+ let (before_id, before_reshard) = boot.upload(+ &mut objects,+ split(1, 0),+ now - chrono::Duration::minutes(15),+ );+ let s3 = FakeS3 {+ listing: vec![after_reshard, before_reshard],+ objects,+ stalled: false,+ };+ let importer = CheckpointImporter::new(Box::new(s3), Duration::from_secs(60));+ let mut search = Search::default();++ let outcome = boot+ .restore(&window(), &mut HashSet::new())+ .search_s3(&importer, 1, Utc::now(), &mut search)+ .await+ .unwrap();++ let ControlFlow::Break(pending) = outcome else {+ panic!(+ "the checkpoint of the old split restores: {:?}",+ search.failed+ );+ };+ assert_eq!(pending.source().checkpoint_id(), before_id);+ assert!(search.failed.is_empty(), "{:?}", search.failed);+ }+#[tokio::test(start_paused = true)]async fn a_download_timeout_ends_the_search_because_older_candidates_are_as_large() {let boot = Boot::new();@@ -1223,12 +1306,14 @@ mod tests {}),("its manifest records no events position", |attempt| {attempt.manifest = OffsetManifest::capture(- PodOrdinal::STANDALONE,&BTreeSet::from([0]),- vec![InputPositions::new(- InputTopic::new("person_merge_events"),- BTreeMap::from([(0, ResumeOffset::try_from(7).unwrap())]),- )],+ OwnedPositions::for_test(+ PartitionOwnership::single(1),+ vec![InputPositions::new(+ InputTopic::new("person_merge_events"),+ BTreeMap::from([(0, ResumeOffset::try_from(7).unwrap())]),+ )],+ ),).unwrap()}),diff --git a/rust/cohort-stream-processor/src/store/durability/restore_plan.rs b/rust/cohort-stream-processor/src/store/durability/restore_plan.rsindex 67e29ebade1f..73c6f0c206aa 100644--- a/rust/cohort-stream-processor/src/store/durability/restore_plan.rs+++ b/rust/cohort-stream-processor/src/store/durability/restore_plan.rs@@ -116,10 +116,11 @@ impl RestorePlan {Ok(Self(slices))}- pub fn resumes_any(&self) -> bool {- self.0- .values()- .any(|slice| matches!(slice, SliceRestore::Resume(_)))+ /// True when a slice `ownership` owns resumes. Boot deletes the slices of the other partitions.+ pub fn resumes_any(&self, ownership: &PartitionOwnership) -> bool {+ self.0.iter().any(|(&partition, slice)| {+ ownership.owns(partition) && matches!(slice, SliceRestore::Resume(_))+ })}pub fn resets(&self) -> impl Iterator<Item = (u16, &ResetReason)> {@@ -165,7 +166,7 @@ mod tests {use super::*;use std::num::NonZeroU16;- use crate::partitions::InputPositions;+ use crate::partitions::{InputPositions, OwnedPositions};use crate::store::durability::lineage::PodOrdinal;const EVENTS: &str = "cohort_stream_events";@@ -227,7 +228,11 @@ mod tests {)}).collect();- OffsetManifest::capture(PodOrdinal::STANDALONE, &owned, positions).unwrap()+ OffsetManifest::capture(+ &owned,+ OwnedPositions::for_test(PartitionOwnership::single(8), positions),+ )+ .unwrap()}type Bounds = ((&'static str, u16), (i64, i64));@@ -298,7 +303,7 @@ mod tests {),]),);- assert!(plan.resumes_any());+ assert!(plan.resumes_any(&PartitionOwnership::single(5)));assert_eq!(plan.positions(&InputTopic::new(EVENTS), &PartitionOwnership::single(5)),BTreeMap::from([(0, offset(10)), (4, offset(10))]),@@ -314,6 +319,10 @@ mod tests {"pod {ordinal} positions only its own kept slice",);}+ assert!(+ !plan.resumes_any(&pod_of_eight(1)),+ "pod 1's only slice resets, so other pods' kept slices do not make it resume",+ );}#[test]@@ -343,7 +352,7 @@ mod tests {let plan = RestorePlan::check(&recorded, &window, 2).unwrap();- assert!(!plan.resumes_any());+ assert!(!plan.resumes_any(&PartitionOwnership::single(2)));assert_eq!(plan.resets().map(|(partition, _)| partition)diff --git a/rust/cohort-stream-processor/src/store/durability/stage.rs b/rust/cohort-stream-processor/src/store/durability/stage.rsindex 83cf87a84f5a..5c622b2de5c4 100644--- a/rust/cohort-stream-processor/src/store/durability/stage.rs+++ b/rust/cohort-stream-processor/src/store/durability/stage.rs@@ -336,8 +336,9 @@ mod tests {use rdkafka::error::KafkaResult;use tempfile::TempDir;- use crate::partitions::{InputPositions, InputTopic, ResumeOffset};- use crate::store::durability::lineage::PodOrdinal;+ use crate::partitions::{+ InputPositions, InputTopic, OwnedPositions, PartitionOwnership, ResumeOffset,+ };use crate::store::keyspace::{Behavioral, BehavioralKey, Meta, META_SCHEMA_VERSION};use crate::store::{LeafStateKey, StoreConfig};@@ -376,9 +377,11 @@ mod tests {)};OffsetManifest::capture(- PodOrdinal::STANDALONE,&BTreeSet::from([0]),- vec![at(EVENTS, 42), at(MERGES, 5)],+ OwnedPositions::for_test(+ PartitionOwnership::single(1),+ vec![at(EVENTS, 42), at(MERGES, 5)],+ ),).unwrap()}diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rsindex e4bb7c44f5f0..621f9e3f5550 100644--- a/rust/cohort-stream-processor/src/store/rocks.rs+++ b/rust/cohort-stream-processor/src/store/rocks.rs@@ -121,9 +121,9 @@ pub struct StoreConfig {/// `cf_person_records` **only** — never `cf_behavioral`, whose eviction deadlines are the sweep's/// contract. See [`super::ttl_filter`].pub person_record_ttl_days: u32,- /// The partitions this pod owns. The store records it at the first open and refuses to open- /// under another. A store that predates coverage records adopts all of its partitions as- /// complete.+ /// The partitions this pod owns. The store records it, and refuses to open under a split its+ /// record does not cover. A store that predates coverage records adopts all of its partitions+ /// as complete.pub ownership: PartitionOwnership,}@@ -195,12 +195,11 @@ pub enum StoreError {)]SchemaMismatch { found: Option<u32>, expected: u32 },- /// The store's slices belong to another split of the partitions, so its slices for this pod's- /// partitions may be missing or another pod's. `None` when the record is unreadable.+ /// The store's slices belong to a split that does not cover this pod's partitions, so its+ /// slices for them may be missing or another pod's. `None` when the record is unreadable.#[error(- "store ownership mismatch: the store was written as {}, but this is {expected}; refusing \- to open (wipe the store, and with checkpoints enabled delete this pod's local and S3 \- checkpoints too, to start its slices over)",+ "store ownership mismatch: the store was written as {}, which does not cover {expected}; \+ refusing to open (wipe the store to start this pod's slices over)",.found.map_or_else(|| "an unreadable ownership record".to_owned(), |found| found.to_string()))]OwnershipMismatch {@@ -518,25 +517,26 @@ impl CohortStore {})}- /// Records `ownership` in a store without an ownership record, and refuses a store written- /// under another. A store from before ownership records adopts the configured one.+ /// Records `ownership` in a store written under a split that covers it, and refuses any other+ /// store. A store from before ownership records adopts the configured one.fn claim_ownership(&self, ownership: PartitionOwnership) -> Result<(), StoreError> {- match self.get(Meta::CF, &Meta::encode(&META_POD_PARTITIONS))? {- None => {- self.write_batch(|batch| {- batch.put::<Meta>(&META_POD_PARTITIONS, &ownership.encode());- })?;- info!(%ownership, "recorded the store's partition ownership");- Ok(())+ if let Some(recorded) = self.get(Meta::CF, &Meta::encode(&META_POD_PARTITIONS))? {+ match PartitionOwnership::decode(&recorded) {+ Some(found) if found == ownership => return Ok(()),+ Some(found) if found.covers(&ownership) => {}+ found => {+ return Err(StoreError::OwnershipMismatch {+ found,+ expected: ownership,+ })+ }}- Some(recorded) => match PartitionOwnership::decode(&recorded) {- Some(found) if found == ownership => Ok(()),- found => Err(StoreError::OwnershipMismatch {- found,- expected: ownership,- }),- },}+ self.write_batch(|batch| {+ batch.put::<Meta>(&META_POD_PARTITIONS, &ownership.encode());+ })?;+ info!(%ownership, "recorded the store's partition ownership");+ Ok(())}/// Adopt every partition as complete in a store without the coverage stamp. The stamp rides the@@ -2902,7 +2902,7 @@ mod tests {}#[test]- fn a_store_opens_only_under_the_ownership_it_recorded() {+ fn a_store_opens_only_under_a_split_its_record_covers_and_then_records_that_split() {let pods = std::num::NonZeroU16::new(2).unwrap();let pod_zero = PartitionOwnership::new(pods, PodOrdinal::STANDALONE, 4).unwrap();let pod_one = PartitionOwnership::new(pods, PodOrdinal::from(1), 4).unwrap();@@ -2945,6 +2945,20 @@ mod tests {CohortStore::open(&under(pod_zero)),Err(StoreError::OwnershipMismatch { found: None, .. })));++ // A parent's store, or a checkpoint of it, opens under a split it covers and records it.+ let parent = TempDir::new().unwrap();+ let resharded = |ownership| StoreConfig {+ path: parent.path().join("db"),+ ownership,+ ..StoreConfig::default()+ };+ drop(CohortStore::open(&resharded(PartitionOwnership::single(4))).unwrap());+ drop(CohortStore::open(&resharded(pod_one)).expect("a covering record opens"));+ assert!(matches!(+ CohortStore::open(&resharded(PartitionOwnership::single(4))),+ Err(StoreError::OwnershipMismatch { found: Some(found), .. }) if found == pod_one+ ));}#[test]diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rsindex c53a72882198..724eee7a1563 100644--- a/rust/cohort-stream-processor/tests/events_consumer.rs+++ b/rust/cohort-stream-processor/tests/events_consumer.rs@@ -1493,7 +1493,7 @@ async fn s3_restore_replays_past_the_checkpoint_after_the_broker_moved_on() {store.clone(),dispatcher,groups.clone(),- lineage,+ claimed.clone(),config.durability_config(),1,tokio_util::sync::CancellationToken::new(),diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rsindex 16be7ec08b39..b18b795ac376 100644--- a/rust/cohort-stream-processor/tests/merge_durability.rs+++ b/rust/cohort-stream-processor/tests/merge_durability.rs@@ -945,12 +945,17 @@ async fn delete_s3_prefix(config: &Config) {/// Runs one checkpoint tick against the running dispatcher, with positions read from the broker,/// and uploads it: `upload_every_n` is 1.-async fn checkpoint_to_s3(instance: &Instance, config: &Config, groups: &Arc<InputGroups>) {+async fn checkpoint_to_s3(+ instance: &Instance,+ config: &Config,+ groups: &Arc<InputGroups>,+ claimed: ClaimedSplit,+) {let sweeper = CheckpointSweeper::new(instance.store.clone(),instance.dispatcher.clone(),groups.clone(),- config.checkpoint_lineage().expect("ordinal pod name"),+ claimed,config.durability_config(),1,tokio_util::sync::CancellationToken::new(),@@ -1132,7 +1137,7 @@ async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {NUM_PARTITIONS as usize,"the dispatcher must still own all 64 partitions at checkpoint time",);- checkpoint_to_s3(&instance, &config, &input_groups).await;+ checkpoint_to_s3(&instance, &config, &input_groups, claimed).await;shutdown.request_shutdown();instance.join().await;diff --git a/rust/cohort-stream-processor/tests/ownership_fence.rs b/rust/cohort-stream-processor/tests/ownership_fence.rsindex a137c41415f6..a9000f3811ae 100644--- a/rust/cohort-stream-processor/tests/ownership_fence.rs+++ b/rust/cohort-stream-processor/tests/ownership_fence.rs@@ -18,7 +18,8 @@ use std::time::Duration;use cohort_stream_processor::config::Config;use cohort_stream_processor::partitions::{- AdmittedSplit, Committed, InputGroups, OwnershipAudit, PartitionOwnership, ResumeOffset, Stamp,+ AdmittedSplit, Committed, InputGroups, OwnershipAudit, PartitionOwnership, PositionsError,+ ResumeOffset, Stamp,};use cohort_stream_processor::store::durability::PodOrdinal;use cohort_stream_processor::sweep::Sweeper;@@ -199,7 +200,8 @@ async fn commit_stamps_round_trip_on_every_group() {/// The audit lets a commit without a stamp pass, as an operator's offset reset writes one, and stops/// the pod when another split commits one of its partitions. It also revokes the pod's commits, so-/// the final commits of the stop cannot cover the foreign stamp, and the next boot holds.+/// the final commits of the stop cannot cover the foreign stamp, and the next boot holds. A+/// checkpoint then refuses that position.#[tokio::test]#[ignore = "requires a running Kafka broker (KAFKA_HOSTS); run with --ignored against a local stack"]async fn the_audit_stops_a_pod_whose_partition_another_split_commits() {@@ -253,6 +255,11 @@ async fn the_audit_stops_a_pod_whose_partition_another_split_commits() {AdmittedSplit::try_admit(split(1, 0), &groups).is_err(),"the next boot holds in the fence",);+ let captured = groups.owned_positions(&claimed, &every_partition());+ assert!(+ matches!(captured, Err(PositionsError::Foreign { partition: 3, .. })),+ "a checkpoint takes no position another split committed: {captured:?}",+ );inputs.delete().await;}