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): reset restored slices the broker can no longer replay (#114758)

Matheus Batistaff660dbfd153
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.md
index db60a57086f2..2c016c25344e 100644
--- a/docs/internal/realtime-cohorts/processor-runtime.md
+++ b/docs/internal/realtime-cohorts/processor-runtime.md
@@ -210,6 +210,7 @@ With durable restore enabled, a restart reopens the same local store instead, an
After a checkpoint restore, it then commits those positions and deletes the restore marker.
A failed seek, commit or delete is retried on the next poll, and nothing is dispatched until all of them succeed.
The consumer reports no liveness while one of them fails, so a failure that persists restarts the process.
+ A restored position the broker expired since the restore checked it stops the process instead, so the next boot resets that slice.
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.
diff --git a/docs/internal/realtime-cohorts/state-store-and-durability.md b/docs/internal/realtime-cohorts/state-store-and-durability.md
index e5644fa6ad9d..37d63aeb3667 100644
--- a/docs/internal/realtime-cohorts/state-store-and-durability.md
+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md
@@ -157,13 +157,15 @@ The restore judges each candidate from its `metadata.json` and `offsets.json` be
- 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 must record a position on the events topic.
+- 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)).
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.
A remote one is downloaded there, within `CHECKPOINT_IMPORT_TIMEOUT_SECS`.
A download that times out fails, and the search stops there, because older candidates are about as large.
The stage must open read-only with this build's column families and schema, and RocksDB's open checks that every SST its MANIFEST names is present at the recorded size.
+The replay window is then checked again, because a download can outlast part of it.
The restore writes the `restore.json` marker into the stage and renames the stage onto the store path.
A kill at any point leaves either the stage, which the next boot deletes, or a published store with its marker.
@@ -175,10 +177,10 @@ 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, or a schema mismatch while `COHORT_WIPE_ON_SCHEMA_MISMATCH` is on.
+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.
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 commit and a local file error also block.
+A failed listing, a failed Kafka read and a local file error also block.
### A blocked restore
@@ -190,18 +192,25 @@ A candidate whose stage failed validation is not downloaded again in later round
To give up on object storage, set `CHECKPOINT_ENABLED=false`.
The boot then creates the store, and every slice begins behind the coverage fence.
-### Slices a restore resets
+### The replay window
-A restored slice is only correct if every input resumes from the checkpoint's position for it.
-A partition the manifest does not list has no positions, so the restore resets it.
-Every other partition resumes from its positions.
+A restored slice is only correct if the broker can still replay every input past the checkpoint's position for it.
+The restore checks each partition against the enabled inputs' watermarks:
+
+- a partition the manifest does not list is reset,
+- a partition where any enabled input's position lies outside the broker's `[low, high]` range is reset,
+- every other partition resumes from its positions.
A reset deletes the slice and its coverage record, and fsyncs the write-ahead log, so the slice begins again behind the coverage fence.
-Each reset counts in `checkpoint_restore_slices_reset_total{reason}` and logs its partition and its reason.
+Each reset counts in `checkpoint_restore_slices_reset_total{reason}` and logs its partition, its reason and the watermarks.
An input whose gate turned on after the capture has no position, so it resumes from its group's commit.
+An input that is no longer enabled is ignored.
-The restore does not compare a position with the broker's retention.
-A consumer whose position the broker no longer holds resets to `latest` for the events topic and `earliest` for the followers, without a trace.
+The check holds at boot, but the consumer still has to read past the oldest retained segment before retention deletes it.
+A consumer whose position falls below the low watermark resets to `latest` for the events topic and `earliest` for the followers, without a trace.
+So keep `CHECKPOINT_IMPORT_WINDOW_HOURS` below the events topic's retention by more than a restore's catch-up time.
+A pod down longer than the window then lists no candidate and creates its store behind the coverage fence, which is the safe direction.
+The window bounds only the listing: a restore already published resumes at any age, and the checks before and after the download, and when the restore finishes, still catch a position that expired.
### Finishing a restore
@@ -211,11 +220,14 @@ A published restore stays pending until the events group commits the restored po
A failure blocks the boot.
2. The store opens, and the resets apply.
3. The events consumer seeks each owned partition to the lower of its restored position and the first event it polled, commits that seek list, then deletes the marker.
- A failed commit or delete keeps boot rewinding, and the next poll retries.
+ A failed watermark read, commit or delete keeps boot rewinding, and the next poll retries.
+ Before the commit it checks every restored position on the partitions it owns again, on every input.
+ If the broker expired one since the boot checked it, the consumer stops the process instead, and the next boot's check resets that slice.
4. Boot ends only then, so no worker folds, no follower dispatches and no checkpoint runs before the marker is gone.
The followers are assigned at their restored positions while boot settles, but they dispatch nothing.
-A crash before step 3 ends resumes the restore at the next boot, and the follower commits repeat.
+A crash before step 3 ends resumes the restore at the next boot.
+The replay window is checked again, because the broker may have expired more of it, and the follower commits repeat.
An unreadable marker means the positions are unknown, so the boot deletes the store and restores again.
It renames the store to the staging path first, so a deletion cut short never leaves a store that reopens without its marker.
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index 9e88e2143e39..c39d0bf80ebc 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -586,7 +586,10 @@ pub struct Config {
pub checkpoint_local_max_staleness_secs: u64,
/// Hours prior to now the S3 importer searches for checkpoint attempts in a PVC-lost recovery.
- #[envconfig(default = "24")]
+ /// Keep it below the `cohort_stream_events` retention by more than a restore's catch-up time: a
+ /// restore resumes about this far back, and a consumer that falls below the low watermark while
+ /// it catches up resets to `latest` without a trace.
+ #[envconfig(default = "20")]
pub checkpoint_import_window_hours: u32,
/// Historical S3 checkpoint attempts to try (newest first) before giving up on import.
@@ -1334,7 +1337,7 @@ mod tests {
checkpoint_s3_operation_timeout_secs: 120,
checkpoint_s3_attempt_timeout_secs: 20,
checkpoint_local_max_staleness_secs: 7200,
- checkpoint_import_window_hours: 24,
+ checkpoint_import_window_hours: 20,
checkpoint_import_attempt_depth: 10,
checkpoint_import_timeout_secs: 7200,
cohort_seed_consumer_enabled: false,
@@ -2117,7 +2120,7 @@ mod tests {
defaults.checkpoint_local_max_staleness(),
Duration::from_secs(7200),
);
- assert_eq!(defaults.checkpoint_import_window_hours, 24);
+ assert_eq!(defaults.checkpoint_import_window_hours, 20);
assert_eq!(defaults.checkpoint_import_attempt_depth, 10);
let env: std::collections::HashMap<String, String> = [
diff --git a/rust/cohort-stream-processor/src/consumers/boot.rs b/rust/cohort-stream-processor/src/consumers/boot.rs
index 737004a0a774..fb6a479ab060 100644
--- a/rust/cohort-stream-processor/src/consumers/boot.rs
+++ b/rust/cohort-stream-processor/src/consumers/boot.rs
@@ -75,6 +75,9 @@ pub(crate) enum BootPhase {
resume: ResumePoints,
restore: Option<PendingRestore>,
},
+ /// A restored position expired during boot and the process is stopping. Nothing seeks, settles
+ /// or folds, and the restore marker keeps the next boot on the restore path.
+ Halted,
Live,
}
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index ffc7320a45b1..e7ac7785227a 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -21,7 +21,7 @@ use metrics::{counter, gauge, histogram};
use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, StreamConsumer};
use rdkafka::message::Message;
use rdkafka::{Offset, TopicPartitionList};
-use tracing::{debug, info, warn};
+use tracing::{debug, error, info, warn};
pub use cohort_core::events::CohortStreamEvent;
@@ -54,9 +54,9 @@ use crate::partitions::pause::{ConsumerPauser, PartitionPauser};
use crate::partitions::rebalance::{CohortConsumerContext, ConsumerCommandReceiver};
use crate::partitions::router::{PartitionRouter, SeedRefusal, SeedSendOutcome, SendOutcome};
use crate::partitions::shuffle_message::ShuffleMessage;
-use crate::partitions::InputTopic;
+use crate::partitions::{list_offsets, InputTopic};
use crate::producer::MembershipSink;
-use crate::store::durability::PendingRestore;
+use crate::store::durability::{FinishError, PendingRestore};
use crate::store::StoreHandle;
use crate::workers::{EventNameGating, EvictionRestore, MergeWorkerDeps, Stage1Worker};
@@ -1188,6 +1188,7 @@ impl CohortStreamEventsConsumer {
resume.hold_back(&outcome.events);
self.rewind(resume, restore, boot_started)
}
+ BootPhase::Halted => BootPhase::Halted,
};
if transport_error {
tokio::time::sleep(RECV_ERROR_BACKOFF).await;
@@ -1280,6 +1281,9 @@ impl CohortStreamEventsConsumer {
}
if let Some(pending) = &restore {
+ let low_watermarks = |partitions: &[(&InputTopic, u16)]| {
+ list_offsets(self.consumer.as_ref(), partitions, Offset::Beginning)
+ };
let commit_events = || match &seek_list {
Some(seek_list) => self.consumer.commit(seek_list, CommitMode::Sync),
None => Ok(()),
@@ -1287,7 +1291,9 @@ impl CohortStreamEventsConsumer {
// A sync commit waits until the group coordinator answers. `block_in_place` hands this
// worker's other tasks to another thread meanwhile, so a runtime with one worker still
// serves the health server.
- match tokio::task::block_in_place(|| pending.finish(commit_events)) {
+ match tokio::task::block_in_place(|| {
+ pending.finish(&owned, low_watermarks, commit_events)
+ }) {
Ok(()) => {
gauge!(CHECKPOINT_RESTORE_BLOCKED).set(0.0);
info!(
@@ -1296,6 +1302,17 @@ impl CohortStreamEventsConsumer {
"checkpoint restore finished: the events group committed the restored positions",
);
}
+ Err(FinishError::Expired(expired)) => {
+ // The marker stays, so the next boot's window check resets these slices before
+ // anything reads them. Halted never finishes, even if a revoke drops one of them.
+ error!(
+ ?expired,
+ "the broker expired restored positions during boot; stopping so the next boot resets those slices",
+ );
+ self.handle
+ .signal_failure("checkpoint restore positions expired during boot");
+ return BootPhase::Halted;
+ }
Err(err) => {
gauge!(CHECKPOINT_RESTORE_BLOCKED).set(1.0);
warn!(
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 1464f44a2754..228b299bd4f9 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -137,8 +137,9 @@ pub const CHECKPOINT_RESTORE_TOTAL: &str = "checkpoint_restore_total";
/// Checkpoint candidates a boot restore tried, labelled by `verdict`
/// (`published`|`unusable`|`failed`) (counter).
pub const CHECKPOINT_RESTORE_CANDIDATES_TOTAL: &str = "checkpoint_restore_candidates_total";
-/// Slices a checkpoint restore deleted because it holds no positions for them, labelled by `reason`
-/// (`not_in_checkpoint`) (counter). Each one begins again behind the coverage fence.
+/// Slices a checkpoint restore deleted because the broker cannot replay them, labelled by `reason`
+/// (`not_in_checkpoint`|`replay_out_of_range`) (counter). Each one begins again behind the coverage
+/// fence.
pub const CHECKPOINT_RESTORE_SLICES_RESET_TOTAL: &str = "checkpoint_restore_slices_reset_total";
/// 1 while the boot retries a restore that cannot finish, else 0 (gauge). **Alert on it**: the pod
/// never reads ready until the logged cause is fixed. Before a restore publishes, turning
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
index 7ccfb30cbcba..24acad661f90 100644
--- a/rust/cohort-stream-processor/src/partitions/mod.rs
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -30,7 +30,9 @@ pub use partitioner::{
merge_partition_key, murmur2, partition_for, partition_of, COHORT_PARTITION_COUNT,
};
pub use pause::{ConsumerPauser, PartitionPauser};
-pub use positions::{FollowerGroup, InputGroups, InputPositions, InputTopic, ResumeOffset};
+pub use positions::{
+ list_offsets, FollowerGroup, InputGroups, InputPositions, InputTopic, ResumeOffset,
+};
pub use rebalance::{
run_rebalance_worker, CohortConsumerContext, ConsumerCommand, ConsumerCommandReceiver,
ConsumerCommandSender, RebalanceEvent, RebalanceEventReceiver,
diff --git a/rust/cohort-stream-processor/src/partitions/positions.rs b/rust/cohort-stream-processor/src/partitions/positions.rs
index 65b721842d6e..dfd5b4a8e17a 100644
--- a/rust/cohort-stream-processor/src/partitions/positions.rs
+++ b/rust/cohort-stream-processor/src/partitions/positions.rs
@@ -73,37 +73,61 @@ impl ResumeOffset {
}
}
-/// The low watermarks of `partitions` on `topic`. Asks each partition leader once, where
-/// `Consumer::fetch_watermarks` asks twice per partition.
-fn low_watermarks<C, X>(
+/// The `[low, high]` watermarks of `partitions` on `topic`. Asks each partition leader once per
+/// bound, where `Consumer::fetch_watermarks` asks twice per partition: a restore checks every
+/// partition of every input, and the boot waits on it.
+fn read_watermarks<C, X>(
client: &C,
- topic: &str,
+ topic: &InputTopic,
partitions: impl IntoIterator<Item = u16>,
-) -> KafkaResult<BTreeMap<u16, i64>>
+) -> KafkaResult<BTreeMap<u16, (i64, i64)>>
where
C: Consumer<X>,
X: ConsumerContext,
{
- let partitions: Vec<u16> = partitions.into_iter().collect();
+ let partitions: Vec<(&InputTopic, u16)> = partitions
+ .into_iter()
+ .map(|partition| (topic, partition))
+ .collect();
+ let low = list_offsets(client, &partitions, Offset::Beginning)?;
+ let high = list_offsets(client, &partitions, Offset::End)?;
+ Ok(partitions
+ .into_iter()
+ .map(|(_, partition)| partition)
+ .zip(low.into_iter().zip(high))
+ .collect())
+}
+
+/// Where `at` falls on each of `partitions`, in their order, from one `ListOffsets` request per
+/// partition leader, all within one timeout. `ListOffsets` reads the special timestamps `Beginning`
+/// and `End` as the low and high watermarks, exactly as `fetch_watermarks` asks for them.
+pub fn list_offsets<C, X>(
+ client: &C,
+ partitions: &[(&InputTopic, u16)],
+ at: Offset,
+) -> KafkaResult<Vec<i64>>
+where
+ C: Consumer<X>,
+ X: ConsumerContext,
+{
+ // librdkafka fails `offsets_for_times` on an empty list with `InvalidArg`.
if partitions.is_empty() {
- return Ok(BTreeMap::new());
+ return Ok(Vec::new());
}
- // `ListOffsets` reads the special timestamp `Beginning` as the low watermark, exactly as
- // `fetch_watermarks` asks for it.
let mut request = TopicPartitionList::new();
- for &partition in &partitions {
- request.add_partition_offset(topic, i32::from(partition), Offset::Beginning)?;
+ for &(topic, partition) in partitions {
+ request.add_partition_offset(topic.as_str(), i32::from(partition), at)?;
}
let answered = client.offsets_for_times(request, FETCH_TIMEOUT)?;
partitions
- .into_iter()
- .map(|partition| {
+ .iter()
+ .map(|&(topic, partition)| {
let elem = answered
- .find_partition(topic, i32::from(partition))
+ .find_partition(topic.as_str(), i32::from(partition))
.ok_or(KafkaError::OffsetFetch(RDKafkaErrorCode::UnknownPartition))?;
elem.error()?;
match elem.offset() {
- Offset::Offset(offset) => Ok((partition, offset)),
+ Offset::Offset(offset) => Ok(offset),
_ => Err(KafkaError::OffsetFetch(RDKafkaErrorCode::InvalidArgument)),
}
})
@@ -190,14 +214,22 @@ impl GroupReader {
Some((Ok(()), Offset::Offset(next))) => {
offsets.insert(partition, ResumeOffset::try_from(next)?);
}
- _ => uncommitted.push(partition),
+ _ => uncommitted.push((&self.topic, partition)),
}
}
- for (partition, low) in low_watermarks(&client, topic, uncommitted)? {
+ let lows = list_offsets(&client, &uncommitted, Offset::Beginning)?;
+ for (&(_, partition), low) in uncommitted.iter().zip(lows) {
offsets.insert(partition, ResumeOffset::try_from(low)?);
}
Ok(InputPositions::new(self.topic.clone(), offsets))
}
+
+ fn watermarks(
+ &self,
+ partitions: impl IntoIterator<Item = u16>,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ read_watermarks(&self.client()?, &self.topic, partitions)
+ }
}
/// A follower's group has no members, so a commit from any client needs no generation. Only
@@ -229,6 +261,7 @@ impl FollowerGroup {
pub struct InputGroups {
events: GroupReader,
followers: Vec<FollowerGroup>,
+ inputs: BTreeSet<InputTopic>,
}
impl InputGroups {
@@ -263,8 +296,20 @@ impl InputGroups {
let followers = follower_inputs
.into_iter()
.map(|(topic, group)| FollowerGroup(GroupReader::new(config, topic, group)))
+ .collect::<Vec<_>>();
+
+ let inputs = std::iter::once(events.topic().clone())
+ .chain(followers.iter().map(|follower| follower.topic().clone()))
.collect();
- Self { events, followers }
+ Self {
+ events,
+ followers,
+ inputs,
+ }
+ }
+
+ pub fn inputs(&self) -> &BTreeSet<InputTopic> {
+ &self.inputs
}
pub fn followers(&self) -> &[FollowerGroup] {
@@ -281,7 +326,39 @@ impl InputGroups {
.collect()
}
+ /// `topic`'s watermarks on partitions `0..partition_count`.
+ pub fn watermarks(
+ &self,
+ topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ self.readers()
+ .find(|reader| reader.topic() == topic)
+ .ok_or(KafkaError::MetadataFetch(
+ RDKafkaErrorCode::UnknownTopicOrPartition,
+ ))?
+ .watermarks(0..partition_count)
+ }
+
fn readers(&self) -> impl Iterator<Item = &GroupReader> {
std::iter::once(&self.events).chain(self.followers.iter().map(|follower| &follower.0))
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rdkafka::ClientConfig;
+
+ #[test]
+ fn an_empty_request_reads_nothing_from_the_broker() {
+ let unreachable: BaseConsumer = ClientConfig::new()
+ .set("bootstrap.servers", "127.0.0.1:1")
+ .create()
+ .unwrap();
+ assert_eq!(
+ list_offsets(&unreachable, &[], Offset::Beginning).unwrap(),
+ Vec::<i64>::new()
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/config.rs b/rust/cohort-stream-processor/src/store/durability/config.rs
index fb3ff214eeb8..9563166d8241 100644
--- a/rust/cohort-stream-processor/src/store/durability/config.rs
+++ b/rust/cohort-stream-processor/src/store/durability/config.rs
@@ -87,7 +87,7 @@ impl Default for DurabilityConfig {
s3_access_key_id: None,
s3_secret_access_key: None,
s3_force_path_style: false,
- checkpoint_import_window_hours: 24,
+ checkpoint_import_window_hours: 20,
s3_operation_timeout: Duration::from_secs(120),
s3_attempt_timeout: Duration::from_secs(20),
s3_max_retries: 3,
diff --git a/rust/cohort-stream-processor/src/store/durability/recovery.rs b/rust/cohort-stream-processor/src/store/durability/recovery.rs
index fb1d36a35db1..707dd5340edd 100644
--- a/rust/cohort-stream-processor/src/store/durability/recovery.rs
+++ b/rust/cohort-stream-processor/src/store/durability/recovery.rs
@@ -30,7 +30,7 @@ use super::import::{CheckpointImporter, ImportError};
use super::lineage::CheckpointLineage;
use super::manifest::{ManifestError, OffsetManifest};
use super::metadata::{CheckpointMetadata, MetadataError, METADATA_FILENAME};
-use super::restore_plan::RestorePlan;
+use super::restore_plan::{ReplayWindow, RestorePlan};
use super::stage::{
link_checkpoint, staging_path, PendingRestore, RestoredFrom, ResumeError, ValidatedStage,
};
@@ -106,6 +106,8 @@ enum Unusable {
MetadataFormat { found: u32 },
#[error("manifest format {found}")]
ManifestFormat { found: u32 },
+ #[error("the broker no longer holds what it lacks on any partition")]
+ NothingToReplay,
}
/// A candidate whose stage failed validation, so later rounds fail it without downloading it
@@ -244,7 +246,14 @@ async fn restore_until_ready(
let mut backoff = RETRY_START;
loop {
let started = Instant::now();
- let attempt = match prepare_store(&config, lineage, searched_at, &mut rejected).await
+ let attempt = match prepare_store(
+ &config,
+ lineage,
+ groups.as_ref(),
+ searched_at,
+ &mut rejected,
+ )
+ .await
{
Ok((BootStore::Restored(pending), source)) => pending
.position_followers(&groups)
@@ -287,6 +296,7 @@ async fn restore_until_ready(
async fn prepare_store(
config: &Config,
lineage: Option<CheckpointLineage>,
+ window: &impl ReplayWindow,
searched_at: DateTime<Utc>,
rejected: &mut HashSet<Rejected>,
) -> Result<(BootStore, &'static str), RestoreBlocked> {
@@ -295,7 +305,7 @@ async fn prepare_store(
remove_dir_if_present(&stage).map_err(RestoreBlocked::Local)?;
if !config.effective_wipe_on_start() && live_store_is_intact(&live) {
- match PendingRestore::resume(&live, config.partition_count()) {
+ match PendingRestore::resume(&live, window, config.partition_count()) {
Ok(Some(pending)) => return Ok((BootStore::Restored(Box::new(pending)), "pending")),
Ok(None) => return Ok((BootStore::Reopened, "reopen_live")),
Err(ResumeError::Undecodable(err)) => {
@@ -311,6 +321,7 @@ async fn prepare_store(
std::fs::rename(&live, &stage).map_err(RestoreBlocked::Local)?;
remove_dir_if_present(&stage).map_err(RestoreBlocked::Local)?;
}
+ Err(ResumeError::Window(err)) => return Err(RestoreBlocked::Positions(err)),
Err(ResumeError::Io(err)) => return Err(RestoreBlocked::Local(err)),
}
}
@@ -329,6 +340,7 @@ async fn prepare_store(
stage,
lineage,
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,
@@ -380,6 +392,12 @@ fn prepared(store: BootStore, source: &'static str, started: Instant) -> BootSto
store
}
+/// What the window check says about a candidate.
+enum Admission {
+ Replays(RestorePlan),
+ Rejected(Unusable),
+}
+
/// A complete local checkpoint attempt: both its manifest and its `metadata.json`, which the
/// sweeper writes last, decode.
struct LocalAttempt {
@@ -389,17 +407,18 @@ struct LocalAttempt {
}
/// One round's restore of candidates into the staging directory.
-struct Restore<'a> {
+struct Restore<'a, W> {
live: &'a Path,
stage: PathBuf,
lineage: CheckpointLineage,
events_topic: InputTopic,
+ window: &'a W,
partition_count: u16,
wipe_on_schema_mismatch: bool,
rejected: &'a mut HashSet<Rejected>,
}
-impl Restore<'_> {
+impl<W: ReplayWindow> Restore<'_, W> {
fn local(&mut self, attempt: LocalAttempt) -> Result<Verdict, RestoreBlocked> {
let LocalAttempt {
dir,
@@ -415,7 +434,7 @@ impl Restore<'_> {
"failed validation earlier in this process",
));
}
- if let Some(verdict) = self.admit(&metadata.id, metadata.store_schema, &manifest) {
+ if let Some(verdict) = self.admit(&metadata.id, metadata.store_schema, &manifest)? {
return Ok(verdict);
}
@@ -492,7 +511,7 @@ impl Restore<'_> {
}
Err(err) => return Ok(failed(checkpoint_id, err)),
};
- if let Some(verdict) = self.admit(checkpoint_id, metadata.store_schema, &manifest) {
+ if let Some(verdict) = self.admit(checkpoint_id, metadata.store_schema, &manifest)? {
return Ok(verdict);
}
@@ -520,33 +539,50 @@ impl Restore<'_> {
checkpoint_id: &str,
store_schema: u32,
manifest: &OffsetManifest,
- ) -> Option<Verdict> {
+ ) -> Result<Option<Verdict>, RestoreBlocked> {
if store_schema != STORE_SCHEMA_VERSION {
- return Some(schema_mismatch(
+ return Ok(Some(schema_mismatch(
checkpoint_id,
store_schema,
self.wipe_on_schema_mismatch,
- ));
+ )));
}
if manifest.ordinal() != self.lineage.ordinal() {
- return Some(failed(
+ 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) {
- return Some(failed(
+ return Ok(Some(failed(
checkpoint_id,
format_args!("its manifest records no position on {}", self.events_topic),
- ));
+ )));
+ }
+ // The plan this check builds is dropped: the one that publishes is checked after the
+ // download.
+ match self.replay_plan(manifest)? {
+ Admission::Replays(_) => Ok(None),
+ Admission::Rejected(reason) => Ok(Some(Verdict::Unusable(reason))),
}
- None
+ }
+
+ /// The window check.
+ fn replay_plan(&self, manifest: &OffsetManifest) -> Result<Admission, RestoreBlocked> {
+ let plan = RestorePlan::check(manifest, self.window, self.partition_count)
+ .map_err(RestoreBlocked::Positions)?;
+ if !plan.resumes_any() {
+ // Older candidates hold older positions, which the broker deletes first, so retrying
+ // cannot help.
+ return Ok(Admission::Rejected(Unusable::NothingToReplay));
+ }
+ Ok(Admission::Replays(plan))
}
fn publish(
@@ -564,7 +600,11 @@ impl Restore<'_> {
return Ok(failed(&checkpoint_id, err));
}
};
- let plan = RestorePlan::check(&manifest, self.partition_count);
+ // Checked again because the broker can delete positions while the candidate downloads.
+ let plan = match self.replay_plan(&manifest)? {
+ Admission::Replays(plan) => plan,
+ Admission::Rejected(reason) => return Ok(Verdict::Unusable(reason)),
+ };
let pending = staged
.publish(manifest, plan, self.live)
.map_err(RestoreBlocked::Local)?;
@@ -663,10 +703,13 @@ fn newest_fresh_local_checkpoint(
#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
+ use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use async_trait::async_trait;
use envconfig::Envconfig;
+ use rdkafka::error::KafkaResult;
+ use rdkafka::types::RDKafkaErrorCode;
use tempfile::TempDir;
use tokio_util::sync::CancellationToken;
@@ -678,6 +721,40 @@ mod tests {
const EVENTS: &str = "cohort_stream_events";
+ /// Every partition holds `[low, i64::MAX]`, and a `None` low fails the read.
+ struct FixedWindow {
+ inputs: BTreeSet<InputTopic>,
+ low: Option<i64>,
+ }
+
+ impl ReplayWindow for FixedWindow {
+ fn inputs(&self) -> &BTreeSet<InputTopic> {
+ &self.inputs
+ }
+
+ fn watermarks(
+ &self,
+ _topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ let low = self
+ .low
+ .ok_or(KafkaError::OffsetFetch(RDKafkaErrorCode::RequestTimedOut))?;
+ Ok((0..partition_count).map(|p| (p, (low, i64::MAX))).collect())
+ }
+ }
+
+ fn window_at(low: Option<i64>) -> FixedWindow {
+ FixedWindow {
+ inputs: BTreeSet::from([InputTopic::new(EVENTS)]),
+ low,
+ }
+ }
+
+ fn window() -> FixedWindow {
+ window_at(Some(0))
+ }
+
fn failure() -> Verdict {
failed("2026-10-09T16-00-00-000Z", "download failed")
}
@@ -689,7 +766,7 @@ mod tests {
(
"only unusable",
vec![
- Verdict::Unusable(Unusable::Unfinished),
+ Verdict::Unusable(Unusable::NothingToReplay),
Verdict::Unusable(Unusable::ManifestFormat { found: 1 }),
],
true,
@@ -697,7 +774,7 @@ mod tests {
(
"a failure among unusable ones",
vec![
- Verdict::Unusable(Unusable::Unfinished),
+ Verdict::Unusable(Unusable::NothingToReplay),
failure(),
Verdict::Unusable(Unusable::MetadataFormat { found: 0 }),
],
@@ -826,22 +903,28 @@ mod tests {
(s3, metadata.id)
}
- fn restore<'a>(&'a self, rejected: &'a mut HashSet<Rejected>) -> Restore<'a> {
+ fn restore<'a, W: ReplayWindow>(
+ &'a self,
+ window: &'a W,
+ rejected: &'a mut HashSet<Rejected>,
+ ) -> Restore<'a, W> {
Restore {
live: Path::new(&self.config.store_path),
stage: staging_path(Path::new(&self.config.store_path)),
lineage: CheckpointLineage::new(PodOrdinal::STANDALONE),
events_topic: InputTopic::new(EVENTS),
+ window,
partition_count: 1,
wipe_on_schema_mismatch: false,
rejected,
}
}
- async fn prepare(&self) -> Result<BootStore, RestoreBlocked> {
+ async fn prepare(&self, window: &impl ReplayWindow) -> Result<BootStore, RestoreBlocked> {
prepare_store(
&self.config,
Some(CheckpointLineage::new(PodOrdinal::STANDALONE)),
+ window,
Utc::now(),
&mut HashSet::new(),
)
@@ -914,11 +997,12 @@ mod tests {
let boot = Boot::new();
let (s3, checkpoint_id) = boot.uploaded_checkpoint();
let importer = CheckpointImporter::new(Box::new(s3), Duration::from_secs(60));
+ let window = window();
let mut rejected = HashSet::from([Rejected::Local(checkpoint_id.clone())]);
let mut search = Search::default();
let outcome = boot
- .restore(&mut rejected)
+ .restore(&window, &mut rejected)
.search_s3(&importer, 1, Utc::now(), &mut search)
.await
.unwrap();
@@ -942,7 +1026,7 @@ mod tests {
let mut search = Search::default();
let outcome = boot
- .restore(&mut HashSet::new())
+ .restore(&window(), &mut HashSet::new())
.search_s3(&importer, 10, Utc::now(), &mut search)
.await
.unwrap();
@@ -962,25 +1046,42 @@ mod tests {
std::fs::create_dir(&stage).unwrap();
std::fs::write(stage.join("000001.sst"), b"torn").unwrap();
- assert!(matches!(boot.prepare().await, Ok(BootStore::Reopened)));
+ assert!(matches!(
+ boot.prepare(&window()).await,
+ Ok(BootStore::Reopened)
+ ));
assert!(!stage.exists());
}
#[tokio::test]
- async fn a_local_checkpoint_publishes_and_stays_pending_on_the_next_boot() {
+ async fn a_local_checkpoint_stays_pending_and_each_boot_checks_its_window_again() {
let boot = Boot::new();
boot.local_checkpoint();
- let Ok(BootStore::Restored(published)) = boot.prepare().await else {
+ let Ok(BootStore::Restored(published)) = boot.prepare(&window()).await else {
panic!("a fresh local checkpoint restores");
};
assert_eq!(published.source().label(), "local");
assert!(boot.live().join(MARKER_FILENAME).is_file());
- let Ok(BootStore::Restored(resumed)) = boot.prepare().await else {
+ let Ok(BootStore::Restored(resumed)) = boot.prepare(&window()).await else {
panic!("a store with a marker resumes its restore instead of reopening");
};
assert_eq!(resumed.plan(), published.plan());
+
+ // The checkpoint resumes the events at 42.
+ let Ok(BootStore::Restored(expired)) = boot.prepare(&window_at(Some(43))).await else {
+ panic!("a pending restore resumes whatever the window holds");
+ };
+ assert_eq!(expired.plan().resets().count(), 1);
+ assert!(matches!(
+ boot.prepare(&window_at(None)).await,
+ Err(RestoreBlocked::Positions(_))
+ ));
+ assert!(
+ boot.live().join(MARKER_FILENAME).is_file(),
+ "a window that cannot be read keeps the published store for the next round",
+ );
}
#[tokio::test]
@@ -993,11 +1094,11 @@ mod tests {
}));
std::fs::write(boot.live().join(MARKER_FILENAME), b"{\"version\": 1").unwrap();
- let Ok(BootStore::Restored(pending)) = boot.prepare().await else {
+ let Ok(BootStore::Restored(pending)) = boot.prepare(&window()).await else {
panic!("the store with an unreadable marker is replaced by a restore");
};
assert_eq!(pending.source().label(), "local");
- PendingRestore::resume(&boot.live(), 1)
+ PendingRestore::resume(&boot.live(), &window(), 1)
.unwrap()
.expect("the new restore carries a readable marker");
}
@@ -1010,7 +1111,7 @@ mod tests {
let torn = boot.local_checkpoint();
std::fs::remove_file(boot.lineage_dir().join(&torn.id).join(METADATA_FILENAME)).unwrap();
- let Ok(BootStore::Restored(pending)) = boot.prepare().await else {
+ let Ok(BootStore::Restored(pending)) = boot.prepare(&window()).await else {
panic!("the newest complete attempt restores");
};
assert_eq!(pending.source().checkpoint_id(), newest.id);
@@ -1084,7 +1185,7 @@ mod tests {
};
break_attempt(&mut attempt);
- let verdict = boot.restore(&mut HashSet::new()).local(attempt);
+ let verdict = boot.restore(&window(), &mut HashSet::new()).local(attempt);
assert!(
matches!(verdict, Ok(Verdict::Failed(_))),
@@ -1092,4 +1193,57 @@ mod tests {
);
}
}
+
+ /// Holds every position on its first read, as the check before a download sees it, and none
+ /// after.
+ struct ExpiringWindow {
+ inputs: BTreeSet<InputTopic>,
+ reads: Cell<u32>,
+ }
+
+ impl ReplayWindow for ExpiringWindow {
+ fn inputs(&self) -> &BTreeSet<InputTopic> {
+ &self.inputs
+ }
+
+ fn watermarks(
+ &self,
+ _topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ let reads = self.reads.get();
+ self.reads.set(reads + 1);
+ let low = if reads == 0 { 0 } else { i64::MAX };
+ Ok((0..partition_count).map(|p| (p, (low, i64::MAX))).collect())
+ }
+ }
+
+ #[tokio::test]
+ async fn a_window_that_expires_while_the_candidate_stages_publishes_nothing() {
+ let boot = Boot::new();
+ boot.local_checkpoint();
+ let window = ExpiringWindow {
+ inputs: BTreeSet::from([InputTopic::new(EVENTS)]),
+ reads: Cell::new(0),
+ };
+ let attempt = newest_fresh_local_checkpoint(
+ &boot.lineage_dir(),
+ Duration::from_secs(3600),
+ Utc::now(),
+ )
+ .unwrap()
+ .unwrap();
+
+ let verdict = boot
+ .restore(&window, &mut HashSet::new())
+ .local(attempt)
+ .unwrap();
+
+ assert!(
+ matches!(verdict, Verdict::Unusable(Unusable::NothingToReplay)),
+ "{verdict:?}"
+ );
+ assert!(!boot.live().exists());
+ assert!(!staging_path(&boot.live()).exists());
+ }
}
diff --git a/rust/cohort-stream-processor/src/store/durability/restore_plan.rs b/rust/cohort-stream-processor/src/store/durability/restore_plan.rs
index 132a4b945d25..7639ca0ff78a 100644
--- a/rust/cohort-stream-processor/src/store/durability/restore_plan.rs
+++ b/rust/cohort-stream-processor/src/store/durability/restore_plan.rs
@@ -1,10 +1,38 @@
//! What a checkpoint restore does with each slice: resume it from the checkpoint's positions, or
-//! reset it because the checkpoint holds no positions for it.
+//! reset it because the broker can no longer replay what the checkpoint lacks.
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
+
+use rdkafka::error::{KafkaError, KafkaResult};
+use rdkafka::types::RDKafkaErrorCode;
use super::manifest::OffsetManifest;
-use crate::partitions::{InputTopic, ResumeOffset};
+use crate::partitions::{InputGroups, InputTopic, ResumeOffset};
+
+/// Watermarks of the enabled inputs.
+pub trait ReplayWindow {
+ fn inputs(&self) -> &BTreeSet<InputTopic>;
+ /// `[low, high]` of `topic` on every partition in `0..partition_count`.
+ fn watermarks(
+ &self,
+ topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>>;
+}
+
+impl ReplayWindow for InputGroups {
+ fn inputs(&self) -> &BTreeSet<InputTopic> {
+ InputGroups::inputs(self)
+ }
+
+ fn watermarks(
+ &self,
+ topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ InputGroups::watermarks(self, topic, partition_count)
+ }
+}
/// What a restore does with one partition's slice.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -18,12 +46,19 @@ pub enum SliceRestore {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResetReason {
NotInCheckpoint,
+ ReplayOutOfRange {
+ topic: InputTopic,
+ resume: ResumeOffset,
+ low: i64,
+ high: i64,
+ },
}
impl ResetReason {
pub fn label(&self) -> &'static str {
match self {
Self::NotInCheckpoint => "not_in_checkpoint",
+ Self::ReplayOutOfRange { .. } => "replay_out_of_range",
}
}
}
@@ -33,22 +68,58 @@ impl ResetReason {
pub struct RestorePlan(BTreeMap<u16, SliceRestore>);
impl RestorePlan {
- /// Check every partition against the manifest. A slice the manifest covers resumes from its
- /// positions; any other slice resets, because nothing says where its inputs resume. An input
- /// the manifest lacks, because its gate turned on after the capture, gets no position and
- /// resumes from its group's commit.
- pub fn check(manifest: &OffsetManifest, partition_count: u16) -> Self {
- Self(
- (0..partition_count)
- .map(|partition| {
- let slice = match manifest.slice(partition) {
- Some(recorded) => SliceRestore::Resume(recorded.clone()),
- None => SliceRestore::Reset(ResetReason::NotInCheckpoint),
- };
- (partition, slice)
- })
- .collect(),
- )
+ /// Check every partition's checkpoint positions against the broker. A slice resumes only when
+ /// every enabled input it records can still be replayed from its position: within
+ /// `[low, high]`. An enabled input the manifest lacks, because its gate turned on after the
+ /// capture, gets no position and resumes from its group's commit. A manifest input that is no
+ /// longer enabled is ignored.
+ pub fn check(
+ manifest: &OffsetManifest,
+ window: &impl ReplayWindow,
+ partition_count: u16,
+ ) -> KafkaResult<Self> {
+ let checked: Vec<&InputTopic> = window.inputs().intersection(manifest.inputs()).collect();
+ let bounds = checked
+ .iter()
+ .map(|&topic| Ok((topic, window.watermarks(topic, partition_count)?)))
+ .collect::<KafkaResult<BTreeMap<_, _>>>()?;
+ let mut slices = BTreeMap::new();
+ for partition in 0..partition_count {
+ let Some(recorded) = manifest.slice(partition) else {
+ slices.insert(partition, SliceRestore::Reset(ResetReason::NotInCheckpoint));
+ continue;
+ };
+ let mut resume = BTreeMap::new();
+ let mut reset = None;
+ for &topic in &checked {
+ let position = recorded[topic];
+ let (low, high) = *bounds[topic]
+ .get(&partition)
+ .ok_or(KafkaError::OffsetFetch(RDKafkaErrorCode::UnknownPartition))?;
+ if !(low..=high).contains(&position.get()) {
+ reset = Some(ResetReason::ReplayOutOfRange {
+ topic: topic.clone(),
+ resume: position,
+ low,
+ high,
+ });
+ break;
+ }
+ resume.insert(topic.clone(), position);
+ }
+ let slice = match reset {
+ Some(reason) => SliceRestore::Reset(reason),
+ None => SliceRestore::Resume(resume),
+ };
+ slices.insert(partition, slice);
+ }
+ Ok(Self(slices))
+ }
+
+ pub fn resumes_any(&self) -> bool {
+ self.0
+ .values()
+ .any(|slice| matches!(slice, SliceRestore::Resume(_)))
}
pub fn resets(&self) -> impl Iterator<Item = (u16, &ResetReason)> {
@@ -58,6 +129,20 @@ impl RestorePlan {
})
}
+ /// Every position the plan keeps: the slice, the input and where it resumes.
+ pub fn kept(&self) -> impl Iterator<Item = (u16, &InputTopic, ResumeOffset)> {
+ self.0.iter().flat_map(|(&partition, slice)| {
+ let positions = match slice {
+ SliceRestore::Resume(positions) => Some(positions),
+ SliceRestore::Reset(_) => None,
+ };
+ positions
+ .into_iter()
+ .flatten()
+ .map(move |(topic, &offset)| (partition, topic, offset))
+ })
+ }
+
/// Where `topic` resumes on every slice the plan keeps.
pub fn positions(&self, topic: &InputTopic) -> BTreeMap<u16, ResumeOffset> {
self.0
@@ -73,13 +158,40 @@ impl RestorePlan {
#[cfg(test)]
mod tests {
use super::*;
- use std::collections::BTreeSet;
-
use crate::partitions::InputPositions;
use crate::store::durability::lineage::PodOrdinal;
const EVENTS: &str = "cohort_stream_events";
const MERGES: &str = "person_merge_events";
+ const SEEDS: &str = "cohort_stream_seed_events";
+
+ struct Window {
+ inputs: BTreeSet<InputTopic>,
+ bounds: BTreeMap<(&'static str, u16), (i64, i64)>,
+ }
+
+ impl ReplayWindow for Window {
+ fn inputs(&self) -> &BTreeSet<InputTopic> {
+ &self.inputs
+ }
+
+ fn watermarks(
+ &self,
+ topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ Ok((0..partition_count)
+ .map(|partition| {
+ let bounds = self
+ .bounds
+ .get(&(topic.as_str(), partition))
+ .copied()
+ .unwrap_or((0, 1_000));
+ (partition, bounds)
+ })
+ .collect())
+ }
+ }
fn offset(value: i64) -> ResumeOffset {
ResumeOffset::try_from(value).unwrap()
@@ -111,14 +223,35 @@ mod tests {
OffsetManifest::capture(PodOrdinal::STANDALONE, &owned, positions).unwrap()
}
+ type Bounds = ((&'static str, u16), (i64, i64));
+
+ fn window(inputs: &[&str], bounds: &[Bounds]) -> Window {
+ Window {
+ inputs: inputs.iter().map(|topic| InputTopic::new(*topic)).collect(),
+ bounds: bounds.iter().copied().collect(),
+ }
+ }
+
#[test]
- fn a_slice_the_manifest_lacks_resets_and_every_other_resumes_from_its_positions() {
+ fn a_slice_resumes_only_when_every_enabled_recorded_input_can_still_replay() {
let recorded = manifest(&[
(0, &[(EVENTS, 10), (MERGES, 5)]),
- (2, &[(EVENTS, 7), (MERGES, 1)]),
+ (1, &[(EVENTS, 10), (MERGES, 5)]),
+ (2, &[(EVENTS, 10), (MERGES, 5)]),
+ (4, &[(EVENTS, 10), (MERGES, 5)]),
]);
+ // Partition 4 sits on both edges: caught up on the events, at the oldest retained merge.
+ let window = window(
+ &[EVENTS, MERGES],
+ &[
+ ((MERGES, 1), (6, 50)),
+ ((EVENTS, 2), (0, 9)),
+ ((EVENTS, 4), (3, 10)),
+ ((MERGES, 4), (5, 5)),
+ ],
+ );
- let plan = RestorePlan::check(&recorded, 3);
+ let plan = RestorePlan::check(&recorded, &window, 5).unwrap();
assert_eq!(
plan.0,
@@ -130,19 +263,72 @@ mod tests {
(InputTopic::new(MERGES), offset(5)),
])),
),
- (1, SliceRestore::Reset(ResetReason::NotInCheckpoint)),
+ (
+ 1,
+ SliceRestore::Reset(ResetReason::ReplayOutOfRange {
+ topic: InputTopic::new(MERGES),
+ resume: offset(5),
+ low: 6,
+ high: 50,
+ }),
+ ),
(
2,
+ SliceRestore::Reset(ResetReason::ReplayOutOfRange {
+ topic: InputTopic::new(EVENTS),
+ resume: offset(10),
+ low: 0,
+ high: 9,
+ }),
+ ),
+ (3, SliceRestore::Reset(ResetReason::NotInCheckpoint)),
+ (
+ 4,
SliceRestore::Resume(BTreeMap::from([
- (InputTopic::new(EVENTS), offset(7)),
- (InputTopic::new(MERGES), offset(1)),
+ (InputTopic::new(EVENTS), offset(10)),
+ (InputTopic::new(MERGES), offset(5)),
])),
),
]),
);
+ assert!(plan.resumes_any());
assert_eq!(
plan.positions(&InputTopic::new(EVENTS)),
- BTreeMap::from([(0, offset(10)), (2, offset(7))]),
+ BTreeMap::from([(0, offset(10)), (4, offset(10))]),
+ );
+ }
+
+ #[test]
+ fn inputs_enabled_on_one_side_only_neither_reset_nor_resume_a_slice() {
+ let recorded = manifest(&[(0, &[(EVENTS, 10), (MERGES, 5)])]);
+ // The merge input was disabled after the capture, and the seed input enabled after it.
+ let window = window(&[EVENTS, SEEDS], &[((MERGES, 0), (900, 1_000))]);
+
+ let plan = RestorePlan::check(&recorded, &window, 1).unwrap();
+
+ assert_eq!(
+ plan.0,
+ BTreeMap::from([(
+ 0,
+ SliceRestore::Resume(BTreeMap::from([(InputTopic::new(EVENTS), offset(10))])),
+ )]),
+ );
+ assert!(plan.positions(&InputTopic::new(SEEDS)).is_empty());
+ }
+
+ #[test]
+ fn a_plan_that_resets_every_slice_resumes_nothing() {
+ let recorded = manifest(&[(0, &[(EVENTS, 10)])]);
+ let window = window(&[EVENTS], &[((EVENTS, 0), (11, 20))]);
+
+ let plan = RestorePlan::check(&recorded, &window, 2).unwrap();
+
+ assert!(!plan.resumes_any());
+ assert_eq!(
+ plan.resets()
+ .map(|(partition, _)| partition)
+ .collect::<Vec<_>>(),
+ [0, 1],
);
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/stage.rs b/rust/cohort-stream-processor/src/store/durability/stage.rs
index c073c7154cdc..62ea69bdf3eb 100644
--- a/rust/cohort-stream-processor/src/store/durability/stage.rs
+++ b/rust/cohort-stream-processor/src/store/durability/stage.rs
@@ -7,6 +7,7 @@
//! boot on the restore path, so a crash never reopens the restored store at the broker's old
//! offsets.
+use std::collections::HashSet;
use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
@@ -18,9 +19,9 @@ use tracing::warn;
use super::manifest::OffsetManifest;
use super::metadata::CheckpointMetadata;
-use super::restore_plan::RestorePlan;
+use super::restore_plan::{ReplayWindow, RestorePlan};
use crate::observability::metrics::CHECKPOINT_RESTORE_SLICES_RESET_TOTAL;
-use crate::partitions::InputGroups;
+use crate::partitions::{InputGroups, InputTopic, ResumeOffset};
use crate::store::{CohortStore, StoreError};
/// The marker a published restore carries inside the store directory. RocksDB ignores files it
@@ -62,8 +63,8 @@ impl RestoredFrom {
}
}
-/// What `restore.json` holds. The manifest travels with it, so a resumed restore rebuilds its plan
-/// from it.
+/// What `restore.json` holds. The manifest travels with it, so a resumed restore can check the
+/// replay window again.
#[derive(Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct RestoreRecord {
@@ -93,7 +94,8 @@ impl ValidatedStage {
/// Fsyncs the staged files, writes the marker, renames the stage onto `live`, then fsyncs the
/// parent. A kill at any point leaves either the stage, which the next boot deletes, or a
- /// published store with its marker. `plan` says which slices the restore keeps.
+ /// published store with its marker. `plan` says which slices the restore keeps. Build it after
+ /// the stage validates, because the broker can delete positions while the candidate downloads.
pub fn publish(
self,
manifest: OffsetManifest,
@@ -148,6 +150,8 @@ pub enum ResumeError {
/// again.
#[error("the restore marker is unreadable")]
Undecodable(#[source] serde_json::Error),
+ #[error("reading the replay window failed")]
+ Window(#[source] KafkaError),
#[error(transparent)]
Io(#[from] io::Error),
}
@@ -162,8 +166,14 @@ pub struct PendingRestore {
}
impl PendingRestore {
- /// Reads the marker of a store found at boot. `None` when the store carries no marker.
- pub(crate) fn resume(live: &Path, partition_count: u16) -> Result<Option<Self>, ResumeError> {
+ /// Reads the marker of a store found at boot and re-checks the replay window, because the
+ /// broker may have expired more of it since the restore was published. `None` when the store
+ /// carries no marker.
+ pub(crate) fn resume(
+ live: &Path,
+ window: &impl ReplayWindow,
+ partition_count: u16,
+ ) -> Result<Option<Self>, ResumeError> {
let marker = live.join(MARKER_FILENAME);
let bytes = match std::fs::read(&marker) {
Ok(bytes) => bytes,
@@ -177,7 +187,8 @@ impl PendingRestore {
format_args!("restore record version {}", record.version),
)));
}
- let plan = RestorePlan::check(&record.manifest, partition_count);
+ let plan = RestorePlan::check(&record.manifest, window, partition_count)
+ .map_err(ResumeError::Window)?;
Ok(Some(Self {
marker,
record,
@@ -220,12 +231,36 @@ impl PendingRestore {
Ok(())
}
- /// Ends the restore: `commit_events` commits the events group's restored positions, and only
- /// then does the marker go. On any error the marker stays, so the next boot resumes the restore.
+ /// Ends the restore once every position it kept still holds. Each kept position on a partition
+ /// in `owned` is checked against its input's low watermark first: the plan was checked before
+ /// boot, and a consumer whose position fell below the low watermark since then skips ahead
+ /// without a trace. `low_watermarks` reads all of them in one call, because the events consumer
+ /// blocks on it within its liveness deadline. It answers in the order it was asked. Then
+ /// `commit_events` commits the events group's restored positions, and only then does the marker
+ /// go. On any error the marker stays, so the next boot resumes the restore and its window check
+ /// resets what expired.
pub(crate) fn finish(
&self,
+ owned: &HashSet<i32>,
+ low_watermarks: impl FnOnce(&[(&InputTopic, u16)]) -> KafkaResult<Vec<i64>>,
commit_events: impl FnOnce() -> KafkaResult<()>,
) -> Result<(), FinishError> {
+ let (partitions, positions): (Vec<(&InputTopic, u16)>, Vec<ResumeOffset>) = self
+ .plan
+ .kept()
+ .filter(|&(partition, _, _)| owned.contains(&i32::from(partition)))
+ .map(|(partition, topic, position)| ((topic, partition), position))
+ .unzip();
+ let lows = low_watermarks(&partitions).map_err(FinishError::Watermarks)?;
+ let expired: Vec<(InputTopic, u16)> = partitions
+ .iter()
+ .zip(positions.iter().zip(lows))
+ .filter(|&(_, (position, low))| position.get() < low)
+ .map(|(&(topic, partition), _)| (topic.clone(), partition))
+ .collect();
+ if !expired.is_empty() {
+ return Err(FinishError::Expired(expired));
+ }
commit_events().map_err(FinishError::Commit)?;
match std::fs::remove_file(&self.marker) {
Ok(()) => {}
@@ -238,6 +273,11 @@ impl PendingRestore {
#[derive(Debug, thiserror::Error)]
pub enum FinishError {
+ /// The boot must stop rather than retry: these slices need the next boot's reset.
+ #[error("the broker expired restored positions since the restore checked them: {0:?}")]
+ Expired(Vec<(InputTopic, u16)>),
+ #[error("reading the inputs' low watermarks failed")]
+ Watermarks(#[source] KafkaError),
#[error("committing the events group's restored positions failed")]
Commit(#[source] KafkaError),
#[error("deleting the restore marker failed")]
@@ -279,9 +319,12 @@ fn sync_dir(dir: &Path) -> io::Result<()> {
#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
+ use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use rdkafka::types::RDKafkaErrorCode;
+
+ use rdkafka::error::KafkaResult;
use tempfile::TempDir;
use crate::partitions::{InputPositions, InputTopic, ResumeOffset};
@@ -292,6 +335,29 @@ mod tests {
const EVENTS: &str = "cohort_stream_events";
const MERGES: &str = "person_merge_events";
+ struct OpenWindow(BTreeSet<InputTopic>);
+
+ impl ReplayWindow for OpenWindow {
+ fn inputs(&self) -> &BTreeSet<InputTopic> {
+ &self.0
+ }
+
+ fn watermarks(
+ &self,
+ _topic: &InputTopic,
+ partition_count: u16,
+ ) -> KafkaResult<BTreeMap<u16, (i64, i64)>> {
+ Ok((0..partition_count).map(|p| (p, (0, i64::MAX))).collect())
+ }
+ }
+
+ fn window() -> OpenWindow {
+ OpenWindow(BTreeSet::from([
+ InputTopic::new(EVENTS),
+ InputTopic::new(MERGES),
+ ]))
+ }
+
/// Slice 0 resumes the events at 42 and the merges at 5.
fn manifest() -> OffsetManifest {
let at = |topic: &str, offset: i64| {
@@ -382,11 +448,11 @@ mod tests {
}
#[test]
- fn a_published_restore_stays_pending_until_the_events_group_commits() {
+ fn a_published_restore_finishes_only_when_its_positions_hold_and_the_events_group_commits() {
let root = TempDir::new().unwrap();
let live = root.path().join("store");
let stage = staged(root.path());
- let plan = RestorePlan::check(&manifest(), 1);
+ let plan = RestorePlan::check(&manifest(), &window(), 1).unwrap();
let published = ValidatedStage::validate(stage.clone(), local())
.unwrap()
@@ -404,23 +470,70 @@ mod tests {
);
drop(store);
- let resumed = PendingRestore::resume(&live, 1)
+ let resumed = PendingRestore::resume(&live, &window(), 1)
.unwrap()
.expect("the marker survives the store's open");
assert_eq!(resumed.plan(), &plan);
assert_eq!(resumed.source(), &local());
+ let owned: HashSet<i32> = HashSet::from([0]);
+ let merges = InputTopic::new(MERGES);
+ let low = |events: i64, merge_low: i64| {
+ let merges = merges.clone();
+ move |partitions: &[(&InputTopic, u16)]| -> KafkaResult<Vec<i64>> {
+ Ok(partitions
+ .iter()
+ .map(|&(topic, _)| if *topic == merges { merge_low } else { events })
+ .collect())
+ }
+ };
+ // Every position at its low watermark still replays.
+ let held = low(42, 5);
+ let merges_expired = low(42, 6);
+ let committed = Cell::new(false);
+ let commit = || {
+ committed.set(true);
+ Ok(())
+ };
+ assert!(matches!(
+ published.finish(&owned, &merges_expired, commit),
+ Err(FinishError::Expired(ref expired)) if expired == &[(merges.clone(), 0)]
+ ));
+ assert!(
+ !committed.get(),
+ "an expired follower position stops the finish before any commit"
+ );
+ let unreadable = |_: &[(&InputTopic, u16)]| -> KafkaResult<Vec<i64>> {
+ Err(KafkaError::OffsetFetch(RDKafkaErrorCode::RequestTimedOut))
+ };
+ assert!(matches!(
+ published.finish(&owned, unreadable, commit),
+ Err(FinishError::Watermarks(_))
+ ));
+ assert!(
+ !committed.get(),
+ "a failed watermark read stops the finish before any commit"
+ );
+
let refused = || Err(KafkaError::OffsetFetch(RDKafkaErrorCode::RequestTimedOut));
assert!(matches!(
- published.finish(refused),
+ published.finish(&HashSet::new(), low(i64::MAX, i64::MAX), refused),
+ Err(FinishError::Commit(_)),
+ ));
+ assert!(matches!(
+ published.finish(&owned, &held, refused),
Err(FinishError::Commit(_))
));
assert!(
- PendingRestore::resume(&live, 1).unwrap().is_some(),
+ PendingRestore::resume(&live, &window(), 1)
+ .unwrap()
+ .is_some(),
"a restore that did not finish is still pending",
);
- published.finish(|| Ok(())).unwrap();
- assert!(PendingRestore::resume(&live, 1).unwrap().is_none());
+ published.finish(&owned, &held, || Ok(())).unwrap();
+ assert!(PendingRestore::resume(&live, &window(), 1)
+ .unwrap()
+ .is_none());
}
}