Skip to content

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

feat(cohorts): per-pod processor checkpoints with a staged restore (#114756)

Matheus Batista94887825a58c
diff --git a/docs/internal/realtime-cohorts/invariants.md b/docs/internal/realtime-cohorts/invariants.md
index 794f5be0cbd5..62734f8e5f4e 100644
--- a/docs/internal/realtime-cohorts/invariants.md
+++ b/docs/internal/realtime-cohorts/invariants.md
@@ -70,7 +70,7 @@ Most of these are not enforced by a single test, and a violation usually shows u
- Kept by: every consumer forces the write-ahead log to disk before each commit, and skips the commit if that fails.
- If broken: a crash loses writes whose inputs are never redelivered.
- Limit: it covers writes that succeeded.
- A live event skipped on a store error, the batch the events consumer drops when boot recovery settles, a wiped slice, and a follower rewind that failed after a checkpoint restore are outside it.
+ A live event skipped on a store error, the batch the events consumer drops when boot recovery settles, and a wiped slice are outside it.
- See [state store and durability](state-store-and-durability.md#the-durability-invariant).
**9. A later success never commits past an earlier failure that set a floor.**
@@ -196,7 +196,7 @@ Most of these are not enforced by a single test, and a violation usually shows u
- Limit: the walk covers only rows the store holds.
It cannot restore a skipped event or find a person whose first Stage 2 row was never written.
Coverage catches a slice that lost its history, but not a stale slice, one whose partition another writer advanced while this store held older state.
- Nothing in one pod produces a stale slice except a rollback of the store or a checkpoint restore.
+ Nothing in one pod produces a stale slice except a rollback of the store.
**25. A run completes only with proof.**
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.md
index 5352fec00f08..db60a57086f2 100644
--- a/docs/internal/realtime-cohorts/processor-runtime.md
+++ b/docs/internal/realtime-cohorts/processor-runtime.md
@@ -191,10 +191,12 @@ Nothing moves state between pods, so more than one replica is unsupported, and r
At boot the processor:
1. validates its configuration and refuses unsafe combinations,
-2. loads the catalog once,
-3. decides where the store comes from: with durable restore enabled, the live store on disk or a checkpoint, otherwise an empty store,
-4. checks the partition counts of the co-partitioned topics against broker metadata,
-5. starts the timer loops and the events consumer, and starts the followers once the catalog has loaded and boot recovery has ended.
+2. binds the health server, so `/_health` answers from here on and `/_ready` reads not ready,
+3. loads the catalog once,
+4. 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,
+5. checks the partition counts of the co-partitioned topics against broker metadata,
+6. 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.
By default the store is wiped at boot, so there is nothing to recover, and the events consumer dispatches from its first poll.
@@ -203,10 +205,11 @@ With durable restore enabled, a restart reopens the same local store instead, an
1. It polls until two consecutive polls report the same non-empty assignment.
It dispatches nothing these polls return, and records the lowest offset it polled on each partition.
2. It deletes the slices of partitions it does not own, and re-produces every transfer waiting in the merge outbox, clearing each outbox row from outside the worker.
-3. After a checkpoint restore, it lowers each owned partition's resume point to the offset the checkpoint recorded.
+3. After a checkpoint restore, it lowers each owned partition's resume point to the position the restore kept for it.
4. It seeks every owned partition back to its resume point, so every event it polled and did not dispatch is fetched again.
- A failed seek is retried on the next poll, and nothing is dispatched until every seek succeeds.
- The consumer reports no liveness while a seek fails, so a seek that keeps failing restarts the process.
+ 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.
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 fea75965bac2..e5644fa6ad9d 100644
--- a/docs/internal/realtime-cohorts/state-store-and-durability.md
+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md
@@ -117,14 +117,14 @@ A deployment that relies on backfilled state must enable it.
With durable restore on, the processor picks where its store comes from at boot, in this order:
1. **Reopen the live store** on the persistent volume, if it is there.
-2. **A local checkpoint**, if checkpoints are enabled and a recent one exists.
-3. **A remote checkpoint** downloaded from object storage, if checkpoints are enabled.
-4. **An empty store**, the cold start.
+ A store that carries a `restore.json` marker holds a checkpoint restore that has not finished, so that restore resumes instead (see [finishing a restore](#finishing-a-restore)).
+2. **A local checkpoint**, if checkpoints are enabled and one was captured within `CHECKPOINT_LOCAL_MAX_STALENESS_SECS`.
+3. **A remote checkpoint** from object storage, newest first, if checkpoints are enabled.
+4. **An empty store**, the cold start, when checkpoints are disabled or nothing is restorable.
+Before it decides, the boot deletes a leftover `<STORE_PATH>.restore` staging directory, which a restore killed midway leaves behind.
Checkpoints, `CHECKPOINT_ENABLED`, are disabled by default, so in practice the choice is between reopening the live store and starting empty.
-A checkpoint restore that fails to clear the store, copy or download the checkpoint, or read its offsets falls back to a cold start.
-The restore never opens the RocksDB files, so a checkpoint whose files cannot open passes it, and the store open that follows fails the pod instead.
-A live store that fails to open does not fall back either: the pod fails to start.
+A live store that fails to open does not fall back to a checkpoint: the pod fails to start.
A cold start does not rebuild history.
The consumers resume at their committed offsets, so the store only fills from new traffic, and every cohort's past membership has to come back through a backfill.
@@ -143,17 +143,114 @@ With durable restore on, the processor also:
Nothing is dispatched to a worker, from the events consumer or a follower, until these boot steps end.
[Processor runtime](processor-runtime.md#startup) lists them in order.
-After a checkpoint restore it also rewinds the consumers to the offsets recorded in the checkpoint.
-The events consumer folds this rewind into its boot seek, which it retries until it succeeds, and dispatches nothing before.
-The merge, transfer, cascade and seed followers get one attempt each.
-A failed attempt only logs a warning, and a checkpoint with no offsets for the topic skips the rewind silently.
-Either way the follower resumes at its broker-stored offsets.
-Those can be ahead of the restored state, and the inputs in between are never applied.
-
When a partition is revoked, its worker drains and exits, and its slice is deleted with its coverage record.
State never moves between pods, which is why the processor runs as a single pod.
[Processor runtime](processor-runtime.md#rebalance-and-the-single-pod-constraint) explains that constraint.
+### Choosing a checkpoint
+
+The 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.
+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 must record a position on the events topic.
+
+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 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.
+
+The first candidate that publishes wins, and no older one is downloaded.
+When none publishes:
+
+| What the candidates were | Outcome |
+| --------------------------- | ----------------------------------------------------- |
+| 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.
+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 blocked restore
+
+A blocked boot retries in process, with a backoff that starts at 30 seconds and doubles to 5 minutes.
+The health server is already listening, so `/_health` answers and `/_ready` returns 503 with "events consumer boot recovery in progress".
+`checkpoint_restore_blocked` reads 1 while it retries, and each round logs the error.
+Every round measures the local staleness window and the remote listing window up to the first round's start, so a candidate that failed stays a candidate however long the boot blocks.
+A candidate whose stage failed validation is not downloaded again in later rounds.
+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
+
+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 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.
+An input whose gate turned on after the capture has no position, so it resumes from its group's commit.
+
+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.
+
+### Finishing a restore
+
+A published restore stays pending until the events group commits the restored positions:
+
+1. Before the store opens, the restore commits each follower group's positions on the partitions it keeps.
+ 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.
+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.
+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.
+
+## Checkpoints
+
+With `CHECKPOINT_ENABLED`, the processor takes a whole-store RocksDB checkpoint into `CHECKPOINT_LOCAL_DIR` every `CHECKPOINT_INTERVAL_MS`, and uploads one in every few to object storage, at `CHECKPOINT_S3_UPLOAD_INTERVAL_MS`.
+The loop starts when boot ends.
+Checkpoints require durable restore, a bucket, and an absolute checkpoint directory without `..` on the store's filesystem but outside the store and its `<STORE_PATH>.restore` staging directory, and the pod fails at start without them.
+
+- **One lineage per pod.**
+ A pod's checkpoints live under `cohort_stream_state/<ordinal>`, locally and in object storage, where the ordinal is the number that ends the StatefulSet pod name in `POD_NAME`.
+ Ordinal 0 keeps the single pod's original layout.
+ Two pods never read or write each other's checkpoints.
+- **Positions from the broker.**
+ Each checkpoint carries `offsets.json`: for every owned slice, the committed offset of every enabled input's consumer group, or the low watermark where the group has none, so idle partitions are recorded too.
+ The positions are read after a write-ahead-log flush and before the checkpoint.
+ Every commit follows a flush of its own, so the checkpoint holds at least the state the positions cover.
+- **Incremental uploads.**
+ An upload sends only the files the previous upload of the same process lacks, so the first upload after every start is full.
+- **No expiry.**
+ Objects are not expired, because a chain of incremental uploads can reference an object of any age.
+
+The uploader is built on the first upload, so an outage of object storage never stops a pod that has its store.
+A failed build counts `checkpoint_uploads_total{result="unavailable"}`, and the next upload tries again.
+
+These metrics follow checkpoints:
+
+- `checkpoint_last_upload_timestamp_seconds` is the last successful upload, and starts at process start, so a staleness alert fires only once its threshold passes,
+- `checkpoint_last_capture_timestamp_seconds` is the last captured manifest,
+- `checkpoint_uploads_total{result}` counts uploads,
+- `checkpoint_capture_failures_total{reason}` counts ticks skipped before the checkpoint,
+- `checkpoint_restore_total{source}` counts where each boot's store came from: `reopen_live`, `pending`, `local`, `s3` or `cold`,
+- `checkpoint_restore_candidates_total{verdict}` counts the candidates a restore tried,
+- `checkpoint_restore_blocked` reads 1 while a restore blocks the boot.
+
## Slice coverage
A slice is one partition's state in one store.
@@ -161,13 +258,13 @@ A slice that lost its history looks like any other empty slice, so each slice ca
The record says either that the slice is complete, or that it holds every event its partition delivered after an instant, and maybe some before.
It lives in `cf_person_records` under a 3-byte key, `[partition][0xFE]`, which no person-record read reaches.
-| What happens | Coverage |
-| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
-| The store is created: none on disk, a wipe at start, a wipe on schema mismatch, or a failed restore | The open stamps `cf_meta[slice_coverage]`, with no records. Each slice begins when its partition is assigned |
-| A store with the stamp reopens | Each slice resumes its own record |
-| A store without the stamp reopens | It predates coverage records. The open writes `complete` for every partition and the stamp in one batch, so it adopts once |
-| A revoke, the boot deletion of an unowned partition, or a move-in wipe | `delete_partition` deletes the record with the slice, and the next worker begins the slice anew from its assignment |
-| A checkpoint restore | The record and the stamp travel inside the checkpoint. A checkpoint from before coverage records is adopted |
+| What happens | Coverage |
+| ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
+| The store is created: none on disk, a wipe at start, a wipe on schema mismatch, or nothing to restore | The open stamps `cf_meta[slice_coverage]`, with no records. Each slice begins when its partition is assigned |
+| A store with the stamp reopens | Each slice resumes its own record |
+| A store without the stamp reopens | It predates coverage records. The open writes `complete` for every partition and the stamp in one batch, so it adopts once |
+| A revoke, the boot deletion of an unowned partition, or a move-in wipe | `delete_partition` deletes the record with the slice, and the next worker begins the slice anew from its assignment |
+| A checkpoint restore | The record and the stamp travel inside the checkpoint. A slice the restore cannot replay is reset with its record and begins anew |
A reconcile certifies its partition only when the slice holds the run's history: the slice is complete, or it began at or before the run's boundary.
Otherwise the partition withholds the run, as [the reconcile guard](seed-apply-and-reconcile.md#the-walk) describes, and its `covered_since` is the boundary a disaster-recovery run must pin.
@@ -179,7 +276,7 @@ That is the trust every store had before coverage records existed.
So before rolling forward again, wipe any store that an older image created.
Coverage does not detect a stale slice, one whose partition another writer advanced while this store held older state.
-With one pod, only a rollback of the store or a checkpoint restore produces one.
+With one pod, only a rollback of the store produces one.
Three metrics follow coverage:
@@ -229,7 +326,10 @@ A lint rule denies direct calls to most store I/O methods, and the synchronous s
- Reopening the live store checks only that RocksDB's `CURRENT` file exists.
A damaged store that has one is chosen, fails to open, and the pod crash-loops.
It never falls back to a checkpoint.
-- A store directory without a `CURRENT` file is neither reopened nor wiped, and the open fails on the missing schema stamp.
+- With checkpoints disabled, a store directory without a `CURRENT` file is neither reopened nor wiped, and the open fails on the missing schema stamp.
+ With 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.
- Static group membership keeps a restart from causing a revoke.
A second group member, or a pod that loses its session or stops polling, still causes one.
Each revoke deletes the whole slice, including merge transfers not yet sent, whose merge offsets may already be committed.
diff --git a/rust/cohort-stream-processor/clippy.toml b/rust/cohort-stream-processor/clippy.toml
index f6d46abdf46d..7d6c30f97333 100644
--- a/rust/cohort-stream-processor/clippy.toml
+++ b/rust/cohort-stream-processor/clippy.toml
@@ -29,6 +29,7 @@ disallowed-methods = [
{ path = "cohort_stream_processor::store::rocks::CohortStore::resume_or_begin_slice", reason = "async code must use StoreHandle::resume_or_begin_slice — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::flush", reason = "async code must go through StoreHandle; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::flush_wal_sync", reason = "async code must use StoreHandle::flush_wal_sync; sync contexts need a module-level allow — see store/handle.rs" },
+ { path = "cohort_stream_processor::store::rocks::CohortStore::reset_slices", reason = "async code must not write the store on a runtime thread; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::create_checkpoint", reason = "async code must go through the checkpoint sweeper's own offload; sync contexts need a module-level allow — see store/handle.rs" },
{ path = "cohort_stream_processor::store::rocks::CohortStore::stats_snapshot", reason = "async code must use StoreHandle::stats_snapshot; sync contexts need a module-level allow — see store/handle.rs" },
]
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index 0c2abc9cf418..9e88e2143e39 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -1,7 +1,7 @@
//! Service configuration, loaded from environment variables via `envconfig`.
use std::num::NonZeroUsize;
-use std::path::PathBuf;
+use std::path::{Component, Path, PathBuf};
use std::time::Duration;
use anyhow::{ensure, Context};
@@ -13,7 +13,8 @@ use rdkafka::ClientConfig;
use tracing::warn;
use crate::partitions::pacing::{AgeMs, Hysteresis, SeedPacingConfig, UsedPct};
-use crate::store::durability::DurabilityConfig;
+use crate::store::durability::stage::staging_path;
+use crate::store::durability::{CheckpointLineage, DurabilityConfig, NotAnOrdinalPod, PodOrdinal};
use crate::store::{OffloadConfig, OffloadMode, StoreConfig};
use crate::workers::seed_run::RunBudget;
use crate::workers::{CascadeConfig, EventNameGating, TransferRetryPolicy};
@@ -518,8 +519,9 @@ pub struct Config {
#[envconfig(default = "900000")]
pub checkpoint_s3_upload_interval_ms: u64,
- /// Base directory for local checkpoints. Must be a subtree separate from `store_path` on the same
- /// filesystem (RocksDB refuses to checkpoint into its own directory and hard-links SSTs).
+ /// Base directory for local checkpoints. Must be an absolute path outside `store_path` and its
+ /// `<store_path>.restore` staging directory, on the same filesystem (RocksDB refuses to
+ /// checkpoint into its own directory and hard-links SSTs, and every boot deletes the stage).
#[envconfig(default = "cohort-checkpoints")]
pub checkpoint_local_dir: String,
@@ -591,9 +593,10 @@ pub struct Config {
#[envconfig(default = "10")]
pub checkpoint_import_attempt_depth: usize,
- /// Max time for a complete S3 checkpoint import — list + metadata + all files + fallbacks (secs).
- /// Kept under `max.poll.interval.ms` so a long restore does not get the consumer kicked.
- #[envconfig(default = "240")]
+ /// Max time to download one S3 checkpoint candidate's files (secs). A slower candidate fails and
+ /// ends the search, because older candidates are about as large. It bounds the size of a store
+ /// that can restore, so keep it above a full store volume at the volume's write throughput.
+ #[envconfig(default = "7200")]
pub checkpoint_import_timeout_secs: u64,
}
@@ -811,7 +814,9 @@ impl Config {
/// - Reconcile scan and tick limits must be non-zero; a zero page would falsely certify an
/// unscanned snapshot, while Tokio rejects a zero timer interval.
/// - `checkpoint_enabled` requires `durable_restore_enabled`: without it the restored DB is wiped
- /// on open, silently discarding the restore.
+ /// on open, silently discarding the restore. It also requires a bucket, non-zero knobs, an
+ /// absolute checkpoint directory apart from the store, and a pod name with an ordinal, so a
+ /// misconfigured pod fails at start instead of running without checkpoints.
/// - `durable_restore_enabled` + `cohort_cascade_enabled` requires `durable_restore_single_pod`
/// and a pod identity: `pod_identity()` alone is not a single-pod signal (set on every k8s pod).
pub fn validate_startup(&self) -> anyhow::Result<()> {
@@ -901,6 +906,9 @@ impl Config {
"CHECKPOINT_ENABLED requires DURABLE_RESTORE_ENABLED: restoring a checkpoint without \
reopen-live is meaningless.",
);
+ if self.checkpoint_enabled {
+ self.validate_checkpoints()?;
+ }
if self.durable_restore_enabled && self.cohort_cascade_enabled {
let single_pod_static =
@@ -936,6 +944,103 @@ impl Config {
Ok(())
}
+ fn validate_checkpoints(&self) -> anyhow::Result<()> {
+ ensure!(
+ !self.checkpoint_s3_bucket.is_empty(),
+ "CHECKPOINT_ENABLED requires CHECKPOINT_S3_BUCKET.",
+ );
+ let knobs: [(&str, u64); 11] = [
+ ("CHECKPOINT_INTERVAL_MS", self.checkpoint_interval_ms),
+ (
+ "CHECKPOINT_S3_UPLOAD_INTERVAL_MS",
+ self.checkpoint_s3_upload_interval_ms,
+ ),
+ (
+ "CHECKPOINT_MAX_CONCURRENT_UPLOADS",
+ self.checkpoint_max_concurrent_uploads as u64,
+ ),
+ (
+ "CHECKPOINT_MAX_CONCURRENT_DOWNLOADS",
+ self.checkpoint_max_concurrent_downloads as u64,
+ ),
+ (
+ "CHECKPOINT_MAX_UPLOAD_BUFFERS",
+ self.checkpoint_max_upload_buffers as u64,
+ ),
+ (
+ "CHECKPOINT_IMPORT_WINDOW_HOURS",
+ u64::from(self.checkpoint_import_window_hours),
+ ),
+ (
+ "CHECKPOINT_LOCAL_MAX_STALENESS_SECS",
+ self.checkpoint_local_max_staleness_secs,
+ ),
+ (
+ "CHECKPOINT_IMPORT_ATTEMPT_DEPTH",
+ self.checkpoint_import_attempt_depth as u64,
+ ),
+ (
+ "CHECKPOINT_S3_OPERATION_TIMEOUT_SECS",
+ self.checkpoint_s3_operation_timeout_secs,
+ ),
+ (
+ "CHECKPOINT_S3_ATTEMPT_TIMEOUT_SECS",
+ self.checkpoint_s3_attempt_timeout_secs,
+ ),
+ (
+ "CHECKPOINT_IMPORT_TIMEOUT_SECS",
+ self.checkpoint_import_timeout_secs,
+ ),
+ ];
+ for (name, value) in knobs {
+ ensure!(value > 0, "{name} must be greater than zero.");
+ }
+ let checkpoints = Path::new(&self.checkpoint_local_dir);
+ let store = Path::new(&self.store_path);
+ // `starts_with` compares path components, so a `..` could name the store or its staging
+ // directory under a spelling the checks below do not match.
+ let plain = |path: &Path| {
+ path.is_absolute() && !path.components().any(|part| part == Component::ParentDir)
+ };
+ ensure!(
+ plain(checkpoints) && plain(store),
+ "CHECKPOINT_LOCAL_DIR {checkpoints:?} and STORE_PATH {store:?} must be absolute paths \
+ without `..`.",
+ );
+ ensure!(
+ !checkpoints.starts_with(store) && !store.starts_with(checkpoints),
+ "CHECKPOINT_LOCAL_DIR {checkpoints:?} and STORE_PATH {store:?} must not contain one \
+ another: RocksDB refuses a checkpoint inside its own directory.",
+ );
+ let staging = staging_path(store);
+ ensure!(
+ !checkpoints.starts_with(&staging),
+ "CHECKPOINT_LOCAL_DIR {checkpoints:?} must not be inside {staging:?}, where a restore \
+ stages a checkpoint: every boot deletes that directory.",
+ );
+ self.checkpoint_lineage().context(
+ "POD_NAME must end in a StatefulSet ordinal, or be unset outside Kubernetes",
+ )?;
+ Ok(())
+ }
+
+ /// The checkpoint lineage of this pod, from the ordinal at the end of `POD_NAME`. A process
+ /// without `POD_NAME` (a local run or a test) uses the single pod's lineage. `HOSTNAME` is not
+ /// consulted: outside Kubernetes it names the machine, not a StatefulSet pod.
+ pub fn checkpoint_lineage(&self) -> Result<CheckpointLineage, NotAnOrdinalPod> {
+ let ordinal = match self.pod_name.as_deref().filter(|name| !name.is_empty()) {
+ Some(name) => PodOrdinal::from_pod_name(name)?,
+ None => PodOrdinal::STANDALONE,
+ };
+ Ok(CheckpointLineage::new(ordinal))
+ }
+
+ /// `COHORT_PARTITION_COUNT` as a slice id range. A count past `u16::MAX` fails the topic checks
+ /// at startup.
+ pub fn partition_count(&self) -> u16 {
+ u16::try_from(self.cohort_partition_count).unwrap_or(u16::MAX)
+ }
+
/// Whether to wipe the store on start, folding in the durable-restore gate: keep the live store
/// only when restore is on and one already exists on disk. Touches the filesystem (`.exists()`) —
/// a one-shot decision evaluated once at store open.
@@ -966,8 +1071,7 @@ impl Config {
periodic_compaction_seconds: self.cohort_periodic_compaction_seconds,
max_background_jobs: self.cohort_max_background_jobs,
person_record_ttl_days: self.cohort_person_record_ttl_days,
- // A count past `u16::MAX` fails the topic checks at startup.
- partition_count: u16::try_from(self.cohort_partition_count).unwrap_or(u16::MAX),
+ partition_count: self.partition_count(),
..StoreConfig::default()
}
}
@@ -1232,7 +1336,7 @@ mod tests {
checkpoint_local_max_staleness_secs: 7200,
checkpoint_import_window_hours: 24,
checkpoint_import_attempt_depth: 10,
- checkpoint_import_timeout_secs: 240,
+ checkpoint_import_timeout_secs: 7200,
cohort_seed_consumer_enabled: false,
cohort_stream_seed_events_topic: "cohort_stream_seed_events".to_string(),
kafka_seed_consumer_group: "cohort-stream-seeds".to_string(),
@@ -1920,11 +2024,73 @@ mod tests {
}
#[test]
- fn durability_startup_guard_allows_checkpoint_with_durable_restore() {
- let mut config = test_config();
- config.checkpoint_enabled = true;
- config.durable_restore_enabled = true;
- assert!(config.validate_startup().is_ok());
+ fn checkpoints_start_only_with_a_bucket_nonzero_knobs_a_separate_absolute_dir_and_an_ordinal() {
+ fn enabled() -> Config {
+ let mut config = test_config();
+ config.checkpoint_enabled = true;
+ config.durable_restore_enabled = true;
+ config.checkpoint_s3_bucket = "bkt".to_string();
+ config.store_path = "/data/store".to_string();
+ config.checkpoint_local_dir = "/data/checkpoints".to_string();
+ config.pod_name = Some("cohort-stream-processor-2".to_string());
+ config
+ }
+ enabled().validate_startup().unwrap();
+
+ type Misconfigure = fn(&mut Config);
+ let cases: [(&str, Misconfigure, &str); 9] = [
+ (
+ "no bucket",
+ |c| c.checkpoint_s3_bucket.clear(),
+ "CHECKPOINT_S3_BUCKET",
+ ),
+ (
+ "a zero interval",
+ |c| c.checkpoint_interval_ms = 0,
+ "CHECKPOINT_INTERVAL_MS",
+ ),
+ (
+ "a relative checkpoint dir",
+ |c| c.checkpoint_local_dir = "checkpoints".to_string(),
+ "absolute",
+ ),
+ (
+ "a relative store path",
+ |c| c.store_path = "cohort-store".to_string(),
+ "absolute",
+ ),
+ (
+ "a checkpoint dir inside the store",
+ |c| c.checkpoint_local_dir = "/data/store/checkpoints".to_string(),
+ "contain",
+ ),
+ (
+ "a store inside the checkpoint dir",
+ |c| c.checkpoint_local_dir = "/data".to_string(),
+ "contain",
+ ),
+ (
+ "a checkpoint dir inside the restore's staging dir",
+ |c| c.checkpoint_local_dir = "/data/store.restore/checkpoints".to_string(),
+ "stages",
+ ),
+ (
+ "a checkpoint dir that reaches the staging dir through `..`",
+ |c| c.checkpoint_local_dir = "/data/../data/store.restore".to_string(),
+ "without `..`",
+ ),
+ (
+ "a pod name without an ordinal",
+ |c| c.pod_name = Some("cohort-stream-processor".to_string()),
+ "POD_NAME",
+ ),
+ ];
+ for (name, misconfigure, expected) in cases {
+ let mut config = enabled();
+ misconfigure(&mut config);
+ let err = config.validate_startup().expect_err(name);
+ assert!(format!("{err:#}").contains(expected), "{name}: {err:#}");
+ }
}
#[test]
diff --git a/rust/cohort-stream-processor/src/consumers/boot.rs b/rust/cohort-stream-processor/src/consumers/boot.rs
index a274e5b38bbc..737004a0a774 100644
--- a/rust/cohort-stream-processor/src/consumers/boot.rs
+++ b/rust/cohort-stream-processor/src/consumers/boot.rs
@@ -12,7 +12,8 @@ use rdkafka::error::KafkaResult;
use rdkafka::{Offset, TopicPartitionList};
use crate::consumers::events::ConsumedEvent;
-use crate::store::durability::OffsetManifest;
+use crate::partitions::ResumeOffset;
+use crate::store::durability::PendingRestore;
/// The lowest offset per events partition that boot polled and did not fold. A seek there fetches
/// every skipped event again. librdkafka discards messages it fetched before a seek, so a held-back
@@ -27,23 +28,17 @@ impl ResumePoints {
}
}
- /// Lowers each owned partition's resume point to its manifest offset, so a restored store never
- /// resumes past its checkpoint.
- pub(crate) fn rewind_to(
- &mut self,
- manifest: &OffsetManifest,
- topic: &str,
- owned: &HashSet<i32>,
- ) {
- for &partition in owned {
- if let Some(next_offset) = manifest.offset_for(topic, partition) {
- self.lower(partition, next_offset);
- }
+ /// Lowers each partition's resume point to the position its restore plan keeps, so a restored
+ /// store never resumes past its checkpoint. The seek list leaves out the ones this consumer does
+ /// not own.
+ pub(crate) fn rewind_to(&mut self, positions: &BTreeMap<u16, ResumeOffset>) {
+ for (&partition, &offset) in positions {
+ self.lower(i32::from(partition), offset.get());
}
}
/// The seek list for the partitions still owned, or `None` when nothing needs a seek. Fails only
- /// on a negative offset, which neither a polled message nor a captured manifest carries.
+ /// on a negative offset, which a polled message never carries.
pub(crate) fn seek_list(
&self,
topic: &str,
@@ -66,27 +61,29 @@ impl ResumePoints {
}
}
-/// Where the events consumer's boot stands. Nothing folds before [`BootPhase::Live`].
+/// Where the events consumer's boot stands. Nothing folds before [`BootPhase::Live`]. A pending
+/// checkpoint restore rides along until the rewind commits its positions and finishes it.
pub(crate) enum BootPhase {
/// Waiting for two consecutive polls to report the same non-empty assignment.
Settling {
previous: Option<HashSet<i32>>,
resume: ResumePoints,
- manifest: Option<OffsetManifest>,
+ restore: Option<PendingRestore>,
},
/// Recovery ran. The owned partitions must seek before anything folds.
Rewinding {
resume: ResumePoints,
+ restore: Option<PendingRestore>,
},
Live,
}
impl BootPhase {
- pub(crate) fn settling(manifest: Option<OffsetManifest>) -> Self {
+ pub(crate) fn settling(restore: Option<PendingRestore>) -> Self {
Self::Settling {
previous: None,
resume: ResumePoints::default(),
- manifest,
+ restore,
}
}
}
@@ -109,8 +106,6 @@ pub(crate) fn boot_assignment_settled(
#[cfg(test)]
mod tests {
- use chrono::Utc;
-
use super::*;
use crate::consumers::events::CohortStreamEvent;
@@ -154,7 +149,7 @@ mod tests {
struct Case {
name: &'static str,
polls: &'static [&'static [(i32, i64)]],
- manifest: Option<&'static [(i32, i64)]>,
+ restored: Option<&'static [(u16, i64)]>,
owned: &'static [i32],
expected: Option<&'static [(i32, i64)]>,
}
@@ -165,35 +160,35 @@ mod tests {
Case {
name: "the lowest polled offset per partition wins across polls",
polls: &[&[(0, 5), (1, 7)], &[(0, 3), (0, 6), (1, 8)]],
- manifest: None,
+ restored: None,
owned: &[0, 1],
expected: Some(&[(0, 3), (1, 7)]),
},
Case {
- name: "a manifest lowers held partitions and adds owned ones boot never polled",
+ name: "a restore lowers held partitions and adds owned ones boot never polled",
polls: &[&[(0, 10), (1, 2)]],
- manifest: Some(&[(0, 4), (1, 6), (2, 9), (3, 1)]),
+ restored: Some(&[(0, 4), (1, 6), (2, 9), (3, 1)]),
owned: &[0, 1, 2],
expected: Some(&[(0, 4), (1, 2), (2, 9)]),
},
Case {
name: "a partition revoked during boot is not sought",
polls: &[&[(0, 3), (1, 7)]],
- manifest: None,
+ restored: None,
owned: &[1],
expected: Some(&[(1, 7)]),
},
Case {
name: "nothing held needs no seek",
polls: &[&[]],
- manifest: None,
+ restored: None,
owned: &[0, 1],
expected: None,
},
Case {
name: "only unowned partitions held needs no seek",
polls: &[&[(2, 4)]],
- manifest: Some(&[(3, 1)]),
+ restored: Some(&[(3, 1)]),
owned: &[0],
expected: None,
},
@@ -209,16 +204,14 @@ mod tests {
.collect();
resume.hold_back(&events);
}
- if let Some(offsets) = case.manifest {
- let manifest = OffsetManifest {
- version: crate::store::durability::MANIFEST_VERSION,
- captured_at: Utc::now(),
- topics: BTreeMap::from([(
- TOPIC.to_string(),
- offsets.iter().copied().collect(),
- )]),
- };
- resume.rewind_to(&manifest, TOPIC, &owned);
+ if let Some(offsets) = case.restored {
+ let positions = offsets
+ .iter()
+ .map(|&(partition, offset)| {
+ (partition, ResumeOffset::try_from(offset).unwrap())
+ })
+ .collect();
+ resume.rewind_to(&positions);
}
assert_eq!(
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index eb58e3c9ce75..ffc7320a45b1 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -32,12 +32,12 @@ use crate::consumers::seeds::ConsumedSeed;
use crate::filters::manager::CatalogHandle;
use crate::merge::transfer::PendingTransfer;
use crate::observability::metrics::{
- CASCADE_HELD_OFFSET_GAUGE, COHORT_STREAM_CASCADES_SKIPPED_NOT_OWNED,
- COHORT_STREAM_CONSUME_BATCH_SIZE, COHORT_STREAM_DESERIALIZE_ERRORS,
- COHORT_STREAM_EMPTY_PAYLOAD, COHORT_STREAM_EVENTS_CONSUMED, COHORT_STREAM_EVENTS_DISPATCHED,
- COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED, COHORT_STREAM_KAFKA_RECV_ERRORS,
- COHORT_STREAM_MERGES_SKIPPED_NOT_OWNED, COHORT_STREAM_OFFSET_COMMITS,
- COHORT_STREAM_OFFSET_COMMIT_ERRORS, COHORT_STREAM_ROUTE_ERRORS,
+ CASCADE_HELD_OFFSET_GAUGE, CHECKPOINT_RESTORE_BLOCKED,
+ COHORT_STREAM_CASCADES_SKIPPED_NOT_OWNED, COHORT_STREAM_CONSUME_BATCH_SIZE,
+ COHORT_STREAM_DESERIALIZE_ERRORS, COHORT_STREAM_EMPTY_PAYLOAD, COHORT_STREAM_EVENTS_CONSUMED,
+ COHORT_STREAM_EVENTS_DISPATCHED, COHORT_STREAM_EVENTS_SKIPPED_NOT_OWNED,
+ COHORT_STREAM_KAFKA_RECV_ERRORS, COHORT_STREAM_MERGES_SKIPPED_NOT_OWNED,
+ COHORT_STREAM_OFFSET_COMMITS, COHORT_STREAM_OFFSET_COMMIT_ERRORS, COHORT_STREAM_ROUTE_ERRORS,
COHORT_STREAM_SEEDS_SKIPPED_NOT_OWNED, COHORT_STREAM_TRANSFERS_SKIPPED_NOT_OWNED,
COHORT_STREAM_WORKERS_SPAWNED, DURABLE_RESTORE_PARTITIONS_KEPT_TOTAL,
DURABLE_RESTORE_PARTITIONS_WIPED_STALE_TOTAL,
@@ -54,8 +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::producer::MembershipSink;
-use crate::store::durability::OffsetManifest;
+use crate::store::durability::PendingRestore;
use crate::store::StoreHandle;
use crate::workers::{EventNameGating, EvictionRestore, MergeWorkerDeps, Stage1Worker};
@@ -172,6 +173,13 @@ impl EventDispatcher {
&self.readiness
}
+ /// Gate `/_ready` on `readiness`, which a health server bound before the dispatcher already
+ /// serves.
+ pub fn with_readiness(mut self, readiness: Arc<BootReadiness>) -> Self {
+ self.readiness = readiness;
+ self
+ }
+
/// Enable crash-restart durability. Must be called before any worker spawns.
pub fn enable_durable_restore(&self) {
self.durable_restore.store(true, Ordering::SeqCst);
@@ -972,6 +980,7 @@ impl EventDispatcher {
recovered
}
+ #[cfg(test)]
fn tracker(&self) -> &OffsetTracker {
self.tracker.as_ref()
}
@@ -990,8 +999,8 @@ impl EventDispatcher {
}
/// Drain all workers, publish the ownership they drained under for the followers' final
- /// commits, and return the tracker for the caller's final sync commit. No consumer polls during
- /// the drain, so no rebalance callback can change `owned` while it runs.
+ /// commits, and return the tracker. No consumer polls during the drain, so no rebalance callback
+ /// can change `owned` while it runs.
async fn shutdown(&self) -> Arc<OffsetTracker> {
self.draining.store(true, Ordering::SeqCst);
self.router.clear();
@@ -1060,9 +1069,9 @@ pub struct CohortStreamEventsConsumer {
events_partitions: usize,
#[allow(dead_code)]
consumer_command_rx: ConsumerCommandReceiver,
- /// Offset manifest from a disaster restore. When set, boot also rewinds every owned partition
- /// the manifest names to its manifest position.
- restore_manifest: Option<OffsetManifest>,
+ /// A checkpoint restore boot must finish. Boot rewinds every owned partition the restore keeps
+ /// to its restored position, commits, and finishes it before anything folds.
+ restore: Option<PendingRestore>,
}
impl CohortStreamEventsConsumer {
@@ -1077,7 +1086,7 @@ impl CohortStreamEventsConsumer {
offset_commit_interval: Duration,
events_partitions: usize,
consumer_command_rx: ConsumerCommandReceiver,
- restore_manifest: Option<OffsetManifest>,
+ restore: Option<PendingRestore>,
) -> Self {
let pauser: Arc<dyn PartitionPauser> =
Arc::new(ConsumerPauser::new(consumer.clone(), topic.clone()));
@@ -1092,7 +1101,7 @@ impl CohortStreamEventsConsumer {
offset_commit_interval,
events_partitions,
consumer_command_rx,
- restore_manifest,
+ restore,
}
}
@@ -1121,14 +1130,14 @@ impl CohortStreamEventsConsumer {
let pauser_task = tokio::spawn(run_pauser_loop(self.pauser.clone(), pause_rx));
let boot_started = Instant::now();
- // `validate_startup` refuses a checkpoint restore without durable restore, so a manifest
+ // `validate_startup` refuses a checkpoint restore without durable restore, so a restore
// always comes with it. Without durable restore the store started empty: nothing to recover.
let mut phase = match (
self.dispatcher.durable_restore_enabled(),
- self.restore_manifest.take(),
+ self.restore.take(),
) {
(false, None) => self.go_live(boot_started, 0),
- (_, manifest) => BootPhase::settling(manifest),
+ (_, restore) => BootPhase::settling(restore),
};
// Untouched until boot recovery completes, so nothing pauses during boot.
let mut backpressure = Backpressure::new();
@@ -1155,7 +1164,7 @@ impl CohortStreamEventsConsumer {
);
BootPhase::Live
}
- BootPhase::Settling { mut previous, mut resume, manifest } => {
+ BootPhase::Settling { mut previous, mut resume, restore } => {
resume.hold_back(&outcome.events);
let assignment = self.assigned_partitions();
if boot_assignment_settled(&assignment, &mut previous) {
@@ -1166,17 +1175,18 @@ impl CohortStreamEventsConsumer {
self.dispatcher
.eager_redrive_pending_transfers_on_boot(&owned)
.await;
- if let Some(manifest) = &manifest {
- resume.rewind_to(manifest, &self.topic, &owned);
+ if let Some(restore) = &restore {
+ let topic = InputTopic::new(self.topic.as_str());
+ resume.rewind_to(&restore.plan().positions(&topic));
}
- self.rewind(resume, boot_started)
+ self.rewind(resume, restore, boot_started)
} else {
- BootPhase::Settling { previous, resume, manifest }
+ BootPhase::Settling { previous, resume, restore }
}
}
- BootPhase::Rewinding { mut resume } => {
+ BootPhase::Rewinding { mut resume, restore } => {
resume.hold_back(&outcome.events);
- self.rewind(resume, boot_started)
+ self.rewind(resume, restore, boot_started)
}
};
if transport_error {
@@ -1198,12 +1208,11 @@ impl CohortStreamEventsConsumer {
warn!(error = %err, "pauser task did not exit cleanly");
}
- let tracker = self.dispatcher.shutdown().await;
+ self.dispatcher.shutdown().await;
let offsets = self.dispatcher.owned_committable_offsets();
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
- &tracker,
offsets,
&self.topic,
CommitMode::Sync,
@@ -1212,10 +1221,19 @@ impl CohortStreamEventsConsumer {
info!(topic = %self.topic, "cohort_stream_events consume loop stopped");
}
- /// Seek every owned partition back to its resume point, then go live. Any failure keeps boot
- /// in `Rewinding`, so the next poll retries the seek and nothing folds from the broker offset.
- /// `Rewinding` reports no liveness, so a persistent failure restarts the process.
- fn rewind(&self, resume: ResumePoints, boot_started: Instant) -> BootPhase {
+ /// Seek every owned partition back to its resume point, finish a pending restore, then go live.
+ /// Any failure keeps boot in `Rewinding`, so the next poll retries and nothing folds from the
+ /// broker offset. `Rewinding` reports no liveness, so a persistent failure restarts the process.
+ ///
+ /// A restore commits the seek list before it finishes. Finishing deletes the restore marker, so
+ /// without the commit a crash right after would reopen the restored store at the broker's old,
+ /// higher offsets and skip the events between.
+ fn rewind(
+ &self,
+ resume: ResumePoints,
+ restore: Option<PendingRestore>,
+ boot_started: Instant,
+ ) -> BootPhase {
let owned = self.dispatcher.owned_set();
let seek_list = match resume.seek_list(&self.topic, &owned) {
Ok(seek_list) => seek_list,
@@ -1225,38 +1243,69 @@ impl CohortStreamEventsConsumer {
error = %err,
"boot seek list rejected an offset; holding off dispatch and retrying",
);
- return BootPhase::Rewinding { resume };
+ return BootPhase::Rewinding { resume, restore };
}
};
- let Some(seek_list) = seek_list else {
- return self.go_live(boot_started, 0);
- };
- let sought = seek_list.count();
+ let sought = seek_list.as_ref().map_or(0, TopicPartitionList::count);
- let failed: Vec<i32> = match self.consumer.seek_partitions(seek_list, BOOT_SEEK_TIMEOUT) {
- Ok(result) => result
- .elements_for_topic(&self.topic)
- .iter()
- .filter(|elem| elem.error().is_err())
- .map(|elem| elem.partition())
- .collect(),
- Err(err) => {
+ if let Some(seek_list) = &seek_list {
+ let failed: Vec<i32> = match self
+ .consumer
+ .seek_partitions(seek_list.clone(), BOOT_SEEK_TIMEOUT)
+ {
+ Ok(result) => result
+ .elements_for_topic(&self.topic)
+ .iter()
+ .filter(|elem| elem.error().is_err())
+ .map(|elem| elem.partition())
+ .collect(),
+ Err(err) => {
+ warn!(
+ topic = %self.topic,
+ partitions = sought,
+ error = %err,
+ "boot seek failed; holding off dispatch and retrying (no progress until it succeeds)",
+ );
+ return BootPhase::Rewinding { resume, restore };
+ }
+ };
+ if !failed.is_empty() {
warn!(
topic = %self.topic,
- partitions = sought,
- error = %err,
- "boot seek failed; holding off dispatch and retrying (no progress until it succeeds)",
+ failed_partitions = ?failed,
+ "boot seek failed for some partitions; holding off dispatch and retrying (no progress until it succeeds)",
);
- return BootPhase::Rewinding { resume };
+ return BootPhase::Rewinding { resume, restore };
+ }
+ }
+
+ if let Some(pending) = &restore {
+ let commit_events = || match &seek_list {
+ Some(seek_list) => self.consumer.commit(seek_list, CommitMode::Sync),
+ None => Ok(()),
+ };
+ // 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)) {
+ Ok(()) => {
+ gauge!(CHECKPOINT_RESTORE_BLOCKED).set(0.0);
+ info!(
+ topic = %self.topic,
+ partitions = sought,
+ "checkpoint restore finished: the events group committed the restored positions",
+ );
+ }
+ Err(err) => {
+ gauge!(CHECKPOINT_RESTORE_BLOCKED).set(1.0);
+ warn!(
+ topic = %self.topic,
+ error = %format!("{:#}", anyhow::Error::new(err)),
+ "checkpoint restore could not finish; holding off dispatch and retrying",
+ );
+ return BootPhase::Rewinding { resume, restore };
+ }
}
- };
- if !failed.is_empty() {
- warn!(
- topic = %self.topic,
- failed_partitions = ?failed,
- "boot seek failed for some partitions; holding off dispatch and retrying (no progress until it succeeds)",
- );
- return BootPhase::Rewinding { resume };
}
self.go_live(boot_started, sought)
}
@@ -1407,7 +1456,6 @@ pub(crate) fn build_commit_tpl(topic: &str, offsets: &HashMap<i32, i64>) -> Topi
pub(crate) fn commit_offsets<C: ConsumerContext>(
consumer: &StreamConsumer<C>,
- tracker: &OffsetTracker,
offsets: HashMap<i32, i64>,
topic: &str,
mode: CommitMode,
@@ -1417,12 +1465,7 @@ pub(crate) fn commit_offsets<C: ConsumerContext>(
}
let tpl = build_commit_tpl(topic, &offsets);
match consumer.commit(&tpl, mode) {
- Ok(()) => {
- counter!(COHORT_STREAM_OFFSET_COMMITS).increment(1);
- for (&partition, &next_offset) in &offsets {
- tracker.mark_committed(partition, next_offset);
- }
- }
+ Ok(()) => counter!(COHORT_STREAM_OFFSET_COMMITS).increment(1),
Err(err) => {
counter!(COHORT_STREAM_OFFSET_COMMIT_ERRORS).increment(1);
warn!(topic, error = %err, "failed to commit consumer offsets");
@@ -1439,7 +1482,6 @@ pub(crate) fn commit_offsets<C: ConsumerContext>(
pub(crate) async fn fsync_then_commit<C: ConsumerContext>(
handle: &StoreHandle,
consumer: &StreamConsumer<C>,
- tracker: &OffsetTracker,
offsets: HashMap<i32, i64>,
topic: &str,
mode: CommitMode,
@@ -1450,7 +1492,7 @@ pub(crate) async fn fsync_then_commit<C: ConsumerContext>(
if handle.flush_wal_sync().await.is_err() {
return; // store counted the error; skip commit so `committed` never outruns `durable`
}
- commit_offsets(consumer, tracker, offsets, topic, mode);
+ commit_offsets(consumer, offsets, topic, mode);
}
/// Flushes the store's WAL and commits the owned committable offsets on a fixed interval, independent
@@ -1472,7 +1514,6 @@ async fn run_commit_loop(
fsync_then_commit(
dispatcher.handle(),
&consumer,
- dispatcher.tracker(),
dispatcher.owned_committable_offsets(),
&topic,
CommitMode::Async,
@@ -3242,8 +3283,9 @@ mod tests {
assert_eq!(dispatcher.workers.len(), 1);
assert!(dispatcher.workers.contains_key(&0));
assert!(!dispatcher.workers.contains_key(&1));
- assert!(
- dispatcher.tracker().committed_offset(1).is_none(),
+ assert_eq!(
+ dispatcher.tracker().partition_count(),
+ 1,
"the dropped partition's dispatch ceiling was never raised",
);
diff --git a/rust/cohort-stream-processor/src/consumers/merges.rs b/rust/cohort-stream-processor/src/consumers/merges.rs
index 95aa5a323db0..0749d7957cee 100644
--- a/rust/cohort-stream-processor/src/consumers/merges.rs
+++ b/rust/cohort-stream-processor/src/consumers/merges.rs
@@ -232,7 +232,6 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
- self.tracker(),
self.owned_committable_offsets(),
&self.topic,
CommitMode::Async,
@@ -254,7 +253,6 @@ impl<R: FollowerRoute> FollowerConsumer<R> {
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
- self.tracker(),
offsets,
&self.topic,
CommitMode::Sync,
diff --git a/rust/cohort-stream-processor/src/consumers/seeds.rs b/rust/cohort-stream-processor/src/consumers/seeds.rs
index 4b72be2dd897..5be48adf4f29 100644
--- a/rust/cohort-stream-processor/src/consumers/seeds.rs
+++ b/rust/cohort-stream-processor/src/consumers/seeds.rs
@@ -541,7 +541,6 @@ impl SeedFollowerConsumer {
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
- &self.dispatcher.merge_deps().seed_tracker,
self.owned_committable_offsets(),
&self.topic,
CommitMode::Async,
@@ -571,7 +570,6 @@ impl SeedFollowerConsumer {
fsync_then_commit(
self.dispatcher.handle(),
&self.consumer,
- &self.dispatcher.merge_deps().seed_tracker,
offsets,
&self.topic,
CommitMode::Sync,
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index ed3b81bd297b..4745444f3949 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -1,4 +1,4 @@
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
@@ -6,8 +6,7 @@ use anyhow::{Context, Result};
use common_database::get_pool_with_config;
use envconfig::Envconfig;
use lifecycle::{ComponentOptions, Handle, Manager};
-use rdkafka::consumer::{CommitMode, Consumer, ConsumerContext, StreamConsumer};
-use rdkafka::{Offset, TopicPartitionList};
+use rdkafka::consumer::{Consumer, ConsumerContext, StreamConsumer};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tracing::{info, warn};
@@ -29,7 +28,7 @@ use cohort_stream_processor::observability::store_stats::{DiskProbe, StoreStatsS
use cohort_stream_processor::observability::tokio_monitor::TokioRuntimeMonitor;
use cohort_stream_processor::partitions::{
run_rebalance_worker, CohortConsumerContext, ConsumerPauser, Follower, FollowerSet,
- LiveWatermarks, OffsetTracker, PartitionPauser, PartitionRouter,
+ InputGroups, LiveWatermarks, OffsetTracker, PartitionPauser, PartitionRouter,
};
use cohort_stream_processor::producer::{
CascadeSink, KafkaCascadeSink, KafkaMembershipSink, KafkaReconcileMarkerSink,
@@ -37,11 +36,11 @@ use cohort_stream_processor::producer::{
NoopReconcileMarkerSink, NoopSeedTileSink, ReconcileMarkerSink, SeedTileSink, StreamEventSink,
TransferSink,
};
+use cohort_stream_processor::store::durability::checkpoint::CHECKPOINT_LOOP_NAME;
use cohort_stream_processor::store::durability::{
- run_boot_restore, upload_cadence, CheckpointExporter, CheckpointSweeper, OffsetManifest,
- S3Uploader, TrackedTopic, CHECKPOINT_LOOP_NAME,
+ ensure_one_filesystem, open_store, upload_cadence, CheckpointSweeper,
};
-use cohort_stream_processor::store::{CohortStore, StoreHandle};
+use cohort_stream_processor::store::StoreHandle;
use cohort_stream_processor::sweep::{
run_sweep_loop, run_sweep_loop_delayed, DispatchSweeper, ReconcileDrainSweeper,
};
@@ -75,6 +74,11 @@ async fn async_main(config: Config) -> Result<()> {
config.validate_startup()?;
+ let lineage = config
+ .checkpoint_enabled
+ .then(|| config.checkpoint_lineage())
+ .transpose()?;
+
let mut manager = Manager::builder(SERVICE_NAME)
.with_global_shutdown_timeout(Duration::from_secs(90))
.build();
@@ -132,13 +136,36 @@ async fn async_main(config: Config) -> Result<()> {
None
};
- let pool = get_pool_with_config(&config.database_url, config.pool_config())
- .context("creating posthog_cohort database pool")?;
-
let catalog = Arc::new(CatalogHandle::with_allowlist(
config.team_allowlist.clone(),
config.cohort_cascade_enabled,
));
+ let boot_readiness = BootReadiness::new(catalog.clone());
+
+ // Bound before the restore, which can outlast the startup probe. `/_health` answers throughout;
+ // `/_ready` reads "boot recovery in progress" until the events consumer goes live.
+ let app = observability::health::router(
+ SERVICE_NAME,
+ readiness,
+ boot_readiness.clone(),
+ liveness,
+ recorder_handle,
+ );
+ let bind = config.bind_address();
+ let listener = TcpListener::bind(&bind)
+ .await
+ .with_context(|| format!("failed to bind observability server to {bind}"))?;
+ info!(address = %bind, "observability server listening");
+ let shutdown_signal = metrics_handle.shutdown_signal();
+ let health_server = tokio::spawn(async move {
+ axum::serve(listener, app)
+ .with_graceful_shutdown(shutdown_signal)
+ .await
+ });
+
+ let pool = get_pool_with_config(&config.database_url, config.pool_config())
+ .context("creating posthog_cohort database pool")?;
+
match catalog.refresh(&pool).await {
Ok(stats) => info!(
teams = stats.teams,
@@ -151,23 +178,17 @@ async fn async_main(config: Config) -> Result<()> {
),
}
- // Decide where the live store comes from and, on the disaster paths, materialize it at
- // `store_path` before the store is opened and before the checkpoint sweep loop is spawned (so no
- // TOCTOU with the sweeper's prune). A restored DB dropped at `store_path` makes the
- // `effective_wipe_on_start` logic below see `db_dir_exists == true` and keep it.
- let restore = run_boot_restore(&config, &PathBuf::from(&config.store_path)).await;
- info!(restore_source = ?restore.source, "boot restore complete");
-
- let store_config = config.store_config();
- info!(
- durable_restore_enabled = config.durable_restore_enabled,
- wipe_store_on_start = config.wipe_store_on_start,
- effective_wipe = store_config.wipe_on_start,
- store_path = %config.store_path,
- mode = if store_config.wipe_on_start { "wipe+replay" } else { "reopen-live" },
- "opening RocksDB state store",
- );
- let store = CohortStore::open(&store_config).context("opening RocksDB state store")?;
+ let groups = Arc::new(InputGroups::new(&config));
+ if lineage.is_some() {
+ ensure_one_filesystem(
+ Path::new(&config.checkpoint_local_dir),
+ Path::new(&config.store_path),
+ )
+ .context("checking the checkpoint directory")?;
+ }
+ let (store, restore) = open_store(&config, lineage, groups.clone())
+ .await
+ .context("opening RocksDB state store")?;
let router = PartitionRouter::with_intake_cap(
config.partition_channel_buffer,
config.partition_intake_max_events,
@@ -270,29 +291,24 @@ async fn async_main(config: Config) -> Result<()> {
seed_budget: config.seed_run_budget(),
});
- // Cheap `Arc` clones taken before the originals move into the dispatcher: the checkpoint sweeper
- // needs its own raw-store handle and each per-topic tracker to capture the offset manifest.
- // Captured unconditionally to satisfy the borrow checker; consumed only when `checkpoint_enabled`.
- // The sweeper keeps the raw `CohortStore` rather than the facade because of its must-not-panic
- // policy (see checkpoint.rs).
+ // The checkpoint sweeper keeps the raw `CohortStore` rather than the facade because of its
+ // must-not-panic policy (see checkpoint.rs).
let store_for_checkpoint = store.clone();
- let events_tracker_for_checkpoint = offset_tracker.clone();
- let merge_tracker_for_checkpoint = merge_deps.merge_tracker.clone();
- let transfer_tracker_for_checkpoint = merge_deps.transfer_tracker.clone();
- let cascade_tracker_for_checkpoint = merge_deps.cascade_tracker.clone();
- let seed_tracker_for_checkpoint = merge_deps.seed_tracker.clone();
let handle = StoreHandle::new(store, config.offload_config());
let handle_for_stats = handle.clone();
- let dispatcher = Arc::new(EventDispatcher::new(
- router,
- offset_tracker,
- handle,
- catalog.clone(),
- sink,
- merge_deps,
- ));
+ let dispatcher = Arc::new(
+ EventDispatcher::new(
+ router,
+ offset_tracker,
+ handle,
+ catalog.clone(),
+ sink,
+ merge_deps,
+ )
+ .with_readiness(boot_readiness.clone()),
+ );
// Set once, before the consume loop and any worker spawn. The fsync-before-commit invariant is
// always on regardless — the gate only governs restore, not durability.
if config.durable_restore_enabled {
@@ -300,7 +316,6 @@ async fn async_main(config: Config) -> Result<()> {
}
// Event-name fan-out gating, likewise set before any worker spawns.
dispatcher.set_event_name_gating(config.event_name_gating());
- let boot_readiness = dispatcher.readiness().clone();
let (context, rebalance_rx) = CohortConsumerContext::new(dispatcher.clone());
let stream_consumer: StreamConsumer<CohortConsumerContext> = config
@@ -425,35 +440,6 @@ async fn async_main(config: Config) -> Result<()> {
}
}
- if let Some(manifest) = restore.manifest.as_ref() {
- commit_follower_offsets_from_manifest(
- &merges_follower_consumer,
- &config.person_merge_events_topic,
- manifest,
- );
- commit_follower_offsets_from_manifest(
- &transfers_follower_consumer,
- &config.cohort_merge_state_transfer_topic,
- manifest,
- );
- if let Some(cascade_consumer) = &cascade_follower_consumer {
- commit_follower_offsets_from_manifest(
- cascade_consumer,
- &config.cohort_cascade_events_topic,
- manifest,
- );
- }
- // State rolls back to the snapshot, so the seed offsets must roll back with it or the
- // in-between tiles never replay.
- if let Some(seed_consumer) = &seed_follower_consumer {
- commit_follower_offsets_from_manifest(
- seed_consumer,
- &config.cohort_stream_seed_events_topic,
- manifest,
- );
- }
- }
-
let mut follower_mirrors = vec![
Follower::new(
merges_follower_consumer.clone(),
@@ -566,58 +552,33 @@ async fn async_main(config: Config) -> Result<()> {
.start_monitoring(tokio_monitor_handle),
);
- // Whole-DB checkpoint → PVC + incremental S3 sweep loop. Spawned only when the master gate is on,
- // so a default deploy starts no checkpoint task. The cascade tracker is included only when cascade
- // is on; otherwise it is idle and would contribute an empty manifest entry.
- if config.checkpoint_enabled {
- let uploader = S3Uploader::new(config.durability_config())
- .await
- .context("building checkpoint S3 uploader")?;
- let exporter = CheckpointExporter::new(Box::new(uploader));
- let upload_every_n = upload_cadence(
- config.checkpoint_interval_ms,
- config.checkpoint_s3_upload_interval_ms,
- );
- let mut trackers: Vec<TrackedTopic> = vec![
- (
- config.cohort_stream_events_topic.clone(),
- events_tracker_for_checkpoint,
- ),
- (
- config.person_merge_events_topic.clone(),
- merge_tracker_for_checkpoint,
- ),
- (
- config.cohort_merge_state_transfer_topic.clone(),
- transfer_tracker_for_checkpoint,
- ),
- ];
- if config.cohort_cascade_enabled {
- trackers.push((
- config.cohort_cascade_events_topic.clone(),
- cascade_tracker_for_checkpoint,
- ));
- }
- if config.cohort_seed_consumer_enabled {
- trackers.push((
- config.cohort_stream_seed_events_topic.clone(),
- seed_tracker_for_checkpoint,
- ));
- }
- tokio::spawn(run_sweep_loop(
- CheckpointSweeper::new(
- store_for_checkpoint,
- dispatcher.clone(),
- trackers,
- exporter,
- config.durability_config(),
- PathBuf::from(&config.checkpoint_local_dir),
- upload_every_n,
+ // Whole-DB checkpoints to the local volume and S3. 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) = lineage {
+ let sweeper = CheckpointSweeper::new(
+ store_for_checkpoint,
+ dispatcher.clone(),
+ groups,
+ lineage,
+ config.durability_config(),
+ upload_cadence(
+ config.checkpoint_interval_ms,
+ config.checkpoint_s3_upload_interval_ms,
),
- config.checkpoint_interval(),
- CHECKPOINT_LOOP_NAME,
- consumer_handle.shutdown_token(),
- ));
+ );
+ let stop = consumer_handle.shutdown_token();
+ let interval = config.checkpoint_interval();
+ let checkpoint_readiness = boot_readiness.clone();
+ tokio::spawn(async move {
+ tokio::select! {
+ biased;
+ // Boot never ended, so there are no settled positions to checkpoint.
+ _ = stop.cancelled() => {}
+ _ = checkpoint_readiness.wait_until_dispatchable() => {
+ run_sweep_loop(sweeper, interval, CHECKPOINT_LOOP_NAME, stop.clone()).await;
+ }
+ }
+ });
}
let merge_follower = FollowerConsumer::<MergeRoute>::new(
@@ -708,28 +669,15 @@ async fn async_main(config: Config) -> Result<()> {
config.offset_commit_interval(),
events_partitions,
consumer_command_rx,
- // Events-topic positions a checkpoint restore rewinds to; `None` on the paths with no
- // checkpoint (reopen-live / cold-start), where boot rewinds only what it polled.
- restore.manifest,
+ // A checkpoint restore boot finishes before anything folds; `None` when the store reopened
+ // or was created, where boot rewinds only what it polled.
+ restore,
);
tokio::spawn(events_consumer.process());
- let app = observability::health::router(
- SERVICE_NAME,
- readiness,
- boot_readiness,
- liveness,
- recorder_handle,
- );
- let bind = config.bind_address();
- info!(address = %bind, "observability server starting");
-
- let listener = TcpListener::bind(&bind)
- .await
- .with_context(|| format!("failed to bind observability server to {bind}"))?;
- axum::serve(listener, app)
- .with_graceful_shutdown(metrics_handle.shutdown_signal())
+ health_server
.await
+ .context("observability server task panicked")?
.context("observability server error")?;
metrics_handle.work_completed();
@@ -766,53 +714,6 @@ fn fetch_partition_count<C: ConsumerContext>(
Ok(count)
}
-/// Seed a follower consumer group's committed offsets from the restore manifest, so its subsequent
-/// `incremental_assign` at [`Offset::Stored`](rdkafka::Offset::Stored) resolves to the restored
-/// position rather than the broker's last commit.
-///
-/// A strict no-op when the manifest has no entry for `topic` or that entry is empty. Commits one
-/// `Offset::Offset(next)` per present partition; a commit error is logged and skipped, never fatal, so
-/// it cannot delay or break the existing follower assignment. The manifest stores `committed_offset`
-/// (next-offset-to-consume), exactly what a Kafka committed offset means, so committing it verbatim is
-/// the correct resume point.
-fn commit_follower_offsets_from_manifest(
- consumer: &StreamConsumer,
- topic: &str,
- manifest: &OffsetManifest,
-) {
- let Some(tpl) = manifest_commit_tpl(topic, manifest) else {
- return;
- };
- match consumer.commit(&tpl, CommitMode::Sync) {
- Ok(()) => info!(
- topic,
- partitions = tpl.count(),
- "seeded follower group offsets from restore manifest",
- ),
- Err(err) => {
- warn!(topic, error = %err, "failed to seed follower offsets from manifest; falling back to broker-stored offsets")
- }
- }
-}
-
-/// Returns the `TopicPartitionList` to commit for `topic`, or `None` when the manifest has no entry,
-/// the entry is empty, or no partition produced a valid offset. Pure (no I/O) so the behavior is
-/// unit-testable without a broker. Each partition is committed at `Offset::Offset(next_offset)` —
-/// the next-to-consume value Kafka committed offsets denote — so `Offset::Stored` resolves to it.
-fn manifest_commit_tpl(topic: &str, manifest: &OffsetManifest) -> Option<TopicPartitionList> {
- let partitions = manifest.topics.get(topic)?;
- if partitions.is_empty() {
- return None;
- }
- let mut tpl = TopicPartitionList::new();
- for (&partition, &next_offset) in partitions {
- if let Err(err) = tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset)) {
- warn!(topic, partition, next_offset, error = %err, "skipping follower partition in manifest commit");
- }
- }
- (tpl.count() > 0).then_some(tpl)
-}
-
fn spawn_follower_after_boot<R: FollowerRoute>(
readiness: Arc<BootReadiness>,
follower: FollowerConsumer<R>,
@@ -902,111 +803,3 @@ fn init_tracing() {
tracing_subscriber::registry().with(log_layer).init();
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use std::collections::BTreeMap;
-
- use cohort_stream_processor::store::durability::MANIFEST_VERSION;
-
- fn manifest_with(topics: BTreeMap<String, BTreeMap<i32, i64>>) -> OffsetManifest {
- OffsetManifest {
- version: MANIFEST_VERSION,
- captured_at: chrono::Utc::now(),
- topics,
- }
- }
-
- #[test]
- fn manifest_commit_tpl_is_none_for_an_absent_topic() {
- let manifest = manifest_with(BTreeMap::new());
- assert!(manifest_commit_tpl("person_merge_events", &manifest).is_none());
- }
-
- #[test]
- fn manifest_commit_tpl_is_none_for_an_empty_topic_entry() {
- let mut topics = BTreeMap::new();
- topics.insert("person_merge_events".to_string(), BTreeMap::new());
- let manifest = manifest_with(topics);
- assert!(
- manifest_commit_tpl("person_merge_events", &manifest).is_none(),
- "an empty follower topic entry must produce no commit (inert in Slice 2)",
- );
- }
-
- #[test]
- fn manifest_commit_tpl_commits_present_follower_offsets() {
- let mut topics = BTreeMap::new();
- topics.insert(
- "person_merge_events".to_string(),
- BTreeMap::from([(0, 7), (4, 19)]),
- );
- let manifest = manifest_with(topics);
-
- let tpl = manifest_commit_tpl("person_merge_events", &manifest)
- .expect("present follower offsets produce a commit list");
- assert_eq!(tpl.count(), 2);
- assert_eq!(
- tpl.find_partition("person_merge_events", 0)
- .unwrap()
- .offset(),
- Offset::Offset(7),
- );
- assert_eq!(
- tpl.find_partition("person_merge_events", 4)
- .unwrap()
- .offset(),
- Offset::Offset(19),
- );
- }
-
- #[test]
- fn manifest_commit_tpl_round_trips_a_multi_topic_live_capture() {
- // Distinct offsets per tracker/partition so a cross-wired capture would surface in the TPL.
- let owned = [3, 7];
- let merge = OffsetTracker::new();
- let transfer = OffsetTracker::new();
- let cascade = OffsetTracker::new();
- for (tracker, base) in [(&merge, 10), (&transfer, 20), (&cascade, 30)] {
- for (partition, bump) in [(3, 1), (7, 2)] {
- let offset = base + bump;
- tracker.mark_dispatched(partition, offset);
- let _ = tracker.mark_processed(partition, offset);
- tracker.mark_committed(partition, offset);
- }
- }
-
- let manifest = OffsetManifest::capture(
- &owned,
- &[
- ("person_merge_events", &merge),
- ("cohort_merge_state_transfer", &transfer),
- ("cohort_cascade_events", &cascade),
- ],
- );
-
- for (topic, base) in [
- ("person_merge_events", 10),
- ("cohort_merge_state_transfer", 20),
- ("cohort_cascade_events", 30),
- ] {
- let tpl = manifest_commit_tpl(topic, &manifest)
- .unwrap_or_else(|| panic!("{topic} live capture must produce a commit list"));
- assert_eq!(tpl.count(), 2, "{topic} commits both owned partitions");
- assert_eq!(
- tpl.find_partition(topic, 3).unwrap().offset(),
- Offset::Offset(base + 1),
- );
- assert_eq!(
- tpl.find_partition(topic, 7).unwrap().offset(),
- Offset::Offset(base + 2),
- );
- }
-
- assert!(
- manifest_commit_tpl("cohort_stream_events", &manifest).is_none(),
- "a topic absent from the live capture must produce no commit",
- );
- }
-}
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index bf21abbc0217..1464f44a2754 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -100,13 +100,25 @@ pub const CHECKPOINT_FILE_COUNT: &str = "checkpoint_file_count";
/// Checkpoint S3 uploads, labelled by `result` (`success`|`error`|`cancelled`|`unavailable`); when
/// `result=cancelled`, an additional `cause` label (`rebalance`|`shutdown`|`unknown`) (counter).
pub const CHECKPOINT_UPLOADS_TOTAL: &str = "checkpoint_uploads_total";
+/// Unix time of the last captured manifest (gauge, seconds). Starts at the sweeper's start, so a
+/// staleness alert fires only after its threshold passes.
+pub const CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS: &str =
+ "checkpoint_last_capture_timestamp_seconds";
+/// Unix time of the last successful upload (gauge, seconds). Starts at the sweeper's start.
+/// **Alert on staleness**: no restorable checkpoint is getting newer.
+pub const CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS: &str =
+ "checkpoint_last_upload_timestamp_seconds";
+/// Checkpoint ticks skipped before the checkpoint, labelled by `reason` (`positions`|`incomplete`)
+/// (counter).
+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";
/// Individual checkpoint files uploaded to S3, labelled by `status` (`success`|`error`|`cancelled`)
/// (counter).
pub const CHECKPOINT_FILES_UPLOADED_TOTAL: &str = "checkpoint_files_uploaded_total";
/// Individual checkpoint files downloaded from S3, labelled by `status`
-/// (`success`|`error`|`cancelled`) (counter).
+/// (`success`|`error`|`cancelled`|`not_found`) (counter). `not_found` is mostly the `metadata.json`
+/// of an upload that never finished.
pub const CHECKPOINT_FILES_DOWNLOADED_TOTAL: &str = "checkpoint_files_downloaded_total";
/// Files seen during incremental checkpoint planning, labelled by `action`
/// (`added`|`replaced`|`retained`) (counter).
@@ -120,17 +132,23 @@ pub const CHECKPOINT_FILE_FETCH_STORE_DURATION_SECONDS: &str =
"checkpoint_file_fetch_store_duration_seconds";
/// Latency of listing a checkpoint's recent attempt folders from S3 (histogram, seconds).
pub const CHECKPOINT_LIST_DURATION_SECONDS: &str = "checkpoint_list_duration_seconds";
-/// Boot restores, labelled by `source` (`reopen_live`|`pvc`|`s3`|`cold`) (counter).
+/// Boot store choices, labelled by `source` (`reopen_live`|`pending`|`local`|`s3`|`cold`) (counter).
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.
+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
+/// `CHECKPOINT_ENABLED` off also ends it.
+pub const CHECKPOINT_RESTORE_BLOCKED: &str = "checkpoint_restore_blocked";
/// Wall-clock duration of one boot restore (histogram, seconds).
pub const CHECKPOINT_RESTORE_DURATION_SECONDS: &str = "checkpoint_restore_duration_seconds";
-/// End-to-end checkpoint import (list + metadata + files + fallbacks), labelled by `result`
-/// (`success`|`failed`|`cancelled`|`timeout`) (histogram, seconds).
+/// Download of one checkpoint candidate's files, labelled by `result` (`success`|`failed`)
+/// (histogram, seconds).
pub const CHECKPOINT_IMPORT_DURATION_SECONDS: &str = "checkpoint_import_duration_seconds";
-/// Duration of one import attempt (one checkpoint's files), labelled by `result`
-/// (`success`|`failed`) (histogram, seconds).
-pub const CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS: &str =
- "checkpoint_import_attempt_duration_seconds";
/// RocksDB batch commits, labelled by `op` (counter).
pub const STORE_WRITE_BATCH_TOTAL: &str = "store_write_batch_total";
@@ -804,9 +822,26 @@ mod tests {
"checkpoint_import_duration_seconds",
);
assert_eq!(
- CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS,
- "checkpoint_import_attempt_duration_seconds",
+ CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS,
+ "checkpoint_last_capture_timestamp_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS,
+ "checkpoint_last_upload_timestamp_seconds",
+ );
+ assert_eq!(
+ CHECKPOINT_CAPTURE_FAILURES_TOTAL,
+ "checkpoint_capture_failures_total",
+ );
+ assert_eq!(
+ CHECKPOINT_RESTORE_CANDIDATES_TOTAL,
+ "checkpoint_restore_candidates_total",
+ );
+ assert_eq!(
+ CHECKPOINT_RESTORE_SLICES_RESET_TOTAL,
+ "checkpoint_restore_slices_reset_total",
);
+ assert_eq!(CHECKPOINT_RESTORE_BLOCKED, "checkpoint_restore_blocked");
assert_eq!(
DURABLE_RESTORE_PENDING_TRANSFERS_RECOVERED_PARTITIONS_TOTAL,
"durable_restore_pending_transfers_recovered_partitions_total",
diff --git a/rust/cohort-stream-processor/src/partitions/mod.rs b/rust/cohort-stream-processor/src/partitions/mod.rs
index ee139267d476..7ccfb30cbcba 100644
--- a/rust/cohort-stream-processor/src/partitions/mod.rs
+++ b/rust/cohort-stream-processor/src/partitions/mod.rs
@@ -11,6 +11,7 @@ pub mod intake;
pub mod offset_tracker;
pub mod pacing;
pub mod pause;
+pub mod positions;
pub mod rebalance;
pub mod router;
pub mod shuffle_message;
@@ -29,6 +30,7 @@ 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 rebalance::{
run_rebalance_worker, CohortConsumerContext, ConsumerCommand, ConsumerCommandReceiver,
ConsumerCommandSender, RebalanceEvent, RebalanceEventReceiver,
diff --git a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
index 2027daf56d3e..2e7a2e1bd911 100644
--- a/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
+++ b/rust/cohort-stream-processor/src/partitions/offset_tracker.rs
@@ -42,9 +42,6 @@ struct PartitionProgress {
/// Releasable commit floors owned by in-flight work that outlives its consumed message. Unlike
/// [`held_offset`](Self::held_offset), each floor is removed explicitly when that work finishes.
deferred: BTreeSet<i64>,
- /// Last offset Kafka acked as committed. The gap to `processed_offset` is the window Kafka
- /// replays after a crash.
- committed_offset: i64,
}
impl PartitionProgress {
@@ -222,14 +219,6 @@ impl OffsetTracker {
floor
}
- /// Mark an offset as acked-committed by Kafka. Monotonic, and a no-op for a never-processed
- /// partition (you cannot commit what you have not consumed).
- pub fn mark_committed(&self, partition: i32, offset: i64) {
- if let Some(mut progress) = self.partitions.get_mut(&partition) {
- progress.committed_offset = progress.committed_offset.max(offset);
- }
- }
-
/// Snapshot of `partition → next-offset-to-consume` for every partition with a *processed*
/// offset, capped at the earliest sticky [`hold`](Self::hold) or releasable
/// [`defer`](Self::defer) floor. Partitions tracked only because they were dispatched or deferred
@@ -253,10 +242,6 @@ impl OffsetTracker {
.collect()
}
- pub fn committed_offset(&self, partition: i32) -> Option<i64> {
- self.partitions.get(&partition).map(|p| p.committed_offset)
- }
-
/// Drop all tracking for a revoked partition. Its offset should already be committed. Removing the
/// whole entry also clears any [`hold`](Self::hold) and [`defer`](Self::defer) floors, so the next
/// tenure starts unheld and replays from the committed offset — the only way a sticky hold is
@@ -354,28 +339,6 @@ mod tests {
assert_eq!(snapshot.get(&2), Some(&30));
}
- #[test]
- fn mark_committed_advances_monotonically_only_for_known_partitions() {
- let tracker = OffsetTracker::new();
-
- // Committing an unprocessed partition is a no-op.
- tracker.mark_committed(7, 100);
- assert_eq!(tracker.committed_offset(7), None);
-
- tracker.mark_dispatched(7, 200);
- assert_eq!(tracker.mark_processed(7, 200), MarkOutcome::WithinDispatch);
- assert_eq!(tracker.committed_offset(7), Some(0));
-
- tracker.mark_committed(7, 150);
- assert_eq!(tracker.committed_offset(7), Some(150));
-
- // Backward commit ignored, forward advances.
- tracker.mark_committed(7, 100);
- assert_eq!(tracker.committed_offset(7), Some(150));
- tracker.mark_committed(7, 200);
- assert_eq!(tracker.committed_offset(7), Some(200));
- }
-
#[test]
fn forget_partition_drops_only_that_partition() {
let tracker = OffsetTracker::new();
diff --git a/rust/cohort-stream-processor/src/partitions/positions.rs b/rust/cohort-stream-processor/src/partitions/positions.rs
new file mode 100644
index 000000000000..65b721842d6e
--- /dev/null
+++ b/rust/cohort-stream-processor/src/partitions/positions.rs
@@ -0,0 +1,287 @@
+//! Where each input topic resumes, read from its consumer group on the broker. A checkpoint records
+//! these positions, and a restore commits them back.
+//!
+//! 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.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::fmt;
+use std::time::Duration;
+
+use rdkafka::consumer::{BaseConsumer, CommitMode, Consumer, ConsumerContext};
+use rdkafka::error::{KafkaError, KafkaResult};
+use rdkafka::types::RDKafkaErrorCode;
+use rdkafka::{ClientConfig, Offset, TopicPartitionList};
+use serde::{Deserialize, Serialize};
+
+use crate::config::Config;
+
+const FETCH_TIMEOUT: Duration = Duration::from_secs(10);
+
+/// An input topic's name. A newtype, so a topic and a consumer group name cannot be swapped.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct InputTopic(String);
+
+impl InputTopic {
+ pub fn new(topic: impl Into<String>) -> Self {
+ Self(topic.into())
+ }
+
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl fmt::Display for InputTopic {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+/// The next offset a consumer reads on one input partition. Never negative.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(try_from = "i64", into = "i64")]
+pub struct ResumeOffset(i64);
+
+#[derive(Debug, thiserror::Error)]
+#[error("offset {0} is negative")]
+pub struct NegativeOffset(i64);
+
+impl TryFrom<i64> for ResumeOffset {
+ type Error = NegativeOffset;
+
+ fn try_from(offset: i64) -> Result<Self, Self::Error> {
+ if offset < 0 {
+ return Err(NegativeOffset(offset));
+ }
+ Ok(Self(offset))
+ }
+}
+
+impl From<ResumeOffset> for i64 {
+ fn from(offset: ResumeOffset) -> Self {
+ offset.0
+ }
+}
+
+impl ResumeOffset {
+ pub fn get(self) -> i64 {
+ self.0
+ }
+}
+
+/// 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>(
+ client: &C,
+ topic: &str,
+ partitions: impl IntoIterator<Item = u16>,
+) -> KafkaResult<BTreeMap<u16, i64>>
+where
+ C: Consumer<X>,
+ X: ConsumerContext,
+{
+ let partitions: Vec<u16> = partitions.into_iter().collect();
+ if partitions.is_empty() {
+ return Ok(BTreeMap::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)?;
+ }
+ let answered = client.offsets_for_times(request, FETCH_TIMEOUT)?;
+ partitions
+ .into_iter()
+ .map(|partition| {
+ let elem = answered
+ .find_partition(topic, i32::from(partition))
+ .ok_or(KafkaError::OffsetFetch(RDKafkaErrorCode::UnknownPartition))?;
+ elem.error()?;
+ match elem.offset() {
+ Offset::Offset(offset) => Ok((partition, offset)),
+ _ => Err(KafkaError::OffsetFetch(RDKafkaErrorCode::InvalidArgument)),
+ }
+ })
+ .collect()
+}
+
+/// One input's resume positions, read from its consumer group.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct InputPositions {
+ topic: InputTopic,
+ offsets: BTreeMap<u16, ResumeOffset>,
+}
+
+impl InputPositions {
+ pub fn new(topic: InputTopic, offsets: BTreeMap<u16, ResumeOffset>) -> Self {
+ Self { topic, offsets }
+ }
+
+ pub fn topic(&self) -> &InputTopic {
+ &self.topic
+ }
+
+ pub fn offsets(&self) -> &BTreeMap<u16, ResumeOffset> {
+ &self.offsets
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum PositionsError {
+ #[error(transparent)]
+ Kafka(#[from] KafkaError),
+ #[error(transparent)]
+ Negative(#[from] NegativeOffset),
+}
+
+/// Reads one input's consumer-group positions without joining the group. Every method blocks, so
+/// async callers go through `spawn_blocking`.
+struct GroupReader {
+ topic: InputTopic,
+ config: ClientConfig,
+}
+
+impl GroupReader {
+ fn new(config: &Config, topic: &str, group: &str) -> Self {
+ Self {
+ topic: InputTopic::new(topic),
+ config: config.follower_client_config(group),
+ }
+ }
+
+ /// A client that never subscribes or assigns, so it outlives the group's own consumer at
+ /// shutdown and never takes part in a rebalance. Each call builds its own and drops it: nothing
+ /// polls these clients, so one kept between calls would hold every log and error event
+ /// librdkafka queues for it.
+ fn client(&self) -> KafkaResult<BaseConsumer> {
+ self.config.create()
+ }
+
+ fn topic(&self) -> &InputTopic {
+ &self.topic
+ }
+
+ /// The group's committed offset per partition, or the low watermark where the group has none.
+ /// A consumer without a commit starts at or after the low watermark, so replay from there
+ /// misses nothing.
+ fn resume_positions(
+ &self,
+ partitions: &BTreeSet<u16>,
+ ) -> Result<InputPositions, PositionsError> {
+ let topic = self.topic.as_str();
+ let mut request = TopicPartitionList::new();
+ for &partition in partitions {
+ request.add_partition(topic, i32::from(partition));
+ }
+ let client = self.client()?;
+ let committed = client.committed_offsets(request, FETCH_TIMEOUT)?;
+
+ let mut offsets = BTreeMap::new();
+ let mut uncommitted = Vec::new();
+ for &partition in partitions {
+ let commit = committed.find_partition(topic, i32::from(partition));
+ match commit.as_ref().map(|elem| (elem.error(), elem.offset())) {
+ Some((Err(err), _)) => return Err(err.into()),
+ Some((Ok(()), Offset::Offset(next))) => {
+ offsets.insert(partition, ResumeOffset::try_from(next)?);
+ }
+ _ => uncommitted.push(partition),
+ }
+ }
+ for (partition, low) in low_watermarks(&client, topic, uncommitted)? {
+ offsets.insert(partition, ResumeOffset::try_from(low)?);
+ }
+ Ok(InputPositions::new(self.topic.clone(), offsets))
+ }
+}
+
+/// A follower's group has no members, so a commit from any client needs no generation. Only
+/// followers get one: the events group commits through its member consumer.
+pub struct FollowerGroup(GroupReader);
+
+impl FollowerGroup {
+ pub fn topic(&self) -> &InputTopic {
+ self.0.topic()
+ }
+
+ pub fn commit(&self, positions: &BTreeMap<u16, ResumeOffset>) -> KafkaResult<()> {
+ if positions.is_empty() {
+ return Ok(());
+ }
+ let mut tpl = TopicPartitionList::new();
+ for (&partition, &offset) in positions {
+ tpl.add_partition_offset(
+ self.topic().as_str(),
+ i32::from(partition),
+ Offset::Offset(offset.get()),
+ )?;
+ }
+ self.0.client()?.commit(&tpl, CommitMode::Sync)
+ }
+}
+
+/// Every enabled input, built once at startup and shared by the restore and the checkpoint sweeper.
+pub struct InputGroups {
+ events: GroupReader,
+ followers: Vec<FollowerGroup>,
+}
+
+impl InputGroups {
+ pub fn new(config: &Config) -> Self {
+ let events = GroupReader::new(
+ config,
+ &config.cohort_stream_events_topic,
+ &config.kafka_consumer_group,
+ );
+ let mut follower_inputs = vec![
+ (
+ &config.person_merge_events_topic,
+ &config.kafka_merge_consumer_group,
+ ),
+ (
+ &config.cohort_merge_state_transfer_topic,
+ &config.kafka_merge_apply_consumer_group,
+ ),
+ ];
+ if config.cohort_cascade_enabled {
+ follower_inputs.push((
+ &config.cohort_cascade_events_topic,
+ &config.kafka_cascade_consumer_group,
+ ));
+ }
+ if config.cohort_seed_consumer_enabled {
+ follower_inputs.push((
+ &config.cohort_stream_seed_events_topic,
+ &config.kafka_seed_consumer_group,
+ ));
+ }
+ let followers = follower_inputs
+ .into_iter()
+ .map(|(topic, group)| FollowerGroup(GroupReader::new(config, topic, group)))
+ .collect();
+ Self { events, followers }
+ }
+
+ pub fn followers(&self) -> &[FollowerGroup] {
+ &self.followers
+ }
+
+ /// Every input's resume positions on `partitions`.
+ pub fn resume_positions(
+ &self,
+ partitions: &BTreeSet<u16>,
+ ) -> Result<Vec<InputPositions>, PositionsError> {
+ self.readers()
+ .map(|reader| reader.resume_positions(partitions))
+ .collect()
+ }
+
+ fn readers(&self) -> impl Iterator<Item = &GroupReader> {
+ std::iter::once(&self.events).chain(self.followers.iter().map(|follower| &follower.0))
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
index 5ff6887389cd..d56098489aca 100644
--- a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
+++ b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
@@ -1,16 +1,17 @@
//! The checkpoint orchestrator.
//!
//! [`CheckpointSweeper`] is one sweep loop, driven by
-//! [`run_sweep_loop`](crate::sweep::run_sweep_loop) at `checkpoint_interval`. Each tick takes a frozen
-//! whole-DB RocksDB checkpoint to the local PVC; every Nth tick it also uploads that checkpoint to S3
-//! incrementally (only the SSTs that changed). One `create_checkpoint` per tick — never two racing.
+//! [`run_sweep_loop`](crate::sweep::run_sweep_loop) at `checkpoint_interval`. Each tick takes a
+//! frozen whole-DB RocksDB checkpoint to the local volume, beside an offset manifest read from the
+//! consumer groups; every Nth tick it also uploads that checkpoint to S3 incrementally. One
+//! `create_checkpoint` per tick, never two racing.
//!
-//! ## Interior mutability without a mutex across `.await`
+//! ## Interior mutability without a lock across `.await`
//!
-//! The tick counter is an [`AtomicU64`] (`fetch_add`, no await). The incremental-upload baseline (the
-//! last-uploaded [`CheckpointMetadata`]) is a [`tokio::sync::Mutex`], but it is never held across an
-//! `.await`: the baseline is cloned out under the guard, which is then dropped, the plan + upload run
-//! lock-free, and on a successful upload the new baseline is stored under a fresh, momentary lock.
+//! The tick counter is an [`AtomicU64`]. The incremental-upload baseline (the last uploaded
+//! [`CheckpointMetadata`]) sits behind a [`Mutex`] that is never held across an `.await`: the
+//! baseline is cloned out under the guard, the plan and upload run lock-free, and a successful
+//! upload stores the new baseline under a fresh, momentary lock.
//!
//! ## Must not panic
//!
@@ -23,35 +24,34 @@
// sanctioned. See `checkpoint_once`.
#![allow(clippy::disallowed_methods)]
+use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use chrono::Utc;
-use tokio::sync::Mutex;
+use tokio::sync::OnceCell;
use tracing::{error, info, warn};
+use super::lineage::CheckpointLineage;
use super::{
- plan_checkpoint, CheckpointExporter, CheckpointMetadata, DurabilityConfig, OffsetManifest,
- STORE_PARTITION, STORE_TOPIC,
+ plan_checkpoint, CheckpointExporter, CheckpointMetadata, CheckpointPlan, DurabilityConfig,
+ OffsetManifest, S3Uploader, METADATA_FILENAME,
};
use crate::consumers::EventDispatcher;
use crate::observability::metrics::{
- CHECKPOINT_FILES_UPLOADED_TOTAL, CHECKPOINT_FILE_COUNT, CHECKPOINT_SIZE_BYTES,
- CHECKPOINT_UPLOADS_TOTAL,
+ CHECKPOINT_CAPTURE_FAILURES_TOTAL, CHECKPOINT_FILE_COUNT,
+ CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS, CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS,
+ CHECKPOINT_SIZE_BYTES, CHECKPOINT_UPLOADS_TOTAL,
};
-use crate::partitions::OffsetTracker;
+use crate::partitions::InputGroups;
use crate::store::CohortStore;
use crate::sweep::Sweeper;
/// The loop-name label for the checkpoint sweep cycle metrics.
pub const CHECKPOINT_LOOP_NAME: &str = "checkpoint";
-/// One topic and the [`OffsetTracker`] that tracks its committed positions, passed to
-/// [`CheckpointSweeper::new`].
-pub type TrackedTopic = (String, Arc<OffsetTracker>);
-
/// True on every `every_n`-th tick (tick 0, N, 2N, …). `every_n == 0` is treated as 1.
pub fn should_upload(tick: u64, every_n: u64) -> bool {
let n = every_n.max(1);
@@ -64,65 +64,58 @@ pub fn upload_cadence(checkpoint_interval_ms: u64, s3_upload_interval_ms: u64) -
(s3_upload_interval_ms / checkpoint_interval_ms.max(1)).max(1)
}
-/// Drives periodic whole-DB checkpoints to the local PVC + incremental S3 backup.
+/// Drives periodic whole-DB checkpoints to the local volume plus incremental S3 backup.
pub struct CheckpointSweeper {
store: CohortStore,
dispatcher: Arc<EventDispatcher>,
- /// The `(topic, tracker)` pairs whose committed offsets the manifest captures.
- trackers: Vec<TrackedTopic>,
- exporter: CheckpointExporter,
+ groups: Arc<InputGroups>,
+ lineage: CheckpointLineage,
config: DurabilityConfig,
- /// Base dir for local checkpoints; a sibling subtree of `store_path` (RocksDB hard-links SSTs, so
- /// it must be on the same filesystem and must not be a child of the store path).
- checkpoint_local_dir: PathBuf,
+ /// Built on the first upload, so an S3 outage never stops a pod that has its store.
+ exporter: OnceCell<CheckpointExporter>,
tick: AtomicU64,
upload_every_n: u64,
- /// Baseline for the next incremental S3 diff. Cloned out before the upload await (never held
- /// across `.await`); updated only after a successful upload. `None` until the first upload.
- last_uploaded: Mutex<Option<CheckpointMetadata>>,
+ /// Baseline for the next incremental upload. Updated only after a successful upload.
+ baseline: Mutex<Option<CheckpointMetadata>>,
}
impl CheckpointSweeper {
pub fn new(
store: CohortStore,
dispatcher: Arc<EventDispatcher>,
- trackers: Vec<TrackedTopic>,
- exporter: CheckpointExporter,
+ groups: Arc<InputGroups>,
+ lineage: CheckpointLineage,
config: DurabilityConfig,
- checkpoint_local_dir: PathBuf,
upload_every_n: u64,
) -> Self {
+ let started = Utc::now().timestamp() as f64;
+ metrics::gauge!(CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS).set(started);
+ metrics::gauge!(CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS).set(started);
Self {
store,
dispatcher,
- trackers,
- exporter,
+ groups,
+ lineage,
config,
- checkpoint_local_dir,
+ exporter: OnceCell::new(),
tick: AtomicU64::new(0),
upload_every_n,
- last_uploaded: Mutex::new(None),
+ baseline: Mutex::new(None),
}
}
- fn attempt_parent(&self) -> PathBuf {
- self.checkpoint_local_dir
- .join(STORE_TOPIC)
- .join(STORE_PARTITION.to_string())
+ fn local_dir(&self) -> PathBuf {
+ self.lineage
+ .local_dir(Path::new(&self.config.local_checkpoint_dir))
}
async fn checkpoint_once(&self) {
let tick = self.tick.fetch_add(1, Ordering::SeqCst);
- // The checkpoint sweeper runs its own `spawn_blocking` and catches every `JoinError` to
- // log-and-skip: the `Sweeper` contract forbids panicking (a panic aborts the timer task and
- // stops all future checkpoints), so store panics must not propagate out of this loop.
- //
- // 1. fsync the WAL before the snapshot so `committed <= durable` holds. A failure here would
- // yield a checkpoint whose manifest claims more than is durable — skip the tick.
+ // 1. fsync the WAL before the snapshot. The checkpoint must hold at least what the commits
+ // read in step 3 cover, and each of those followed its own fsync.
let flush_store = self.store.clone();
- let flush_result = tokio::task::spawn_blocking(move || flush_store.flush_wal_sync()).await;
- match flush_result {
+ match tokio::task::spawn_blocking(move || flush_store.flush_wal_sync()).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
warn!(error = %e, "checkpoint tick: WAL fsync failed; skipping tick");
@@ -138,35 +131,66 @@ impl CheckpointSweeper {
}
}
- // 2. Capture committed offsets (not committable/processed) for all owned partitions.
- let owned = self.dispatcher.owned_partitions();
- let tracker_refs: Vec<(&str, &OffsetTracker)> = self
- .trackers
- .iter()
- .map(|(topic, tracker)| (topic.as_str(), tracker.as_ref()))
+ // 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.
+ let owned: BTreeSet<u16> = self
+ .dispatcher
+ .owned_partitions()
+ .into_iter()
+ .filter_map(|partition| u16::try_from(partition).ok())
.collect();
- let manifest = OffsetManifest::capture(&owned, &tracker_refs);
+ if owned.is_empty() {
+ info!("checkpoint tick: no owned slice; skipping tick");
+ return;
+ }
- // 3. Take a whole-DB RocksDB checkpoint (sync I/O → spawn_blocking). The attempt dir must
+ // 3. Every input's resume positions, from its consumer group on the broker.
+ let groups = self.groups.clone();
+ let partitions = owned.clone();
+ let positions = match tokio::task::spawn_blocking(move || {
+ groups.resume_positions(&partitions)
+ })
+ .await
+ {
+ Ok(Ok(positions)) => positions,
+ Ok(Err(e)) => {
+ warn!(error = %e, "checkpoint tick: reading input positions failed; skipping tick");
+ metrics::counter!(CHECKPOINT_CAPTURE_FAILURES_TOTAL, "reason" => "positions")
+ .increment(1);
+ return;
+ }
+ Err(join_err) => {
+ error!(error = %join_err, "checkpoint tick: reading input positions panicked; skipping tick");
+ metrics::counter!(CHECKPOINT_CAPTURE_FAILURES_TOTAL, "reason" => "positions")
+ .increment(1);
+ return;
+ }
+ };
+
+ // 4. The manifest refuses a slice that lacks a position on any input.
+ let manifest = match OffsetManifest::capture(self.lineage.ordinal(), &owned, positions) {
+ Ok(manifest) => manifest,
+ Err(e) => {
+ warn!(error = %e, "checkpoint tick: incomplete manifest; skipping tick");
+ metrics::counter!(CHECKPOINT_CAPTURE_FAILURES_TOTAL, "reason" => "incomplete")
+ .increment(1);
+ return;
+ }
+ };
+
+ // 5. Take a whole-DB RocksDB checkpoint (sync I/O → spawn_blocking). The attempt dir must
// not be a child of store_path; SST hard-links require the same filesystem.
let attempt_timestamp = Utc::now();
- let checkpoint_id = format!(
- "{}-{tick}",
- CheckpointMetadata::generate_id(attempt_timestamp)
- );
- let attempt_dir = self.attempt_parent().join(&checkpoint_id);
+ let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
+ let attempt_dir = self.local_dir().join(&checkpoint_id);
// `create_checkpoint` requires the leaf to NOT exist; it creates it and errors if it does.
- if let Err(e) = tokio::fs::create_dir_all(self.attempt_parent()).await {
- warn!(error = %e, dir = %self.attempt_parent().display(), "checkpoint tick: cannot create attempt parent dir; skipping tick");
+ if let Err(e) = tokio::fs::create_dir_all(self.local_dir()).await {
+ warn!(error = %e, dir = %self.local_dir().display(), "checkpoint tick: cannot create attempt parent dir; skipping tick");
return;
}
let checkpoint_store = self.store.clone();
let checkpoint_dir = attempt_dir.clone();
- debug_assert!(
- !attempt_dir.exists(),
- "checkpoint attempt dir must not exist before create_checkpoint: {}",
- attempt_dir.display(),
- );
let create_result = tokio::task::spawn_blocking(move || {
checkpoint_store.create_checkpoint(&checkpoint_dir)
})
@@ -185,22 +209,24 @@ impl CheckpointSweeper {
}
}
- // 4. Write offsets.json after create_checkpoint (so it is never frozen mid-write) but before
+ // 6. Write offsets.json after create_checkpoint (so it is never frozen mid-write) but before
// planning, so the planner tracks it as a non-SST file and the S3 upload carries it.
- // Without offsets.json an S3 restore cannot seek. metadata.json is written after planning.
if let Err(e) = manifest.write_to_dir(&attempt_dir) {
warn!(error = %e, "checkpoint tick: writing offsets.json failed; skipping tick");
drop(tokio::fs::remove_dir_all(&attempt_dir).await);
return;
}
- // 5. Plan the incremental diff vs the last-uploaded baseline, then write metadata.json.
- let baseline = { self.last_uploaded.lock().await.clone() };
+ // 7. Plan against the baseline, then write metadata.json.
+ let baseline = self
+ .baseline
+ .lock()
+ .expect("the baseline lock is never held across a panic")
+ .clone();
let plan = match plan_checkpoint(
&attempt_dir,
+ CheckpointMetadata::new(self.lineage.ordinal(), attempt_timestamp),
self.config.s3_key_prefix.clone(),
- attempt_timestamp,
- tick,
baseline.as_ref(),
None,
) {
@@ -211,18 +237,22 @@ impl CheckpointSweeper {
return;
}
};
-
- let mut info = plan.info.clone();
- if let Err(e) = info.metadata.write_to_dir(&attempt_dir).await {
+ if let Err(e) = plan
+ .info
+ .metadata
+ .save(&attempt_dir.join(METADATA_FILENAME))
+ {
warn!(error = %e, "checkpoint tick: writing metadata.json failed; skipping tick");
drop(tokio::fs::remove_dir_all(&attempt_dir).await);
return;
}
- // 6. Emit local-checkpoint size and file-count metrics.
+ // 8. Emit local-checkpoint size and file-count metrics.
let (size_bytes, file_count) = dir_size_and_count(&attempt_dir);
metrics::histogram!(CHECKPOINT_SIZE_BYTES).record(size_bytes as f64);
metrics::histogram!(CHECKPOINT_FILE_COUNT).record(file_count as f64);
+ metrics::gauge!(CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS)
+ .set(manifest.captured_at().timestamp() as f64);
info!(
checkpoint_id,
dir = %attempt_dir.display(),
@@ -231,42 +261,53 @@ impl CheckpointSweeper {
"local checkpoint taken",
);
- // 7. Every Nth tick: upload to S3 and advance the baseline on success.
+ // 9. Upload when due, and advance the baseline on success.
if should_upload(tick, self.upload_every_n) {
self.upload(&plan).await;
}
- // 8. Prune older local checkpoint dirs (keep latest only) to avoid pinning SSTs that the live
+ // 10. Prune older local checkpoint dirs (keep latest only) to avoid pinning SSTs that the live
// DB compacted away, which would cause unbounded PVC growth.
self.prune_old_checkpoints(&attempt_dir).await;
}
- async fn upload(&self, plan: &super::CheckpointPlan) {
- let files_in_plan = plan.files_to_upload.len();
- match self
+ async fn upload(&self, plan: &CheckpointPlan) {
+ let exporter = match self
.exporter
- .export_checkpoint_with_plan_cancellable(plan, None, None)
+ .get_or_try_init(|| async {
+ S3Uploader::new(self.config.clone(), self.lineage)
+ .await
+ .map(|uploader| CheckpointExporter::new(Box::new(uploader)))
+ })
.await
{
- Ok(()) => {
- metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "success")
- .increment(files_in_plan as u64);
- {
- let mut baseline = self.last_uploaded.lock().await;
- *baseline = Some(plan.info.metadata.clone());
- }
- info!(uploaded_files = files_in_plan, "checkpoint uploaded to S3");
- }
+ Ok(exporter) => exporter,
Err(e) => {
- metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "error")
- .increment(files_in_plan as u64);
- warn!(error = %e, "checkpoint S3 upload failed; baseline unchanged");
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "unavailable").increment(1);
+ warn!(error = %format!("{e:#}"), "checkpoint S3 uploader unavailable; retrying on the next upload");
+ return;
}
+ };
+
+ if let Err(e) = exporter.export_checkpoint_with_plan(plan).await {
+ warn!(error = %format!("{e:#}"), "checkpoint S3 upload failed; baseline unchanged");
+ return;
}
+ metrics::gauge!(CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS)
+ .set(Utc::now().timestamp() as f64);
+ *self
+ .baseline
+ .lock()
+ .expect("the baseline lock is never held across a panic") =
+ Some(plan.info.metadata.clone());
+ info!(
+ uploaded_files = plan.files_to_upload.len(),
+ "checkpoint uploaded to S3"
+ );
}
async fn prune_old_checkpoints(&self, keep: &Path) {
- let parent = self.attempt_parent();
+ let parent = self.local_dir();
let entries = match tokio::fs::read_dir(&parent).await {
Ok(entries) => entries,
Err(_) => return,
diff --git a/rust/cohort-stream-processor/src/store/durability/config.rs b/rust/cohort-stream-processor/src/store/durability/config.rs
index 5f2e0abef90e..fb3ff214eeb8 100644
--- a/rust/cohort-stream-processor/src/store/durability/config.rs
+++ b/rust/cohort-stream-processor/src/store/durability/config.rs
@@ -65,9 +65,8 @@ pub struct DurabilityConfig {
/// BufWriter).
pub max_upload_buffers: usize,
- /// Maximum time allowed for a complete checkpoint import. This includes listing checkpoints,
- /// downloading metadata, and downloading all files. Should be less than Kafka max.poll.interval.ms
- /// to prevent consumer group kicks.
+ /// Maximum time to download one checkpoint candidate's files. A candidate that takes longer
+ /// fails and ends the search, because older candidates are about as large.
pub checkpoint_import_timeout: Duration,
/// Maximum age of a local checkpoint before the local store is considered stale and the service
@@ -96,7 +95,7 @@ impl Default for DurabilityConfig {
max_concurrent_checkpoint_file_downloads: 40,
max_concurrent_checkpoint_file_uploads: 40,
max_upload_buffers: 40,
- checkpoint_import_timeout: Duration::from_secs(240),
+ checkpoint_import_timeout: Duration::from_secs(7200),
local_checkpoint_max_staleness: Duration::from_secs(
DEFAULT_LOCAL_CHECKPOINT_MAX_STALENESS_SECS,
),
diff --git a/rust/cohort-stream-processor/src/store/durability/downloader.rs b/rust/cohort-stream-processor/src/store/durability/downloader.rs
index 48c2a072a5c0..f2a8b8e6eaaa 100644
--- a/rust/cohort-stream-processor/src/store/durability/downloader.rs
+++ b/rust/cohort-stream-processor/src/store/durability/downloader.rs
@@ -1,12 +1,14 @@
use anyhow::Result;
use async_trait::async_trait;
+use chrono::{DateTime, Utc};
use std::path::Path;
use tokio_util::sync::CancellationToken;
#[async_trait]
pub trait CheckpointDownloader: Send + Sync + std::fmt::Debug {
- /// List remote checkpoint-attempt metadata.json keys, sorted newest to oldest.
- async fn list_recent_checkpoints(&self) -> Result<Vec<String>>;
+ /// List the metadata.json keys of the checkpoint attempts inside the import window that ends at
+ /// `now`, sorted newest to oldest.
+ async fn list_recent_checkpoints(&self, now: DateTime<Utc>) -> Result<Vec<String>>;
/// Download a single remote file and return its bytes.
async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>>;
@@ -38,6 +40,4 @@ pub trait CheckpointDownloader: Send + Sync + std::fmt::Debug {
local_base_path: &Path,
cancel_token: Option<&CancellationToken>,
) -> Result<()>;
-
- async fn is_available(&self) -> bool;
}
diff --git a/rust/cohort-stream-processor/src/store/durability/error.rs b/rust/cohort-stream-processor/src/store/durability/error.rs
index bcada21f2472..2d65f0c5ae6e 100644
--- a/rust/cohort-stream-processor/src/store/durability/error.rs
+++ b/rust/cohort-stream-processor/src/store/durability/error.rs
@@ -47,23 +47,3 @@ impl fmt::Display for PlanningCancelledError {
}
impl std::error::Error for PlanningCancelledError {}
-
-/// A checkpoint import timed out, bounding import time below Kafka's max poll interval. Detect via
-/// `downcast_ref::<Self>()`. `store` is a static descriptor since the whole DB imports as one unit.
-#[derive(Debug)]
-pub struct ImportTimeoutError {
- pub store: &'static str,
- pub timeout_secs: u64,
-}
-
-impl fmt::Display for ImportTimeoutError {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(
- f,
- "Checkpoint import timed out after {}s for {}",
- self.timeout_secs, self.store
- )
- }
-}
-
-impl std::error::Error for ImportTimeoutError {}
diff --git a/rust/cohort-stream-processor/src/store/durability/export.rs b/rust/cohort-stream-processor/src/store/durability/export.rs
index eba145315467..6a790b777dd4 100644
--- a/rust/cohort-stream-processor/src/store/durability/export.rs
+++ b/rust/cohort-stream-processor/src/store/durability/export.rs
@@ -110,7 +110,7 @@ mod tests {
use chrono::{TimeZone, Utc};
use crate::store::durability::{
- CheckpointInfo, CheckpointMetadata, UploadCancelledError, STORE_PARTITION, STORE_TOPIC,
+ CheckpointInfo, CheckpointMetadata, PodOrdinal, UploadCancelledError,
};
#[derive(Debug)]
@@ -168,15 +168,8 @@ mod tests {
fn create_test_plan() -> CheckpointPlan {
let timestamp = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- timestamp,
- 12345,
- 0,
- 0,
- );
- let info = CheckpointInfo::new(metadata, "checkpoints".to_string(), None);
+ let metadata = CheckpointMetadata::new(PodOrdinal::STANDALONE, timestamp);
+ let info = CheckpointInfo::new(metadata, "checkpoints".to_string());
CheckpointPlan {
info,
files_to_upload: vec![],
diff --git a/rust/cohort-stream-processor/src/store/durability/import.rs b/rust/cohort-stream-processor/src/store/durability/import.rs
index e22b877c8ee3..bfb60e97b5c4 100644
--- a/rust/cohort-stream-processor/src/store/durability/import.rs
+++ b/rust/cohort-stream-processor/src/store/durability/import.rs
@@ -1,856 +1,122 @@
-use std::path::{Path, PathBuf};
-use std::time::{Duration, Instant};
+//! Reads checkpoint candidates from S3. Deciding which candidate to restore is
+//! [`recovery`](super::recovery)'s job; this module only downloads and decodes.
-use super::error::{DownloadCancelledError, ImportTimeoutError};
-use super::{CheckpointDownloader, CheckpointMetadata, DirCleanupGuard, STORE_TOPIC};
-use crate::observability::metrics::{
- CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, CHECKPOINT_IMPORT_DURATION_SECONDS,
-};
-use crate::store::STORE_SCHEMA_VERSION;
+use std::path::Path;
+use std::time::{Duration, Instant};
-use anyhow::{Context, Result};
+use chrono::{DateTime, Utc};
use tokio_util::sync::CancellationToken;
-use tracing::{error, info, warn};
+use tracing::info;
+
+use super::manifest::{ManifestError, OffsetManifest, MANIFEST_FILENAME};
+use super::metadata::{CheckpointMetadata, MetadataError, METADATA_FILENAME};
+use super::CheckpointDownloader;
+use crate::observability::metrics::CHECKPOINT_IMPORT_DURATION_SECONDS;
+
+#[derive(Debug, thiserror::Error)]
+pub enum ImportError {
+ /// The attempt has no `metadata.json`: its upload failed or was cancelled before the end, since
+ /// `metadata.json` is written last.
+ #[error("the attempt has no {METADATA_FILENAME}, so its upload never finished")]
+ Unfinished,
+ #[error(transparent)]
+ Download(anyhow::Error),
+ #[error(transparent)]
+ Metadata(#[from] MetadataError),
+ #[error(transparent)]
+ Manifest(#[from] ManifestError),
+ #[error("the checkpoint tracks no {MANIFEST_FILENAME}")]
+ NoManifest,
+ #[error("downloading the checkpoint files took longer than {0:?}")]
+ Timeout(Duration),
+}
#[derive(Debug)]
pub struct CheckpointImporter {
downloader: Box<dyn CheckpointDownloader>,
- import_attempt_depth: usize,
import_timeout: Duration,
}
impl CheckpointImporter {
- pub fn new(
- downloader: Box<dyn CheckpointDownloader>,
- import_attempt_depth: usize,
- import_timeout: Duration,
- ) -> Self {
+ pub fn new(downloader: Box<dyn CheckpointDownloader>, import_timeout: Duration) -> Self {
Self {
downloader,
- import_attempt_depth,
import_timeout,
}
}
- /// Lists recent checkpoint metadata.json keys (newest first), tries up to `import_attempt_depth`
- /// of them lazily (one metadata download at a time), and falls back to the next on failure. On
- /// success, downloads all tracked files and writes metadata.json into `target_path`.
- pub async fn import_checkpoint(&self, target_path: &Path) -> Result<PathBuf> {
- self.import_checkpoint_cancellable(target_path, None).await
- }
-
- /// Import with optional cancellation. The whole operation is bounded by `import_timeout` to stay
- /// below Kafka's max poll interval.
- pub async fn import_checkpoint_cancellable(
- &self,
- target_path: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<PathBuf> {
- let start_time = Instant::now();
-
- match tokio::time::timeout(
- self.import_timeout,
- self.import_checkpoint_inner(target_path, cancel_token, start_time),
- )
- .await
- {
- Ok(result) => result,
- Err(_elapsed) => {
- error!(
- store = STORE_TOPIC,
- timeout_secs = self.import_timeout.as_secs(),
- elapsed_secs = start_time.elapsed().as_secs_f64(),
- "Checkpoint import timed out"
- );
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "timeout")
- .record(start_time.elapsed().as_secs_f64());
- Err(ImportTimeoutError {
- store: STORE_TOPIC,
- timeout_secs: self.import_timeout.as_secs(),
- }
- .into())
- }
- }
- }
-
- async fn import_checkpoint_inner(
- &self,
- target_path: &Path,
- cancel_token: Option<&CancellationToken>,
- start_time: Instant,
- ) -> Result<PathBuf> {
- let metadata_keys = match self.downloader.list_recent_checkpoints().await {
- Ok(keys) => keys,
- Err(e) => {
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
- .record(start_time.elapsed().as_secs_f64());
- return Err(e).context("listing checkpoint metadata");
- }
- };
-
- if metadata_keys.is_empty() {
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
- .record(start_time.elapsed().as_secs_f64());
- return Err(anyhow::anyhow!(
- "No checkpoint metadata files found for store {STORE_TOPIC}"
- ));
- }
-
- let metadata_keys: Vec<_> = metadata_keys
- .into_iter()
- .take(self.import_attempt_depth)
- .collect();
-
- info!(
- "Found checkpoint metadata keys for store {STORE_TOPIC}, will attempt up to {} (newest first)",
- metadata_keys.len(),
- );
-
- let target_path_tag = target_path.to_string_lossy().to_string();
-
- for remote_key in &metadata_keys {
- if let Some(token) = cancel_token {
- if token.is_cancelled() {
- warn!(
- store = STORE_TOPIC,
- "Checkpoint import cancelled before attempt"
- );
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "cancelled")
- .record(start_time.elapsed().as_secs_f64());
- return Err(DownloadCancelledError {
- reason: "import cancelled before attempt".to_string(),
- }
- .into());
- }
- }
-
- let attempt_start = Instant::now();
-
- let mut attempt = match self.downloader.download_file(remote_key).await {
- Ok(content) => match CheckpointMetadata::from_json_bytes(&content) {
- Ok(metadata) => metadata,
- Err(e) => {
- error!("Failed to parse metadata: {remote_key}: {e:#}");
- continue;
- }
- },
- Err(e) => {
- error!("Failed to download metadata: {remote_key}: {e:#}");
- continue;
- }
- };
-
- // Skip a schema-mismatched checkpoint before the bulk data-file download or any local dir
- // mutation. Skipping (not failing) falls through to the next candidate, and a fully-skipped
- // list downgrades to a cold start in `restore_from_s3`.
- if attempt.store_schema != STORE_SCHEMA_VERSION {
- warn!(
- store = STORE_TOPIC,
- checkpoint = %remote_key,
- found = attempt.store_schema,
- expected = STORE_SCHEMA_VERSION,
- "Skipping checkpoint written under a different store schema version",
- );
- continue;
- }
-
- let attempt_tag = attempt.get_attempt_path();
-
- if target_path.exists() {
- info!(
- store = STORE_TOPIC,
- path = %target_path.display(),
- "Removing stale local store before import"
- );
- drop(tokio::fs::remove_dir_all(target_path).await);
- }
-
- if let Err(e) = tokio::fs::create_dir_all(target_path).await {
- metrics::histogram!(CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, "result" => "failed")
- .record(attempt_start.elapsed().as_secs_f64());
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
- .record(start_time.elapsed().as_secs_f64());
- return Err(e).with_context(|| {
- format!("Failed to create local directory for import: {target_path_tag}")
- });
- }
-
- let guard = DirCleanupGuard::new(target_path.to_path_buf());
-
- // A failed file cancels siblings, but the parent token survives so the next attempt can proceed.
- let attempt_token = cancel_token
- .map(|parent| parent.child_token())
- .unwrap_or_default();
-
- match self
- .fetch_checkpoint_files_cancellable(&attempt, target_path, Some(&attempt_token))
- .await
- {
- Ok(_) => {
- let attempt_duration = attempt_start.elapsed().as_secs_f64();
-
- attempt.write_to_dir(target_path).await.with_context(|| {
- format!("Failed to write metadata.json to import dir: {target_path_tag}")
- })?;
-
- info!(
- checkpoint = attempt_tag,
- local_store_path = target_path_tag,
- original_checkpoint_timestamp = %attempt.attempt_timestamp,
- attempt_duration_secs = attempt_duration,
- total_duration_secs = start_time.elapsed().as_secs_f64(),
- "Successfully imported checkpoint to local directory"
- );
- metrics::histogram!(CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, "result" => "success")
- .record(attempt_duration);
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "success")
- .record(start_time.elapsed().as_secs_f64());
-
- return Ok(guard.defuse());
- }
- Err(e) => {
- let attempt_duration = attempt_start.elapsed().as_secs_f64();
- metrics::histogram!(CHECKPOINT_IMPORT_ATTEMPT_DURATION_SECONDS, "result" => "failed")
- .record(attempt_duration);
- error!(
- checkpoint = attempt_tag,
- local_attempt_path = target_path_tag,
- attempt_duration_secs = attempt_duration,
- error = ?e,
- "Failed to import checkpoint files"
- );
- continue;
- }
- }
- }
-
- let err_msg =
- format!("No usable checkpoints identified in recovery window for store {STORE_TOPIC}");
- error!(err_msg);
- metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => "failed")
- .record(start_time.elapsed().as_secs_f64());
- Err(anyhow::anyhow!(err_msg))
+ /// Metadata keys of the lineage's attempts inside the listing window that ends at `now`, newest
+ /// first.
+ pub async fn candidates(&self, now: DateTime<Utc>) -> anyhow::Result<Vec<String>> {
+ self.downloader.list_recent_checkpoints(now).await
}
- pub async fn fetch_checkpoint_files(
- &self,
- checkpoint_metadata: &CheckpointMetadata,
- local_attempt_path: &Path,
- ) -> Result<()> {
- self.fetch_checkpoint_files_cancellable(checkpoint_metadata, local_attempt_path, None)
+ pub async fn metadata(&self, metadata_key: &str) -> Result<CheckpointMetadata, ImportError> {
+ let bytes = self
+ .downloader
+ .download_file(metadata_key)
.await
+ .map_err(|err| match err.downcast_ref::<object_store::Error>() {
+ Some(object_store::Error::NotFound { .. }) => ImportError::Unfinished,
+ _ => ImportError::Download(err),
+ })?;
+ Ok(CheckpointMetadata::from_json_bytes(&bytes)?)
}
- pub async fn fetch_checkpoint_files_cancellable(
+ /// The candidate's `offsets.json`, downloaded alone so a candidate is judged before its bulk
+ /// download.
+ pub async fn manifest(
&self,
- checkpoint_metadata: &CheckpointMetadata,
- local_attempt_path: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- let target_files = checkpoint_metadata
+ metadata: &CheckpointMetadata,
+ ) -> Result<OffsetManifest, ImportError> {
+ let suffix = format!("/{MANIFEST_FILENAME}");
+ let key = metadata
.files
.iter()
- .map(|f| f.remote_filepath.clone())
- .collect::<Vec<_>>();
-
- info!(
- metadata = checkpoint_metadata.get_metadata_filepath(),
- file_count = checkpoint_metadata.files.len(),
- "Fetching checkpoint files from metadata tracking list",
- );
-
- match self
+ .find(|file| file.remote_filepath.ends_with(&suffix))
+ .ok_or(ImportError::NoManifest)?;
+ let bytes = self
.downloader
- .download_files_cancellable(&target_files, local_attempt_path, cancel_token)
+ .download_file(&key.remote_filepath)
.await
- {
- Ok(_) => {
- info!(
- "Successfully downloaded {} checkpoint files to: {local_attempt_path:?}",
- target_files.len()
- );
- Ok(())
- }
- Err(e) => {
- error!("Failed to download checkpoint files to: {local_attempt_path:?}: {e:#}");
- Err(e)
- }
- }
- }
-
- pub async fn is_available(&self) -> bool {
- self.downloader.is_available().await
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use async_trait::async_trait;
- use chrono::{TimeZone, Utc};
- use std::sync::atomic::{AtomicUsize, Ordering};
- use std::sync::Arc;
- use std::time::Duration;
- use tempfile::TempDir;
-
- use crate::store::durability::{STORE_PARTITION, STORE_TOPIC};
-
- #[derive(Debug)]
- struct MockDownloader {
- metadata: CheckpointMetadata,
- download_count: Arc<AtomicUsize>,
- }
-
- impl MockDownloader {
- fn new(metadata: CheckpointMetadata) -> Self {
- Self {
- metadata,
- download_count: Arc::new(AtomicUsize::new(0)),
- }
- }
- }
-
- #[async_trait]
- impl CheckpointDownloader for MockDownloader {
- async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
- Ok(vec![self.metadata.get_metadata_filepath()])
- }
-
- async fn download_file(&self, _remote_key: &str) -> Result<Vec<u8>> {
- let json = self.metadata.to_json()?;
- Ok(json.into_bytes())
- }
-
- async fn download_and_store_file_cancellable(
- &self,
- _remote_key: &str,
- local_filepath: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- if let Some(token) = cancel_token {
- if token.is_cancelled() {
- return Err(DownloadCancelledError {
- reason: "test mock".to_string(),
- }
- .into());
- }
- }
- tokio::fs::write(local_filepath, b"mock file content").await?;
- Ok(())
- }
-
- async fn download_files_cancellable(
- &self,
- remote_keys: &[String],
- local_base_path: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- self.download_count.fetch_add(1, Ordering::SeqCst);
- for key in remote_keys {
- let filename = key.rsplit('/').next().unwrap_or(key);
- let local_path = local_base_path.join(filename);
- self.download_and_store_file_cancellable(key, &local_path, cancel_token)
- .await?;
- }
- Ok(())
- }
-
- async fn is_available(&self) -> bool {
- true
- }
- }
-
- #[derive(Debug)]
- struct CancellationTestDownloader {
- checkpoints: Vec<CheckpointMetadata>,
- }
-
- impl CancellationTestDownloader {
- fn new(checkpoints: Vec<CheckpointMetadata>) -> Self {
- Self { checkpoints }
- }
- }
-
- #[async_trait]
- impl CheckpointDownloader for CancellationTestDownloader {
- async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
- Ok(self
- .checkpoints
- .iter()
- .map(CheckpointMetadata::get_metadata_filepath)
- .collect())
- }
-
- async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>> {
- for checkpoint in &self.checkpoints {
- if checkpoint.get_metadata_filepath() == remote_key {
- return Ok(checkpoint.to_json()?.into_bytes());
- }
- }
- Err(anyhow::anyhow!("Metadata not found: {remote_key}"))
- }
-
- async fn download_and_store_file_cancellable(
- &self,
- _remote_key: &str,
- local_filepath: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- if let Some(token) = cancel_token {
- if token.is_cancelled() {
- return Err(DownloadCancelledError {
- reason: "test mock".to_string(),
- }
- .into());
- }
- }
-
- tokio::fs::write(local_filepath, b"mock file content").await?;
- Ok(())
- }
-
- async fn download_files_cancellable(
- &self,
- remote_keys: &[String],
- local_base_path: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- if let Some(token) = cancel_token {
- if token.is_cancelled() {
- return Err(DownloadCancelledError {
- reason: "test mock".to_string(),
- }
- .into());
- }
- }
-
- for key in remote_keys {
- let filename = key.rsplit('/').next().unwrap_or(key);
- let local_path = local_base_path.join(filename);
- self.download_and_store_file_cancellable(key, &local_path, cancel_token)
- .await?;
- }
- Ok(())
- }
-
- async fn is_available(&self) -> bool {
- true
- }
+ .map_err(ImportError::Download)?;
+ Ok(OffsetManifest::decode(&bytes)?)
}
- fn create_test_metadata(hour: u32) -> CheckpointMetadata {
- let timestamp = Utc.with_ymd_and_hms(2025, 6, 15, hour, 0, 0).unwrap();
- let mut metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- timestamp,
- 12345,
- 0,
- 0,
- );
- metadata.track_file(
- format!(
- "checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2025-06-15T{hour:02}-00-00Z/000001.sst"
- ),
- "checksum1".to_string(),
- );
- metadata
- }
-
- #[tokio::test]
- async fn download_files_cancellable_returns_early_when_pre_cancelled() {
- let tmp_dir = TempDir::new().unwrap();
- let metadata = create_test_metadata(12);
- let downloader = CancellationTestDownloader::new(vec![metadata]);
-
- let token = CancellationToken::new();
- token.cancel();
-
- let result = downloader
- .download_files_cancellable(
- &["checkpoints/file.sst".to_string()],
- tmp_dir.path(),
- Some(&token),
- )
- .await;
-
- assert!(result.is_err());
- let err = result.unwrap_err();
- assert!(
- err.downcast_ref::<DownloadCancelledError>().is_some(),
- "Error should be DownloadCancelledError: {err}",
- );
- }
-
- #[tokio::test]
- async fn import_checkpoint_cancellable_returns_early_when_pre_cancelled() {
- let tmp_dir = TempDir::new().unwrap();
- let metadata = create_test_metadata(12);
- let downloader = CancellationTestDownloader::new(vec![metadata]);
- let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));
-
- let token = CancellationToken::new();
- token.cancel();
-
- let result = importer
- .import_checkpoint_cancellable(&tmp_dir.path().join("store"), Some(&token))
- .await;
-
- assert!(result.is_err());
- let err = result.unwrap_err();
- assert!(
- err.downcast_ref::<DownloadCancelledError>().is_some(),
- "Error should be DownloadCancelledError: {err}",
- );
- }
-
- #[tokio::test]
- async fn import_materializes_target_path_with_files_and_metadata() {
- let tmp_dir = TempDir::new().unwrap();
- let target_path = tmp_dir.path().join("store");
-
- let attempt_timestamp = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();
- let mut metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 12345,
- 0,
- 0,
- );
- metadata.track_file(
- format!("checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2025-06-15T12-00-00Z/000001.sst"),
- "checksum1".to_string(),
- );
-
- let downloader = MockDownloader::new(metadata);
- let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));
-
- let before_import = Utc::now();
- let result = importer.import_checkpoint(&target_path).await;
- let after_import = Utc::now();
-
- assert!(result.is_ok(), "Import should succeed: {:?}", result.err());
- let import_path = result.unwrap();
- assert_eq!(import_path, target_path, "Import path should be the target");
- assert!(import_path.exists(), "Import path should exist");
-
- let imported_file = import_path.join("000001.sst");
- assert!(
- imported_file.exists(),
- "Imported SST file should exist after successful import"
- );
-
- let loaded_metadata = CheckpointMetadata::load_from_dir(&import_path)
- .await
- .expect("metadata.json should exist and deserialize");
- assert_eq!(loaded_metadata.topic, STORE_TOPIC);
- assert_eq!(loaded_metadata.partition, STORE_PARTITION);
- assert!(
- loaded_metadata.updated_at.timestamp_millis() >= before_import.timestamp_millis(),
- "updated_at should be >= before_import"
- );
- assert!(
- loaded_metadata.updated_at.timestamp_millis() <= after_import.timestamp_millis(),
- "updated_at should be <= after_import"
- );
- }
-
- #[tokio::test]
- async fn import_skips_a_schema_mismatched_checkpoint_and_uses_the_next() {
- let tmp_dir = TempDir::new().unwrap();
- let target_path = tmp_dir.path().join("store");
-
- let mut newest = create_test_metadata(13);
- newest.store_schema = STORE_SCHEMA_VERSION + 1; // incompatible
- let current = create_test_metadata(12); // stamped with STORE_SCHEMA_VERSION by `new`
- assert_eq!(current.store_schema, STORE_SCHEMA_VERSION);
-
- // Newest first, matching the S3 listing order.
- let downloader = CancellationTestDownloader::new(vec![newest.clone(), current.clone()]);
- let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));
-
- let import_path = importer
- .import_checkpoint(&target_path)
- .await
- .expect("import should skip the mismatched candidate and use the current one");
-
- let loaded = CheckpointMetadata::load_from_dir(&import_path)
- .await
- .expect("metadata.json written for the accepted candidate");
- assert_eq!(
- loaded.store_schema, STORE_SCHEMA_VERSION,
- "the imported checkpoint is the current-era one, not the mismatched newest",
- );
- assert_eq!(
- loaded.id, current.id,
- "the accepted attempt is the older, schema-matching candidate",
- );
- }
-
- #[tokio::test]
- async fn import_fails_when_every_candidate_has_a_mismatched_schema() {
- let tmp_dir = TempDir::new().unwrap();
- let target_path = tmp_dir.path().join("store");
-
- let mut old_era = create_test_metadata(12);
- old_era.store_schema = 0; // pre-versioning metadata.json decodes to this
- let downloader = CancellationTestDownloader::new(vec![old_era]);
- let importer = CheckpointImporter::new(Box::new(downloader), 3, Duration::from_secs(60));
-
- let result = importer.import_checkpoint(&target_path).await;
- assert!(
- result.is_err(),
- "an all-mismatched candidate list yields no usable checkpoint",
- );
- assert!(
- !target_path.exists(),
- "a skipped candidate must not create or leave any local store directory",
- );
- }
-
- #[derive(Debug)]
- struct FailingDownloader {
- metadata: CheckpointMetadata,
- }
-
- impl FailingDownloader {
- fn new(metadata: CheckpointMetadata) -> Self {
- Self { metadata }
- }
- }
-
- #[async_trait]
- impl CheckpointDownloader for FailingDownloader {
- async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
- Ok(vec![self.metadata.get_metadata_filepath()])
- }
-
- async fn download_file(&self, _remote_key: &str) -> Result<Vec<u8>> {
- let json = self.metadata.to_json()?;
- Ok(json.into_bytes())
- }
-
- async fn download_and_store_file_cancellable(
- &self,
- _remote_key: &str,
- _local_filepath: &Path,
- _cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- Err(anyhow::anyhow!("Simulated download failure"))
- }
-
- async fn download_files_cancellable(
- &self,
- _remote_keys: &[String],
- _local_base_path: &Path,
- _cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- Err(anyhow::anyhow!("Simulated download failure"))
- }
-
- async fn is_available(&self) -> bool {
- true
- }
- }
-
- #[tokio::test]
- async fn cleanup_guard_removes_directory_on_failure() {
- let tmp_dir = TempDir::new().unwrap();
- let target_path = tmp_dir.path().join("store");
-
- let attempt_timestamp = Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap();
- let mut metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 12345,
- 0,
- 0,
- );
- metadata.track_file(
- format!("checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2025-06-15T12-00-00Z/000001.sst"),
- "checksum1".to_string(),
- );
-
- let downloader = FailingDownloader::new(metadata);
- let importer = CheckpointImporter::new(
- Box::new(downloader),
- 1, // Only 1 attempt so we fail fast
- Duration::from_secs(60),
- );
-
- let result = importer.import_checkpoint(&target_path).await;
- assert!(result.is_err(), "Import should fail");
-
- assert!(
- !target_path.exists(),
- "Cleanup guard should have removed the store directory on failure"
- );
- }
-
- #[test]
- fn cleanup_guard_defuse_prevents_cleanup() {
- let tmp_dir = TempDir::new().unwrap();
- let test_path = tmp_dir.path().join("test_dir");
- std::fs::create_dir_all(&test_path).unwrap();
- let test_file = test_path.join("test_file.txt");
- std::fs::write(&test_file, b"test content").unwrap();
-
- let guard = DirCleanupGuard::new(test_path.clone());
- let returned_path = guard.defuse();
-
- assert_eq!(returned_path, test_path);
- assert!(test_path.exists(), "Directory should exist after defuse");
- assert!(test_file.exists(), "File should exist after defuse");
- }
-
- #[test]
- fn cleanup_guard_removes_directory_on_drop() {
- let tmp_dir = TempDir::new().unwrap();
- let test_path = tmp_dir.path().join("test_dir");
- std::fs::create_dir_all(&test_path).unwrap();
- let test_file = test_path.join("test_file.txt");
- std::fs::write(&test_file, b"test content").unwrap();
-
- {
- let _guard = DirCleanupGuard::new(test_path.clone());
- }
-
- assert!(
- !test_path.exists(),
- "Directory should be removed after guard drops"
- );
- }
-
- #[derive(Debug)]
- struct TrackingDownloader {
- checkpoints: Vec<CheckpointMetadata>,
- metadata_download_count: Arc<AtomicUsize>,
- file_download_fail_count: usize,
- file_download_attempts: Arc<AtomicUsize>,
- }
-
- impl TrackingDownloader {
- fn new(checkpoints: Vec<CheckpointMetadata>, file_download_fail_count: usize) -> Self {
- Self {
- checkpoints,
- metadata_download_count: Arc::new(AtomicUsize::new(0)),
- file_download_fail_count,
- file_download_attempts: Arc::new(AtomicUsize::new(0)),
- }
- }
- }
-
- #[async_trait]
- impl CheckpointDownloader for TrackingDownloader {
- async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
- Ok(self
- .checkpoints
- .iter()
- .map(CheckpointMetadata::get_metadata_filepath)
- .collect())
- }
-
- async fn download_file(&self, remote_key: &str) -> Result<Vec<u8>> {
- self.metadata_download_count.fetch_add(1, Ordering::SeqCst);
- for checkpoint in &self.checkpoints {
- if checkpoint.get_metadata_filepath() == remote_key {
- return Ok(checkpoint.to_json()?.into_bytes());
- }
- }
- Err(anyhow::anyhow!("Metadata not found: {remote_key}"))
- }
-
- async fn download_and_store_file_cancellable(
- &self,
- _remote_key: &str,
- local_filepath: &Path,
- _cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- tokio::fs::write(local_filepath, b"mock file content").await?;
- Ok(())
- }
-
- async fn download_files_cancellable(
- &self,
- remote_keys: &[String],
- local_base_path: &Path,
- cancel_token: Option<&CancellationToken>,
- ) -> Result<()> {
- let attempt = self.file_download_attempts.fetch_add(1, Ordering::SeqCst);
- if attempt < self.file_download_fail_count {
- return Err(anyhow::anyhow!("Simulated file download failure"));
- }
- for key in remote_keys {
- let filename = key.rsplit('/').next().unwrap_or(key);
- let local_path = local_base_path.join(filename);
- self.download_and_store_file_cancellable(key, &local_path, cancel_token)
- .await?;
- }
- Ok(())
- }
-
- async fn is_available(&self) -> bool {
- true
- }
- }
-
- #[tokio::test]
- async fn lazy_metadata_download_only_fetches_needed() {
- let tmp_dir = TempDir::new().unwrap();
-
- let checkpoints = vec![
- create_test_metadata(14),
- create_test_metadata(13),
- create_test_metadata(12),
- ];
-
- let tracker = TrackingDownloader::new(checkpoints, 0);
- let download_count = Arc::clone(&tracker.metadata_download_count);
-
- let importer = CheckpointImporter::new(Box::new(tracker), 3, Duration::from_secs(60));
-
- let result = importer
- .import_checkpoint(&tmp_dir.path().join("store"))
- .await;
-
- assert!(result.is_ok(), "Import should succeed: {:?}", result.err());
- assert_eq!(
- download_count.load(Ordering::SeqCst),
- 1,
- "Only the newest metadata.json should be downloaded when the first attempt succeeds"
- );
- }
-
- #[tokio::test]
- async fn lazy_metadata_download_fallback_downloads_incrementally() {
- let tmp_dir = TempDir::new().unwrap();
-
- let checkpoints = vec![
- create_test_metadata(14),
- create_test_metadata(13),
- create_test_metadata(12),
- ];
-
- let tracker = TrackingDownloader::new(checkpoints, 2);
- let metadata_count = Arc::clone(&tracker.metadata_download_count);
-
- let importer = CheckpointImporter::new(Box::new(tracker), 3, Duration::from_secs(60));
-
- let result = importer
- .import_checkpoint(&tmp_dir.path().join("store"))
- .await;
-
- assert!(
- result.is_ok(),
- "Import should succeed on 3rd attempt: {:?}",
- result.err()
- );
- assert_eq!(
- metadata_count.load(Ordering::SeqCst),
- 3,
- "Should download exactly 3 metadata files (2 failed attempts + 1 success)"
- );
+ /// Downloads every file the candidate tracks into `stage`, which the caller owns and removes on
+ /// failure.
+ pub async fn fetch_files(
+ &self,
+ metadata: &CheckpointMetadata,
+ stage: &Path,
+ ) -> Result<(), ImportError> {
+ let started = Instant::now();
+ let keys: Vec<String> = metadata
+ .files
+ .iter()
+ .map(|file| file.remote_filepath.clone())
+ .collect();
+ // Without a token, the files left after a failed one would all still download.
+ let siblings = CancellationToken::new();
+ let download = self
+ .downloader
+ .download_files_cancellable(&keys, stage, Some(&siblings));
+ let result = match tokio::time::timeout(self.import_timeout, download).await {
+ Ok(Ok(())) => Ok(()),
+ Ok(Err(err)) => Err(ImportError::Download(err)),
+ Err(_elapsed) => Err(ImportError::Timeout(self.import_timeout)),
+ };
+ let label = if result.is_ok() { "success" } else { "failed" };
+ metrics::histogram!(CHECKPOINT_IMPORT_DURATION_SECONDS, "result" => label)
+ .record(started.elapsed().as_secs_f64());
+ if result.is_ok() {
+ info!(
+ checkpoint = %metadata.id,
+ files = keys.len(),
+ elapsed_secs = started.elapsed().as_secs_f64(),
+ "downloaded checkpoint files into the stage",
+ );
+ }
+ result
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/lineage.rs b/rust/cohort-stream-processor/src/store/durability/lineage.rs
new file mode 100644
index 000000000000..86b34f61c72e
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/lineage.rs
@@ -0,0 +1,128 @@
+//! Which pod a checkpoint belongs to. Every local path and S3 key a checkpoint uses comes from a
+//! [`CheckpointLineage`], so two ordinals never read or write each other's checkpoints.
+
+use std::fmt;
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use super::STORE_TOPIC;
+
+/// The `n` in a StatefulSet pod name `cohort-stream-processor-n`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct PodOrdinal(u16);
+
+#[derive(Debug, thiserror::Error)]
+#[error("pod name {0:?} does not end in a StatefulSet ordinal")]
+pub struct NotAnOrdinalPod(String);
+
+impl PodOrdinal {
+ /// A process outside a StatefulSet, a local run or a test, uses the lineage the single pod
+ /// always used.
+ pub const STANDALONE: Self = Self(0);
+
+ /// Accepts only `<name>-<ascii digits>`, which is the only shape a StatefulSet gives. `u16`'s
+ /// own parser also takes a leading `+`, which would map `x-+5` and `x-5` to one lineage.
+ pub fn from_pod_name(name: &str) -> Result<Self, NotAnOrdinalPod> {
+ name.rsplit_once('-')
+ .map(|(_, digits)| digits)
+ .filter(|digits| !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()))
+ .and_then(|digits| digits.parse().ok())
+ .map(Self)
+ .ok_or_else(|| NotAnOrdinalPod(name.to_owned()))
+ }
+}
+
+impl fmt::Display for PodOrdinal {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.0.fmt(f)
+ }
+}
+
+/// One pod's checkpoint lineage.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CheckpointLineage(PodOrdinal);
+
+impl CheckpointLineage {
+ pub fn new(ordinal: PodOrdinal) -> Self {
+ Self(ordinal)
+ }
+
+ pub fn ordinal(self) -> PodOrdinal {
+ self.0
+ }
+
+ /// `<base>/cohort_stream_state/<ordinal>`.
+ pub fn local_dir(self, base: &Path) -> PathBuf {
+ base.join(STORE_TOPIC).join(self.0.to_string())
+ }
+
+ /// `<hash>/<s3_key_prefix>/cohort_stream_state/<ordinal>/`. The hash spreads lineages across S3
+ /// key partitions. Ordinal 0 keeps the single pod's original layout. The trailing slash keeps a
+ /// sibling namespace from prefix-matching.
+ pub fn remote_dir(self, s3_key_prefix: &str) -> String {
+ let identity = format!("{STORE_TOPIC}/{}", self.0);
+ let hash = Sha256::digest(identity.as_bytes());
+ format!(
+ "{:02x}{:02x}{:02x}{:02x}/{s3_key_prefix}/{identity}/",
+ hash[0], hash[1], hash[2], hash[3]
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_a_statefulset_suffix_parses_to_an_ordinal() {
+ let cases = [
+ ("cohort-stream-processor-0", Some(0)),
+ ("cohort-stream-processor-12", Some(12)),
+ ("cohort-stream-processor-65535", Some(65535)),
+ ("cohort-stream-processor", None),
+ ("cohort-stream-processor-", None),
+ ("cohort-stream-processor-+5", None),
+ ("cohort-stream-processor-65536", None),
+ ("cohort-stream-processor-1a", None),
+ ];
+ for (name, expected) in cases {
+ assert_eq!(
+ PodOrdinal::from_pod_name(name).ok(),
+ expected.map(PodOrdinal),
+ "{name}",
+ );
+ }
+ }
+
+ #[test]
+ fn ordinal_zero_keeps_the_single_pod_layout_and_other_ordinals_get_their_own() {
+ let zero = CheckpointLineage::new(PodOrdinal::STANDALONE);
+ assert_eq!(
+ zero.remote_dir("cohort-stream-checkpoints"),
+ "819f7b67/cohort-stream-checkpoints/cohort_stream_state/0/",
+ );
+ assert_eq!(
+ zero.local_dir(Path::new("/ckpt")),
+ PathBuf::from("/ckpt/cohort_stream_state/0"),
+ );
+
+ let one = CheckpointLineage::new(PodOrdinal(1));
+ let one_remote = one.remote_dir("cohort-stream-checkpoints");
+ assert!(
+ one_remote.ends_with("/cohort-stream-checkpoints/cohort_stream_state/1/"),
+ "{one_remote}",
+ );
+ assert_ne!(
+ one_remote[..8],
+ zero.remote_dir("cohort-stream-checkpoints")[..8]
+ );
+ assert!(!one_remote.starts_with(&zero.remote_dir("cohort-stream-checkpoints")));
+ assert_eq!(
+ one.local_dir(Path::new("/ckpt")),
+ PathBuf::from("/ckpt/cohort_stream_state/1"),
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/manifest.rs b/rust/cohort-stream-processor/src/store/durability/manifest.rs
index 6c9fcc92d770..a347f7303e07 100644
--- a/rust/cohort-stream-processor/src/store/durability/manifest.rs
+++ b/rust/cohort-stream-processor/src/store/durability/manifest.rs
@@ -1,293 +1,286 @@
-//! The multi-partition offset manifest for the disaster-recovery layer.
+//! The offset manifest: for every slice a checkpoint holds, where each input resumes.
//!
-//! A RocksDB `Checkpoint` is a whole-DB snapshot, so one checkpoint freezes every partition's state
-//! at once. On restore the DB content is materialized, but Kafka still needs to know where to resume
-//! each topic-partition. The processor keeps one DB per process spanning up to 64 partitions across
-//! four topics, so the resume positions live here, in a sibling `offsets.json` written alongside the
-//! checkpoint.
+//! A RocksDB `Checkpoint` is a whole-DB snapshot, so one checkpoint freezes every slice at once. On
+//! restore the DB content is materialized, but each input still needs to know where to resume on
+//! each partition. Those positions live in a sibling `offsets.json` written alongside the checkpoint.
//!
-//! [`capture`](OffsetManifest::capture) records [`OffsetTracker::committed_offset`] (the offset Kafka
-//! last acked), not the processed position, which can outrun the fsync'd state under the async WAL.
-//! The committed offset is `<= durable`: the events consumer fsyncs the WAL before every offset
-//! commit, so seeking a restored DB to its committed offset re-folds the gap `[committed, processed]`
-//! idempotently via per-key `AppliedOffsets` — no loss, no double-count.
+//! 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.
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
-use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
-use crate::partitions::OffsetTracker;
+use super::format_version;
+use super::lineage::PodOrdinal;
+use crate::partitions::{InputPositions, InputTopic, 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.
pub const MANIFEST_FILENAME: &str = "offsets.json";
-/// Current on-disk shape version, bumped on any structural change to [`OffsetManifest`]. Decode is
-/// strict: a manifest whose `version` does not match is rejected, so a format skew surfaces as a
-/// restore failure (fall through to S3 / cold-start) instead of a mis-seek.
-pub const MANIFEST_VERSION: u32 = 1;
+/// 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;
-/// The per-process resume positions captured alongside a whole-DB checkpoint: for each topic, the
-/// next offset to consume on each owned partition.
+/// Fields are private: the only constructors are [`Self::capture`] and decoding, and both refuse a
+/// slice that lacks a position on any input.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(try_from = "ManifestWire", into = "ManifestWire")]
pub struct OffsetManifest {
- /// On-disk shape version; see [`MANIFEST_VERSION`].
- pub version: u32,
- /// When this manifest was captured (the checkpoint's logical instant).
- pub captured_at: DateTime<Utc>,
- /// `topic -> { partition -> next-offset-to-consume }`. A `BTreeMap` keeps the serialized JSON
- /// deterministic, so the SHA256 the planner computes over non-SST files stays stable across
- /// captures with identical content.
- pub topics: BTreeMap<String, BTreeMap<i32, i64>>,
+ captured_at: DateTime<Utc>,
+ ordinal: PodOrdinal,
+ inputs: BTreeSet<InputTopic>,
+ slices: BTreeMap<u16, BTreeMap<InputTopic, ResumeOffset>>,
}
-impl OffsetManifest {
- /// Capture the committed positions of every owned partition across the supplied trackers.
- ///
- /// For each `(topic, tracker)` and each partition in `owned`, records
- /// `topics[topic][partition] = committed_offset` only when the tracker has a committed offset for
- /// that partition. A partition the tracker has never seen (an idle follower, or a topic that
- /// never produced to this pod) is absent — inert on restore (nothing to seek).
- pub fn capture(owned: &[i32], trackers: &[(&str, &OffsetTracker)]) -> Self {
- let mut topics: BTreeMap<String, BTreeMap<i32, i64>> = BTreeMap::new();
- for (topic, tracker) in trackers {
- let mut per_partition: BTreeMap<i32, i64> = BTreeMap::new();
- for &partition in owned {
- if let Some(offset) = tracker.committed_offset(partition) {
- per_partition.insert(partition, offset);
- }
+#[derive(Debug, thiserror::Error)]
+pub enum ManifestError {
+ #[error("manifest format {found}; this build reads {MANIFEST_VERSION}")]
+ UnsupportedFormat { found: u32 },
+ #[error("slice {partition} has no position on {topic}")]
+ Incomplete { partition: u16, topic: InputTopic },
+ #[error("the manifest covers no slice")]
+ Empty,
+ #[error(transparent)]
+ Decode(#[from] serde_json::Error),
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+}
+
+/// The JSON shape.
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct ManifestWire {
+ version: u32,
+ captured_at: DateTime<Utc>,
+ ordinal: PodOrdinal,
+ inputs: BTreeSet<InputTopic>,
+ slices: BTreeMap<u16, BTreeMap<InputTopic, ResumeOffset>>,
+}
+
+impl TryFrom<ManifestWire> for OffsetManifest {
+ type Error = ManifestError;
+
+ fn try_from(wire: ManifestWire) -> Result<Self, Self::Error> {
+ if wire.version != MANIFEST_VERSION {
+ return Err(ManifestError::UnsupportedFormat {
+ found: wire.version,
+ });
+ }
+ if wire.slices.is_empty() {
+ return Err(ManifestError::Empty);
+ }
+ for (&partition, positions) in &wire.slices {
+ if let Some(topic) = wire.inputs.iter().find(|t| !positions.contains_key(*t)) {
+ return Err(ManifestError::Incomplete {
+ partition,
+ topic: topic.clone(),
+ });
}
- topics.insert((*topic).to_string(), per_partition);
}
+ Ok(Self {
+ captured_at: wire.captured_at,
+ ordinal: wire.ordinal,
+ inputs: wire.inputs,
+ slices: wire.slices,
+ })
+ }
+}
+
+impl From<OffsetManifest> for ManifestWire {
+ fn from(manifest: OffsetManifest) -> Self {
Self {
version: MANIFEST_VERSION,
- captured_at: Utc::now(),
- topics,
+ captured_at: manifest.captured_at,
+ ordinal: manifest.ordinal,
+ inputs: manifest.inputs,
+ slices: manifest.slices,
}
}
+}
- /// The next-offset-to-consume for one `(topic, partition)`, if present.
- pub fn offset_for(&self, topic: &str, partition: i32) -> Option<i64> {
- self.topics
- .get(topic)
- .and_then(|partitions| partitions.get(&partition).copied())
+impl OffsetManifest {
+ /// Record `positions` for every owned slice. 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>,
+ ) -> Result<Self, ManifestError> {
+ let slices = owned
+ .iter()
+ .map(|&partition| {
+ let offsets = positions
+ .iter()
+ .filter_map(|input| {
+ let offset = input.offsets().get(&partition)?;
+ Some((input.topic().clone(), *offset))
+ })
+ .collect();
+ (partition, offsets)
+ })
+ .collect();
+ ManifestWire {
+ version: MANIFEST_VERSION,
+ captured_at: Utc::now(),
+ ordinal,
+ inputs: positions
+ .iter()
+ .map(|input| input.topic().clone())
+ .collect(),
+ slices,
+ }
+ .try_into()
}
- /// Load the manifest from `<dir>/offsets.json`. Strict-decodes: a missing file, malformed JSON,
- /// or a `version` other than [`MANIFEST_VERSION`] is an error (the caller treats the source as
- /// unusable and falls through).
- pub fn load_from_dir(dir: &Path) -> Result<Self> {
- let path = dir.join(MANIFEST_FILENAME);
- let bytes = std::fs::read(&path)
- .with_context(|| format!("reading offset manifest from {path:?}"))?;
- let manifest: Self = serde_json::from_slice(&bytes)
- .with_context(|| format!("parsing offset manifest from {path:?}"))?;
- if manifest.version != MANIFEST_VERSION {
- anyhow::bail!(
- "offset manifest at {path:?} has version {} but this build expects {MANIFEST_VERSION}",
- manifest.version,
- );
+ pub fn decode(bytes: &[u8]) -> Result<Self, ManifestError> {
+ let version = format_version(bytes)?;
+ if version != MANIFEST_VERSION {
+ return Err(ManifestError::UnsupportedFormat { found: version });
}
- Ok(manifest)
+ serde_json::from_slice::<ManifestWire>(bytes)?.try_into()
+ }
+
+ pub fn load_from_dir(dir: &Path) -> Result<Self, ManifestError> {
+ Self::decode(&std::fs::read(dir.join(MANIFEST_FILENAME))?)
}
- /// Write the manifest to `<dir>/offsets.json` atomically (tmp file + rename) so a concurrent
- /// reader never observes a torn file.
- pub fn write_to_dir(&self, dir: &Path) -> Result<()> {
- let json = serde_json::to_vec_pretty(self).context("serializing offset manifest")?;
- let path = dir.join(MANIFEST_FILENAME);
+ /// Write `<dir>/offsets.json` atomically (tmp file + rename) so a reader never sees a torn file.
+ pub fn write_to_dir(&self, dir: &Path) -> Result<(), ManifestError> {
+ let json = serde_json::to_vec_pretty(self)?;
let tmp_path = dir.join(".offsets.json.tmp");
if let Err(e) = std::fs::write(&tmp_path, &json) {
- // Best-effort cleanup of the partial tmp file before propagating the write error.
drop(std::fs::remove_file(&tmp_path));
- return Err(e).with_context(|| format!("writing temp offset manifest to {tmp_path:?}"));
+ return Err(e.into());
}
- // rename(2) atomically replaces the destination on Unix.
- std::fs::rename(&tmp_path, &path)
- .with_context(|| format!("renaming temp offset manifest to {path:?}"))?;
+ std::fs::rename(&tmp_path, dir.join(MANIFEST_FILENAME))?;
Ok(())
}
+
+ pub fn captured_at(&self) -> DateTime<Utc> {
+ self.captured_at
+ }
+
+ pub fn ordinal(&self) -> PodOrdinal {
+ self.ordinal
+ }
+
+ pub fn inputs(&self) -> &BTreeSet<InputTopic> {
+ &self.inputs
+ }
+
+ /// Where each input resumes on `partition`, or `None` when the checkpoint does not cover it.
+ pub fn slice(&self, partition: u16) -> Option<&BTreeMap<InputTopic, ResumeOffset>> {
+ self.slices.get(&partition)
+ }
}
#[cfg(test)]
mod tests {
use super::*;
- use crate::partitions::MarkOutcome;
+ use serde_json::json;
use tempfile::TempDir;
- fn capture_one(owned: &[i32], topic: &str, tracker: &OffsetTracker) -> OffsetManifest {
- OffsetManifest::capture(owned, &[(topic, tracker)])
+ const EVENTS: &str = "cohort_stream_events";
+ const MERGES: &str = "person_merge_events";
+
+ fn positions(topic: &str, offsets: &[(u16, i64)]) -> InputPositions {
+ InputPositions::new(
+ InputTopic::new(topic),
+ offsets
+ .iter()
+ .map(|&(partition, offset)| (partition, ResumeOffset::try_from(offset).unwrap()))
+ .collect(),
+ )
}
#[test]
- fn manifest_round_trips_through_a_dir() {
+ fn capture_round_trips_and_refuses_an_owned_slice_one_input_lacks() {
+ let owned = BTreeSet::from([0, 3]);
+ let manifest = OffsetManifest::capture(
+ PodOrdinal::STANDALONE,
+ &owned,
+ vec![
+ positions(EVENTS, &[(0, 100), (3, 250)]),
+ positions(MERGES, &[(0, 0), (3, 7)]),
+ ],
+ )
+ .unwrap();
let dir = TempDir::new().unwrap();
- let mut topics = BTreeMap::new();
- topics.insert(
- "cohort_stream_events".to_string(),
- BTreeMap::from([(0, 100), (3, 250)]),
- );
- topics.insert("person_merge_events".to_string(), BTreeMap::from([(0, 7)]));
- let manifest = OffsetManifest {
- version: MANIFEST_VERSION,
- captured_at: Utc::now(),
- topics,
- };
-
manifest.write_to_dir(dir.path()).unwrap();
let loaded = OffsetManifest::load_from_dir(dir.path()).unwrap();
assert_eq!(loaded, manifest);
- assert_eq!(loaded.offset_for("cohort_stream_events", 3), Some(250));
- assert_eq!(loaded.offset_for("cohort_stream_events", 1), None);
- assert_eq!(loaded.offset_for("person_merge_events", 0), Some(7));
- }
-
- #[test]
- fn capture_uses_committed_not_committable() {
- // `capture` must record the committed (durable) offset, not the processed one — recording
- // processed could seek past un-fsynced state on restore and silently skip events.
- let tracker = OffsetTracker::new();
- let partition = 5;
- tracker.mark_dispatched(partition, 1000);
assert_eq!(
- tracker.mark_processed(partition, 1000),
- MarkOutcome::WithinDispatch,
+ loaded.slice(3).unwrap()[&InputTopic::new(MERGES)],
+ ResumeOffset::try_from(7).unwrap(),
);
- tracker.mark_committed(partition, 400);
+ assert_eq!(loaded.slice(1), None);
- let manifest = capture_one(&[partition], "cohort_stream_events", &tracker);
- assert_eq!(
- manifest.offset_for("cohort_stream_events", partition),
- Some(400),
- "capture must record the committed offset (400), not the processed one (1000)",
- );
- }
-
- #[test]
- fn capture_omits_an_absent_follower() {
- let owned = [0, 1, 2];
- let idle = OffsetTracker::new();
- let manifest = capture_one(&owned, "person_merge_events", &idle);
- let inner = manifest
- .topics
- .get("person_merge_events")
- .expect("topic recorded even when empty");
- assert!(
- inner.is_empty(),
- "an idle follower's topic maps to an empty inner map",
- );
- for partition in owned {
- assert_eq!(manifest.offset_for("person_merge_events", partition), None);
- }
- }
-
- #[test]
- fn capture_records_present_follower_offsets() {
- let owned = [3, 7];
- let merge = OffsetTracker::new();
- let transfer = OffsetTracker::new();
- let cascade = OffsetTracker::new();
- for (tracker, base) in [(&merge, 10), (&transfer, 20), (&cascade, 30)] {
- for (partition, bump) in [(3, 1), (7, 2)] {
- let offset = base + bump;
- tracker.mark_dispatched(partition, offset);
- let _ = tracker.mark_processed(partition, offset);
- tracker.mark_committed(partition, offset);
- }
- }
-
- let manifest = OffsetManifest::capture(
+ let err = OffsetManifest::capture(
+ PodOrdinal::STANDALONE,
&owned,
- &[
- ("person_merge_events", &merge),
- ("cohort_merge_state_transfer", &transfer),
- ("cohort_cascade_events", &cascade),
- ],
- );
-
- for (topic, base) in [
- ("person_merge_events", 10),
- ("cohort_merge_state_transfer", 20),
- ("cohort_cascade_events", 30),
- ] {
- let inner = manifest.topics.get(topic).expect("follower topic recorded");
- assert!(!inner.is_empty(), "{topic} follower map must be non-empty");
- assert_eq!(inner.len(), 2, "{topic} records both owned partitions");
- assert_eq!(manifest.offset_for(topic, 3), Some(base + 1));
- assert_eq!(manifest.offset_for(topic, 7), Some(base + 2));
- }
- }
-
- #[test]
- fn capture_records_only_owned_partitions() {
- // Partitions committed in the tracker but not in `owned` must not appear in the manifest.
- let tracker = OffsetTracker::new();
- for partition in [0, 1, 9] {
- tracker.mark_dispatched(partition, 50);
- let _ = tracker.mark_processed(partition, 50);
- tracker.mark_committed(partition, 50);
- }
- let manifest = capture_one(&[0, 1], "cohort_stream_events", &tracker);
- let inner = manifest.topics.get("cohort_stream_events").unwrap();
- assert_eq!(inner.len(), 2);
- assert_eq!(manifest.offset_for("cohort_stream_events", 0), Some(50));
- assert_eq!(manifest.offset_for("cohort_stream_events", 1), Some(50));
- assert_eq!(manifest.offset_for("cohort_stream_events", 9), None);
- }
-
- #[test]
- fn capture_spans_multiple_topics() {
- let events = OffsetTracker::new();
- events.mark_dispatched(0, 100);
- let _ = events.mark_processed(0, 100);
- events.mark_committed(0, 100);
-
- let merges = OffsetTracker::new();
- merges.mark_dispatched(0, 5);
- let _ = merges.mark_processed(0, 5);
- merges.mark_committed(0, 5);
-
- let manifest = OffsetManifest::capture(
- &[0],
- &[
- ("cohort_stream_events", &events),
- ("person_merge_events", &merges),
+ vec![
+ positions(EVENTS, &[(0, 100), (3, 250)]),
+ positions(MERGES, &[(0, 0)]),
],
- );
- assert_eq!(manifest.offset_for("cohort_stream_events", 0), Some(100));
- assert_eq!(manifest.offset_for("person_merge_events", 0), Some(5));
- }
-
- #[test]
- fn a_version_mismatch_fails_to_decode() {
- let dir = TempDir::new().unwrap();
- let json = serde_json::json!({
- "version": MANIFEST_VERSION + 1,
- "captured_at": Utc::now(),
- "topics": { "cohort_stream_events": { "0": 100 } },
- });
- std::fs::write(
- dir.path().join(MANIFEST_FILENAME),
- serde_json::to_vec(&json).unwrap(),
)
- .unwrap();
-
- let err = OffsetManifest::load_from_dir(dir.path()).unwrap_err();
+ .unwrap_err();
assert!(
- err.to_string().contains("version"),
- "version-mismatch error should mention version: {err}",
+ matches!(err, ManifestError::Incomplete { partition: 3, ref topic } if topic.as_str() == MERGES),
+ "{err:?}",
);
+ assert!(matches!(
+ OffsetManifest::capture(
+ PodOrdinal::STANDALONE,
+ &BTreeSet::new(),
+ vec![positions(EVENTS, &[])]
+ ),
+ Err(ManifestError::Empty),
+ ));
}
#[test]
- fn a_missing_manifest_fails_to_load() {
- let dir = TempDir::new().unwrap();
- assert!(
- OffsetManifest::load_from_dir(dir.path()).is_err(),
- "load on a dir with no offsets.json must error",
- );
+ fn decode_refuses_another_format_an_incomplete_slice_a_negative_offset_and_no_slices() {
+ let wire = |version: u32, slices: serde_json::Value| {
+ json!({
+ "version": version,
+ "captured_at": "2026-10-09T16:00:00Z",
+ "ordinal": 0,
+ "inputs": [EVENTS, MERGES],
+ "slices": slices,
+ })
+ .to_string()
+ };
+ let format_one = json!({
+ "version": 1,
+ "captured_at": "2026-10-09T16:00:00Z",
+ "topics": { EVENTS: { "0": 100 } },
+ })
+ .to_string();
+
+ assert!(OffsetManifest::decode(
+ wire(2, json!({ "0": { EVENTS: 1, MERGES: 2 } })).as_bytes()
+ )
+ .is_ok());
+ assert!(matches!(
+ OffsetManifest::decode(format_one.as_bytes()),
+ Err(ManifestError::UnsupportedFormat { found: 1 }),
+ ));
+ assert!(matches!(
+ OffsetManifest::decode(wire(2, json!({ "0": { EVENTS: 1 } })).as_bytes()),
+ Err(ManifestError::Incomplete { partition: 0, .. }),
+ ));
+ assert!(matches!(
+ OffsetManifest::decode(wire(2, json!({ "0": { EVENTS: -1, MERGES: 2 } })).as_bytes()),
+ Err(ManifestError::Decode(_)),
+ ));
+ assert!(matches!(
+ OffsetManifest::decode(wire(2, json!({})).as_bytes()),
+ Err(ManifestError::Empty),
+ ));
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/metadata.rs b/rust/cohort-stream-processor/src/store/durability/metadata.rs
index b67074361eb9..863fa96f5f6b 100644
--- a/rust/cohort-stream-processor/src/store/durability/metadata.rs
+++ b/rust/cohort-stream-processor/src/store/durability/metadata.rs
@@ -1,105 +1,61 @@
//! Checkpoint metadata: the per-attempt file registry, plus S3-key construction.
-//!
-//! `topic`/`partition` are pinned to the fixed store identity (`STORE_TOPIC`/`STORE_PARTITION`); the
-//! offset scalars are written as 0 and never read, since offset positions live in a separate manifest.
-use std::path::{Path, PathBuf};
-use std::sync::OnceLock;
+use std::path::Path;
-use anyhow::{Context, Result};
-use chrono::{DateTime, Utc};
+use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
-use sha2::{Digest, Sha256};
use tracing::debug;
-use super::{STORE_PARTITION, STORE_TOPIC};
+use super::format_version;
+use super::lineage::{CheckpointLineage, PodOrdinal};
use crate::store::STORE_SCHEMA_VERSION;
-/// Deterministic 8-hex-char prefix for spreading S3 object keys across internal partitions.
-/// Applied ONLY to checkpoint object file paths, NEVER to metadata.json paths.
-pub fn hash_prefix_for_partition(topic: &str, partition: i32) -> String {
- let input = format!("{topic}/{partition}");
- let hash = Sha256::digest(input.as_bytes());
- format!(
- "{:02x}{:02x}{:02x}{:02x}",
- hash[0], hash[1], hash[2], hash[3]
- )
-}
-
-/// The single, process-wide S3 hash prefix, derived from the fixed store identity. One DB holds all
-/// partitions, so there is exactly one stable prefix. Computed once and cached.
-pub fn store_hash_prefix() -> &'static str {
- static PREFIX: OnceLock<String> = OnceLock::new();
- PREFIX.get_or_init(|| hash_prefix_for_partition(STORE_TOPIC, STORE_PARTITION))
-}
-
-/// Build the store path `<base_path>/<topic>/<partition>`. Slashes in the topic are replaced with
-/// `_` to guarantee a two-level directory structure.
-fn format_store_path(base_path: &Path, topic: &str, partition: i32) -> PathBuf {
- base_path
- .join(topic.replace('/', "_"))
- .join(partition.to_string())
-}
-
-/// Filename of the checkpoint metadata JSON file. Used in remote checkpoint attempt directories (S3)
-/// and in local store directories (see `write_to_dir` / `load_from_dir`).
+/// Filename of the checkpoint metadata JSON file, in a remote attempt directory and in a local one.
pub const METADATA_FILENAME: &str = "metadata.json";
-/// Hour-scoped prefix format used to filter the S3 listing window.
-pub const DATE_PLUS_HOURS_ONLY_FORMAT: &str = "%Y-%m-%d-%H";
-/// Checkpoint ID format: human-readable S3 path element derived from `attempt_timestamp`.
-pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H-%M-%SZ";
+/// Checkpoint ID format: the S3 attempt directory name, derived from `attempt_timestamp`. It
+/// carries milliseconds, so two checkpoints in one second get two attempt paths.
+pub const TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H-%M-%S-%3fZ";
+/// Current metadata shape. Decode refuses any other, so a restore can tell a checkpoint written by
+/// an older build from a corrupt one.
+pub const METADATA_VERSION: u32 = 2;
+
+#[derive(Debug, thiserror::Error)]
+pub enum MetadataError {
+ /// Metadata written before `version` existed decodes as format 0.
+ #[error("checkpoint metadata format {found}; this build reads {METADATA_VERSION}")]
+ UnsupportedFormat { found: u32 },
+ #[error(transparent)]
+ Decode(#[from] serde_json::Error),
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+}
-/// Metadata about a checkpoint. Can be written to and loaded from a local store directory via
-/// `write_to_dir` / `load_from_dir` (e.g. after import or for round-trip tests).
-#[derive(Debug, Clone, Serialize, Deserialize)]
+/// Metadata about a checkpoint: what a restore must download, and what the next incremental upload
+/// may reuse.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
pub struct CheckpointMetadata {
- /// Checkpoint ID (RFC3339-ish timestamp, e.g., "2025-10-14T16-00-05Z")
+ /// Always [`METADATA_VERSION`] once decoded.
+ pub version: u32,
+ /// Checkpoint ID, e.g. `2025-10-14T16-00-05-123Z`.
pub id: String,
- /// Topic name (fixed to `STORE_TOPIC`).
- pub topic: String,
- /// Partition number (fixed to `STORE_PARTITION`).
- pub partition: i32,
- /// Timestamp of this checkpoint's attempt
+ /// The lineage this checkpoint belongs to.
+ pub ordinal: PodOrdinal,
pub attempt_timestamp: DateTime<Utc>,
- /// RocksDB sequence number at checkpoint time
- pub sequence: u64,
- /// Unused: written as 0 and never read (offsets live in a separate manifest).
- pub consumer_offset: i64,
- /// Unused: written as 0 and never read.
- pub producer_offset: i64,
- /// When this metadata was last written (creation or local write). Serde default when
- /// deserializing metadata.json that lacks this field (backward compat).
- #[serde(default = "Utc::now")]
- pub updated_at: DateTime<Utc>,
- /// The [`STORE_SCHEMA_VERSION`] the checkpointed DB was written under, stamped at construction. A
- /// restore skips a checkpoint whose `store_schema` does not match this binary before downloading
- /// it. `#[serde(default)]` makes pre-versioning metadata.json decode to `0`, which never matches a
- /// real version and is therefore skipped.
- #[serde(default)]
+ /// The [`STORE_SCHEMA_VERSION`] the checkpointed DB was written under. A restore checks it
+ /// before downloading anything.
pub store_schema: u32,
- /// Registry of file metadata for all remotely-stored files required to reconstitute a local
- /// RocksDB store across all relevant checkpoint attempts.
+ /// Every remote file needed to reconstitute the store, across this and earlier attempts.
pub files: Vec<CheckpointFile>,
}
impl CheckpointMetadata {
- pub fn new(
- topic: String,
- partition: i32,
- attempt_timestamp: DateTime<Utc>,
- sequence: u64,
- consumer_offset: i64,
- producer_offset: i64,
- ) -> Self {
+ pub fn new(ordinal: PodOrdinal, attempt_timestamp: DateTime<Utc>) -> Self {
Self {
- id: CheckpointMetadata::generate_id(attempt_timestamp),
- topic,
- partition,
+ version: METADATA_VERSION,
+ id: Self::generate_id(attempt_timestamp),
+ ordinal,
attempt_timestamp,
- sequence,
- consumer_offset,
- producer_offset,
- updated_at: attempt_timestamp,
store_schema: STORE_SCHEMA_VERSION,
files: Vec::new(),
}
@@ -109,37 +65,34 @@ impl CheckpointMetadata {
attempt_timestamp.format(TIMESTAMP_FORMAT).to_string()
}
- pub fn from_json_bytes(json: &[u8]) -> Result<Self> {
- let metadata: Self =
- serde_json::from_slice(json).context("In CheckpointMetadata::from_json")?;
- Ok(metadata)
+ /// The attempt instant a checkpoint id names, or `None` for a name that is not an id.
+ pub fn parse_id(id: &str) -> Option<DateTime<Utc>> {
+ NaiveDateTime::parse_from_str(id, TIMESTAMP_FORMAT)
+ .ok()
+ .map(|naive| naive.and_utc())
}
- pub async fn load_from_dir(dir: &Path) -> Result<Self> {
- let path = dir.join(METADATA_FILENAME);
- let json = tokio::fs::read_to_string(&path)
- .await
- .with_context(|| format!("Failed to read metadata from: {path:?}"))?;
- let metadata: Self = serde_json::from_str(&json)
- .with_context(|| format!("Failed to parse metadata from: {path:?}"))?;
- Ok(metadata)
+ pub fn from_json_bytes(json: &[u8]) -> Result<Self, MetadataError> {
+ let version = format_version(json)?;
+ if version != METADATA_VERSION {
+ return Err(MetadataError::UnsupportedFormat { found: version });
+ }
+ Ok(serde_json::from_slice(json)?)
+ }
+
+ pub fn load(path: &Path) -> Result<Self, MetadataError> {
+ Self::from_json_bytes(&std::fs::read(path)?)
}
- /// Write metadata.json atomically (tmp file + rename) to prevent torn reads.
- pub async fn write_to_dir(&mut self, dir: &Path) -> Result<()> {
- self.updated_at = Utc::now();
- let json = self.to_json().context("In write_to_dir")?;
- let path = dir.join(METADATA_FILENAME);
- let tmp_path = dir.join(".metadata.json.tmp");
- if let Err(e) = tokio::fs::write(&tmp_path, json).await {
- drop(tokio::fs::remove_file(&tmp_path).await);
- return Err(e)
- .with_context(|| format!("Failed to write temp metadata to: {tmp_path:?}"));
+ /// Write atomically (tmp file + rename) so a reader never sees a torn file.
+ pub fn save(&self, path: &Path) -> Result<(), MetadataError> {
+ let tmp_path = path.with_extension("json.tmp");
+ if let Err(e) = std::fs::write(&tmp_path, self.to_json()?) {
+ drop(std::fs::remove_file(&tmp_path));
+ return Err(e.into());
}
- tokio::fs::rename(&tmp_path, &path)
- .await
- .with_context(|| format!("Failed to rename temp metadata to: {path:?}"))?;
- debug!("Saved checkpoint metadata to {:?}", path);
+ std::fs::rename(&tmp_path, path)?;
+ debug!(path = %path.display(), "saved checkpoint metadata");
Ok(())
}
@@ -148,98 +101,52 @@ impl CheckpointMetadata {
.push(CheckpointFile::new(remote_filepath, checksum));
}
- /// Returns `<topic>/<partition>/<checkpoint_id>`, excluding bucket namespace and local base path.
- pub fn get_attempt_path(&self) -> String {
- format!("{}/{}/{}", self.topic, self.partition, self.id)
- }
-
- pub fn get_store_path(&self, local_store_base_path: &Path) -> PathBuf {
- format_store_path(local_store_base_path, &self.topic, self.partition)
- }
-
- pub fn get_metadata_filepath(&self) -> String {
- format!("{}/{}", self.get_attempt_path(), METADATA_FILENAME)
- }
-
- pub fn to_json(&self) -> Result<String> {
- serde_json::to_string_pretty(self).context("Failed to serialize checkpoint metadata")
+ pub fn to_json(&self) -> Result<String, serde_json::Error> {
+ serde_json::to_string_pretty(self)
}
}
+/// A checkpoint's metadata and where its attempt lives in S3.
#[derive(Debug, Clone)]
pub struct CheckpointInfo {
pub metadata: CheckpointMetadata,
/// App-level S3 bucket namespace for all checkpoint attempts.
pub s3_key_prefix: String,
- /// When `Some`, object file keys include this prefix; metadata.json keys never do.
- pub hash_prefix: Option<String>,
}
impl CheckpointInfo {
- pub fn new(
- metadata: CheckpointMetadata,
- s3_key_prefix: String,
- hash_prefix: Option<String>,
- ) -> Self {
+ pub fn new(metadata: CheckpointMetadata, s3_key_prefix: String) -> Self {
Self {
metadata,
s3_key_prefix,
- hash_prefix,
}
}
- pub fn get_metadata_key(&self) -> String {
- match &self.hash_prefix {
- Some(h) => format!(
- "{}/{}/{}",
- h,
- self.s3_key_prefix,
- self.metadata.get_metadata_filepath()
- ),
- None => format!(
- "{}/{}",
- self.s3_key_prefix,
- self.metadata.get_metadata_filepath()
- ),
- }
+ /// `<lineage remote dir><checkpoint id>`.
+ pub fn get_remote_attempt_path(&self) -> String {
+ format!(
+ "{}{}",
+ CheckpointLineage::new(self.metadata.ordinal).remote_dir(&self.s3_key_prefix),
+ self.metadata.id,
+ )
}
- /// Fully-qualified remote path for a file in this attempt (`relative_file_path` is filename only).
- /// Files from prior attempts already carry their full remote path and should not go through this.
- pub fn get_file_key(&self, relative_file_path: &str) -> String {
- match &self.hash_prefix {
- Some(h) => format!(
- "{}/{}/{}/{}",
- h,
- self.s3_key_prefix,
- self.metadata.get_attempt_path(),
- relative_file_path
- ),
- None => format!("{}/{}", self.get_remote_attempt_path(), relative_file_path),
- }
+ pub fn get_metadata_key(&self) -> String {
+ self.get_file_key(METADATA_FILENAME)
}
- pub fn get_remote_attempt_path(&self) -> String {
- match &self.hash_prefix {
- Some(h) => format!(
- "{}/{}/{}",
- h,
- self.s3_key_prefix,
- self.metadata.get_attempt_path(),
- ),
- None => format!(
- "{}/{}",
- self.s3_key_prefix,
- self.metadata.get_attempt_path(),
- ),
- }
+ /// Remote key for a file this attempt uploads. Files reused from earlier attempts keep the key
+ /// they were uploaded under.
+ pub fn get_file_key(&self, filename: &str) -> String {
+ format!("{}/{filename}", self.get_remote_attempt_path())
}
}
-#[derive(Debug, Clone, Serialize, Deserialize)]
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CheckpointFile {
- /// Fully-qualified remote path from the original upload. Object files:
- /// `<hash>/<namespace>/<topic>/<partition>/<id>/<filename>`. The importer GETs using this path.
+ /// Fully-qualified remote path from the original upload:
+ /// `<hash>/<namespace>/cohort_stream_state/<ordinal>/<id>/<filename>`. The importer GETs this
+ /// path.
pub remote_filepath: String,
/// SHA256 of the file contents. Planning compares it against a same-named file from the previous
@@ -260,345 +167,80 @@ impl CheckpointFile {
#[cfg(test)]
mod tests {
use super::*;
+ use chrono::TimeZone;
use tempfile::TempDir;
- #[tokio::test]
- async fn checkpoint_metadata_creation() {
- let attempt_timestamp = Utc::now();
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 1234567890,
- 0,
- 0,
- );
-
- assert_eq!(
- metadata.id,
- CheckpointMetadata::generate_id(attempt_timestamp)
- );
- assert_eq!(metadata.topic, STORE_TOPIC);
- assert_eq!(metadata.partition, STORE_PARTITION);
- assert_eq!(metadata.sequence, 1234567890);
- assert_eq!(metadata.files.len(), 0);
+ fn metadata(ordinal: PodOrdinal) -> CheckpointMetadata {
+ let attempt = Utc.with_ymd_and_hms(2026, 10, 9, 16, 0, 5).unwrap()
+ + chrono::Duration::milliseconds(123);
+ CheckpointMetadata::new(ordinal, attempt)
}
- #[tokio::test]
- async fn write_to_dir_creates_metadata_json_file() {
+ #[test]
+ fn metadata_round_trips_through_a_file() {
let dir = TempDir::new().unwrap();
- let mut metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- Utc::now(),
- 1,
- 0,
- 0,
- );
- metadata.write_to_dir(dir.path()).await.unwrap();
let path = dir.path().join(METADATA_FILENAME);
- assert!(
- path.exists(),
- "write_to_dir should create {METADATA_FILENAME} in dir",
- );
- }
-
- #[tokio::test]
- async fn load_from_dir_fails_when_metadata_missing() {
- let dir = TempDir::new().unwrap();
- let result = CheckpointMetadata::load_from_dir(dir.path()).await;
- assert!(result.is_err(), "load_from_dir on empty dir should fail");
- }
-
- #[tokio::test]
- async fn write_to_dir_and_load_from_dir_round_trip() {
- let dir = TempDir::new().unwrap();
- let bucket_namespace = "checkpoints";
- let attempt_timestamp = Utc::now();
- let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
-
- let mut metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 9876543210,
- 0,
- 0,
- );
- metadata.track_file(
- format!(
- "{}/{}/000001.sst",
- bucket_namespace,
- metadata.get_attempt_path()
- ),
- "checksum1".to_string(),
- );
-
- metadata.write_to_dir(dir.path()).await.unwrap();
+ let mut original = metadata(PodOrdinal::STANDALONE);
+ original.track_file("a/000001.sst".to_string(), String::new());
- let loaded = CheckpointMetadata::load_from_dir(dir.path()).await.unwrap();
-
- assert_eq!(loaded.id, metadata.id);
- assert_eq!(loaded.topic, metadata.topic);
- assert_eq!(loaded.partition, metadata.partition);
- assert_eq!(loaded.attempt_timestamp, metadata.attempt_timestamp);
- assert_eq!(loaded.sequence, metadata.sequence);
- assert_eq!(loaded.files.len(), 1);
- let expected_remote_file_path = format!(
- "{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/000001.sst"
- );
- assert_eq!(loaded.files[0].remote_filepath, expected_remote_file_path);
- assert_eq!(loaded.files[0].checksum, "checksum1");
-
- assert!(
- (loaded.updated_at - Utc::now()).num_seconds().abs() < 2,
- "updated_at should be approximately now after write_to_dir, got {:?}",
- loaded.updated_at
- );
- }
-
- #[test]
- fn updated_at_set_on_creation() {
- let attempt_timestamp = Utc::now();
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 1,
- 0,
- 0,
- );
- assert_eq!(metadata.updated_at, attempt_timestamp);
+ original.save(&path).unwrap();
+ assert_eq!(CheckpointMetadata::load(&path).unwrap(), original);
}
#[test]
- fn updated_at_serde_default() {
- let json = r#"{
- "id": "2025-06-15T12-00-00Z",
+ fn metadata_from_another_format_is_refused_as_a_format_not_as_corruption() {
+ let older = serde_json::json!({
+ "id": "2026-10-09T16-00-05Z",
"topic": "cohort_stream_state",
"partition": 0,
- "attempt_timestamp": "2025-06-15T12:00:00Z",
+ "attempt_timestamp": "2026-10-09T16:00:05Z",
"sequence": 1,
"consumer_offset": 0,
"producer_offset": 0,
- "files": []
- }"#;
- let metadata: CheckpointMetadata =
- serde_json::from_str(json).expect("deserialize without updated_at should succeed");
- assert_eq!(metadata.topic, "cohort_stream_state");
- assert_eq!(metadata.partition, 0);
- assert!(metadata.updated_at.timestamp() > 0);
- assert_eq!(
- metadata.store_schema, 0,
- "metadata without store_schema defaults to 0 (old-era, skipped on restore)",
- );
- }
-
- #[test]
- fn store_schema_is_stamped_on_new_and_round_trips() {
- let mut metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- Utc::now(),
- 1,
- 0,
- 0,
- );
- assert_eq!(
- metadata.store_schema, STORE_SCHEMA_VERSION,
- "a newly-constructed checkpoint is stamped with the current store schema",
- );
- let decoded = CheckpointMetadata::from_json_bytes(metadata.to_json().unwrap().as_bytes())
- .expect("round-trip");
- assert_eq!(decoded.store_schema, STORE_SCHEMA_VERSION);
-
- // A hand-forged older-era value survives decode unchanged (so the restore skip can read it).
- metadata.store_schema = STORE_SCHEMA_VERSION - 1;
- let older = CheckpointMetadata::from_json_bytes(metadata.to_json().unwrap().as_bytes())
- .expect("round-trip");
- assert_eq!(older.store_schema, STORE_SCHEMA_VERSION - 1);
- }
-
- #[test]
- fn get_attempt_path_formats_topic_partition_id() {
- let attempt_timestamp = Utc::now();
- let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
-
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 1234567890,
- 0,
- 0,
- );
-
- let prefix = metadata.get_attempt_path();
- let expected_attempt_path = format!("{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}");
- assert_eq!(prefix, expected_attempt_path);
- }
-
- #[test]
- fn checkpoint_info_keys_without_hash_prefix() {
- let attempt_timestamp = Utc::now();
- let bucket_namespace = "checkpoints";
- let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 1234567890,
- 0,
- 0,
- );
-
- let info = CheckpointInfo::new(metadata, bucket_namespace.to_string(), None);
-
- assert_eq!(
- info.get_metadata_key(),
- format!(
- "{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/{METADATA_FILENAME}"
- )
- );
-
- let local_file_relative_path = "000001.sst";
- assert_eq!(
- info.get_file_key(local_file_relative_path),
- format!(
- "{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/000001.sst"
- )
- );
- }
-
- #[test]
- fn hash_prefix_deterministic() {
- let h1 = hash_prefix_for_partition("events", 0);
- let h2 = hash_prefix_for_partition("events", 0);
- assert_eq!(h1, h2);
- }
-
- #[test]
- fn hash_prefix_different_partitions() {
- let h0 = hash_prefix_for_partition("events", 0);
- let h1 = hash_prefix_for_partition("events", 1);
- let h2 = hash_prefix_for_partition("other-topic", 0);
- assert_ne!(h0, h1);
- assert_ne!(h0, h2);
- assert_ne!(h1, h2);
- }
-
- #[test]
- fn hash_prefix_format() {
- let h = hash_prefix_for_partition("t", 0);
- assert_eq!(h.len(), 8);
- assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
+ "store_schema": STORE_SCHEMA_VERSION,
+ "files": [],
+ });
+ assert!(matches!(
+ CheckpointMetadata::from_json_bytes(older.to_string().as_bytes()),
+ Err(MetadataError::UnsupportedFormat { found: 0 }),
+ ));
+ assert!(matches!(
+ CheckpointMetadata::from_json_bytes(b"{\"version\": 2, \"id\": 5}"),
+ Err(MetadataError::Decode(_)),
+ ));
}
#[test]
- fn store_hash_prefix_is_the_single_db_identity_hash() {
+ fn ids_carry_milliseconds_and_parse_back_to_the_attempt_instant() {
+ let metadata = metadata(PodOrdinal::STANDALONE);
+ assert_eq!(metadata.id, "2026-10-09T16-00-05-123Z");
assert_eq!(
- store_hash_prefix(),
- hash_prefix_for_partition(STORE_TOPIC, STORE_PARTITION)
+ CheckpointMetadata::parse_id(&metadata.id),
+ Some(metadata.attempt_timestamp),
);
+ assert_eq!(CheckpointMetadata::parse_id("2026-10-09T16-00-05Z"), None);
+ assert_eq!(CheckpointMetadata::parse_id("not-an-id"), None);
}
#[test]
- fn checkpoint_info_with_hash_prefix() {
- let attempt_timestamp = Utc::now();
- let bucket_namespace = "checkpoints";
- let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 1234567890,
- 0,
- 0,
- );
- let hash = store_hash_prefix().to_string();
- let info = CheckpointInfo::new(metadata, bucket_namespace.to_string(), Some(hash.clone()));
-
- let meta_key = info.get_metadata_key();
- assert!(meta_key.contains(&hash));
+ fn remote_keys_live_under_the_lineage_of_the_metadata_ordinal() {
+ let zero = CheckpointInfo::new(metadata(PodOrdinal::STANDALONE), "checkpoints".to_string());
assert_eq!(
- meta_key,
- format!(
- "{hash}/{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/{METADATA_FILENAME}"
- )
- );
-
- let file_key = info.get_file_key("000001.sst");
- assert!(file_key.contains(&hash));
- assert_eq!(
- file_key,
- format!(
- "{hash}/{bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/000001.sst"
- )
- );
- }
-
- #[test]
- fn metadata_filepath_format() {
- let attempt_timestamp = Utc::now();
- let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- 1234567890,
- 0,
- 0,
- );
-
- let expected_metadata_filepath =
- format!("{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/{METADATA_FILENAME}");
- assert_eq!(metadata.get_metadata_filepath(), expected_metadata_filepath);
- }
-
- #[test]
- fn generate_id_format() {
- let attempt_timestamp = Utc::now();
- let id = CheckpointMetadata::generate_id(attempt_timestamp);
- let expected_id = attempt_timestamp.format(TIMESTAMP_FORMAT).to_string();
-
- assert!(id.contains('T'));
- assert!(id.ends_with('Z'));
- assert!(id.len() > 15);
- assert_eq!(id, expected_id);
- }
-
- #[test]
- fn get_store_path_nests_topic_and_partition() {
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- Utc::now(),
- 1234567890,
- 0,
- 0,
+ zero.get_metadata_key(),
+ "819f7b67/checkpoints/cohort_stream_state/0/2026-10-09T16-00-05-123Z/metadata.json",
);
-
- let base_path = Path::new("/data/stores");
- let store_path = metadata.get_store_path(base_path);
assert_eq!(
- store_path,
- PathBuf::from(format!("/data/stores/{STORE_TOPIC}/{STORE_PARTITION}"))
+ zero.get_file_key("000001.sst"),
+ "819f7b67/checkpoints/cohort_stream_state/0/2026-10-09T16-00-05-123Z/000001.sst",
);
- }
- #[test]
- fn get_store_path_replaces_slashes_in_topic() {
- let metadata = CheckpointMetadata::new(
- "org/team/events".to_string(),
- 0,
- Utc::now(),
- 1234567890,
- 0,
- 0,
+ let three = CheckpointInfo::new(
+ metadata(PodOrdinal::from_pod_name("p-3").unwrap()),
+ "checkpoints".to_string(),
);
-
- let base_path = Path::new("/data/stores");
- let store_path = metadata.get_store_path(base_path);
- assert_eq!(store_path, PathBuf::from("/data/stores/org_team_events/0"));
+ assert!(three
+ .get_file_key("000001.sst")
+ .ends_with("/checkpoints/cohort_stream_state/3/2026-10-09T16-00-05-123Z/000001.sst"));
+ assert_ne!(three.get_file_key("x")[..8], zero.get_file_key("x")[..8]);
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/mod.rs b/rust/cohort-stream-processor/src/store/durability/mod.rs
index 1a1ae5fcd223..3194859958f8 100644
--- a/rust/cohort-stream-processor/src/store/durability/mod.rs
+++ b/rust/cohort-stream-processor/src/store/durability/mod.rs
@@ -1,14 +1,13 @@
-//! Disaster-recovery durability for the per-process RocksDB state store: a frozen whole-DB
-//! `Checkpoint` plus incremental S3 backup/restore.
+//! Disaster-recovery durability for the per-process RocksDB state store: frozen whole-DB
+//! checkpoints on the local volume, uploaded incrementally to S3, and a boot that restores one
+//! safely when the live store is gone.
//!
-//! ## Single-DB identity
+//! ## One lineage per pod
//!
-//! The processor keeps one DB per process holding all 64 partitions (keys are
-//! `partition_id`-prefixed), so there is exactly one checkpoint lineage per pod. The per-`(topic,
-//! partition)` identity used to key the S3 layout therefore collapses to the two fixed constants
-//! below, yielding one stable S3 prefix for the pod. The identity is fixed rather than configurable:
-//! a stable prefix is all that matters, and freezing it keeps the S3 layout reproducible across
-//! restarts.
+//! The processor keeps one DB per process holding every slice it owns (keys are
+//! `partition_id`-prefixed), so each pod has one checkpoint lineage, named by its StatefulSet
+//! ordinal ([`CheckpointLineage`]). Every local path and S3 key derives from it, so two pods never
+//! read or write each other's checkpoints.
pub mod checkpoint;
pub mod config;
@@ -16,50 +15,59 @@ pub mod downloader;
pub mod error;
pub mod export;
pub mod import;
+pub mod lineage;
pub mod manifest;
pub mod metadata;
pub mod planner;
pub mod recovery;
+pub mod restore_plan;
pub mod s3_client;
pub mod s3_downloader;
pub mod s3_uploader;
+pub mod stage;
pub mod uploader;
-/// The single-DB identity's "topic": a fixed store-id string used only to derive the S3 prefix (the
-/// whole-DB checkpoint is not tied to any one Kafka topic). See the module docs.
+/// The fixed first segment of every lineage's paths. The whole-DB checkpoint is not tied to any one
+/// Kafka topic; the name only has to stay stable, because ordinal 0's S3 hash derives from it.
pub const STORE_TOPIC: &str = "cohort_stream_state";
-/// The single-DB identity's "partition". Always 0: one DB per pod, not one per Kafka partition.
-pub const STORE_PARTITION: i32 = 0;
-pub use checkpoint::{
- should_upload, upload_cadence, CheckpointSweeper, TrackedTopic, CHECKPOINT_LOOP_NAME,
-};
+pub use checkpoint::{upload_cadence, CheckpointSweeper};
pub use config::DurabilityConfig;
pub use downloader::CheckpointDownloader;
pub use export::CheckpointExporter;
pub use import::CheckpointImporter;
-pub use manifest::{OffsetManifest, MANIFEST_FILENAME, MANIFEST_VERSION};
+pub use lineage::{CheckpointLineage, NotAnOrdinalPod, PodOrdinal};
+pub use manifest::{OffsetManifest, MANIFEST_FILENAME};
pub use metadata::{
- hash_prefix_for_partition, store_hash_prefix, CheckpointFile, CheckpointInfo,
- CheckpointMetadata, METADATA_FILENAME,
+ CheckpointFile, CheckpointInfo, CheckpointMetadata, MetadataError, METADATA_FILENAME,
};
pub use planner::{plan_checkpoint, CheckpointPlan, LocalCheckpointFile};
-pub use recovery::{decide_restore_source, run_boot_restore, RestoreOutcome, RestoreSource};
+pub use recovery::open_store;
pub use s3_downloader::S3Downloader;
pub use s3_uploader::S3Uploader;
+pub use stage::{ensure_one_filesystem, FinishError, PendingRestore, MARKER_FILENAME};
pub use uploader::CheckpointUploader;
-pub use error::{
- DownloadCancelledError, ImportTimeoutError, PlanningCancelledError, UploadCancelledError,
-};
+pub use error::{DownloadCancelledError, PlanningCancelledError, UploadCancelledError};
use std::path::PathBuf;
use tracing::{info, warn};
-/// Removes `path` on drop (failure, timeout, cancellation, or panic) unless defused. Shared by both
-/// disaster-restore materializers — the S3 import ([`import`]) and the PVC copy ([`recovery`]) — so a
-/// failed restore never leaves a partial store directory behind. That guarantee is what lets the next
-/// boot's cold-start *outcome* actually start cold rather than reopening a torn store.
+/// The `version` of a checkpoint JSON file, 0 when it has none. Decoding reads it first, so a file
+/// from another build is an unsupported format, which makes its candidate unusable, and not
+/// corruption, which fails the candidate and blocks the boot.
+fn format_version(json: &[u8]) -> serde_json::Result<u32> {
+ #[derive(serde::Deserialize)]
+ struct FormatProbe {
+ #[serde(default)]
+ version: u32,
+ }
+ Ok(serde_json::from_slice::<FormatProbe>(json)?.version)
+}
+
+/// Removes `path` on drop (failure, timeout, cancellation, or panic) unless defused, so a failed
+/// restore leaves no partial staging directory behind. A kill runs no destructor; the next boot
+/// deletes the stage before it decides.
pub(super) struct DirCleanupGuard {
path: PathBuf,
defused: bool,
@@ -86,14 +94,37 @@ impl Drop for DirCleanupGuard {
match std::fs::remove_dir_all(&self.path) {
Ok(_) => info!(
path = %self.path.display(),
- "Dir cleanup guard: removed incomplete store directory"
+ "Dir cleanup guard: removed an incomplete staging directory"
),
Err(e) => warn!(
path = %self.path.display(),
error = ?e,
- "Dir cleanup guard: failed to remove directory, orphan cleaner will handle it"
+ "Dir cleanup guard: failed to remove the directory; the next boot deletes it"
),
}
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ #[test]
+ fn cleanup_guard_removes_the_directory_unless_defused() {
+ let tmp_dir = TempDir::new().unwrap();
+ let kept = tmp_dir.path().join("kept");
+ let dropped = tmp_dir.path().join("dropped");
+ for dir in [&kept, &dropped] {
+ std::fs::create_dir_all(dir).unwrap();
+ std::fs::write(dir.join("000001.sst"), b"sst").unwrap();
+ }
+
+ assert_eq!(DirCleanupGuard::new(kept.clone()).defuse(), kept);
+ drop(DirCleanupGuard::new(dropped.clone()));
+
+ assert!(kept.join("000001.sst").exists());
+ assert!(!dropped.exists());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/planner.rs b/rust/cohort-stream-processor/src/store/durability/planner.rs
index 6ab547832dfd..9fe31c9286f0 100644
--- a/rust/cohort-stream-processor/src/store/durability/planner.rs
+++ b/rust/cohort-stream-processor/src/store/durability/planner.rs
@@ -1,14 +1,10 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
-use super::{
- store_hash_prefix, CheckpointFile, CheckpointInfo, CheckpointMetadata, PlanningCancelledError,
- STORE_PARTITION, STORE_TOPIC,
-};
+use super::{CheckpointFile, CheckpointInfo, CheckpointMetadata, PlanningCancelledError};
use crate::observability::metrics::CHECKPOINT_PLAN_FILES_TOTAL;
use anyhow::{Context, Result};
-use chrono::{DateTime, Utc};
use sha2::{Digest, Sha256};
use tokio_util::sync::CancellationToken;
use tracing::{debug, info};
@@ -19,30 +15,20 @@ pub struct CheckpointPlan {
pub files_to_upload: Vec<LocalCheckpointFile>,
}
-/// Build a checkpoint plan: new metadata plus the files to upload.
+/// Build a checkpoint plan: `metadata` with its files tracked, plus the files to upload.
///
/// Incremental dedup keyed on filename: SST files (immutable) are reused from the previous attempt;
/// mutable files are re-uploaded only on checksum change. The cancellation token, if given, is
/// checked during the directory walk and before hashing non-SST files.
pub fn plan_checkpoint(
local_checkpoint_attempt_dir: &Path,
+ metadata: CheckpointMetadata,
remote_bucket_namespace: String,
- attempt_timestamp: DateTime<Utc>,
- sequence: u64,
previous_metadata: Option<&CheckpointMetadata>,
cancel_token: Option<&CancellationToken>,
) -> Result<CheckpointPlan> {
ensure_not_cancelled(cancel_token, "before planning start")?;
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- attempt_timestamp,
- sequence,
- 0,
- 0,
- );
- let hash = store_hash_prefix().to_string();
- let mut info = CheckpointInfo::new(metadata, remote_bucket_namespace, Some(hash));
+ let mut info = CheckpointInfo::new(metadata, remote_bucket_namespace);
let mut files_to_upload: Vec<LocalCheckpointFile> = Vec::new();
let local_files = collect_local_files(local_checkpoint_attempt_dir, cancel_token)?;
@@ -245,23 +231,35 @@ impl LocalCheckpointFile {
#[cfg(test)]
mod tests {
use super::*;
- use chrono::Duration;
+ use chrono::{DateTime, Duration, Utc};
use tempfile::TempDir;
use tokio_util::sync::CancellationToken;
+ use crate::store::durability::{CheckpointLineage, PodOrdinal};
+
fn attempt_dir(base: &Path, checkpoint_id: &str) -> PathBuf {
- base.join(STORE_TOPIC)
- .join(STORE_PARTITION.to_string())
+ CheckpointLineage::new(PodOrdinal::STANDALONE)
+ .local_dir(base)
.join(checkpoint_id)
}
+ fn metadata_at(attempt_timestamp: DateTime<Utc>) -> CheckpointMetadata {
+ CheckpointMetadata::new(PodOrdinal::STANDALONE, attempt_timestamp)
+ }
+
+ fn remote_attempt_dir(namespace: &str, checkpoint_id: &str) -> String {
+ format!(
+ "{}{checkpoint_id}",
+ CheckpointLineage::new(PodOrdinal::STANDALONE).remote_dir(namespace)
+ )
+ }
+
#[test]
fn plan_checkpoint_no_previous() {
let temp_dir = TempDir::new().unwrap();
let remote_bucket_namespace = "checkpoints";
let attempt_timestamp = Utc::now();
let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let sequence = 1000;
let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
@@ -270,9 +268,8 @@ mod tests {
let plan = plan_checkpoint(
&local_checkpoint_attempt_dir,
+ metadata_at(attempt_timestamp),
remote_bucket_namespace.to_string(),
- attempt_timestamp,
- sequence,
None,
None,
)
@@ -298,10 +295,7 @@ mod tests {
assert_eq!(got_sst2, &expected_sst2);
assert_eq!(plan.info.metadata.files.len(), 2);
- let hash = store_hash_prefix();
- let expected_remote_path = format!(
- "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}"
- );
+ let expected_remote_path = remote_attempt_dir(remote_bucket_namespace, &checkpoint_id);
assert!(plan
.info
.metadata
@@ -320,13 +314,9 @@ mod tests {
.files
.iter()
.any(|f| f.remote_filepath.ends_with("file2.sst")));
- let meta_key = plan.info.get_metadata_key();
- assert!(meta_key.contains(hash));
assert_eq!(
- meta_key,
- format!(
- "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}/metadata.json"
- )
+ plan.info.get_metadata_key(),
+ format!("{expected_remote_path}/metadata.json"),
);
}
@@ -336,16 +326,8 @@ mod tests {
let remote_bucket_namespace = "checkpoints";
let prev_attempt_timestamp = Utc::now() - Duration::hours(1);
let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
- let prev_sequence = 1000;
-
- let mut prev_metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- prev_attempt_timestamp,
- prev_sequence,
- 0,
- 0,
- );
+
+ let mut prev_metadata = metadata_at(prev_attempt_timestamp);
let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
@@ -358,9 +340,8 @@ mod tests {
let expected_prev_sst2 =
build_candidate_file(&prev_local_attempt_dir.join("00002.sst"), None).unwrap();
- let prev_remote_path = format!(
- "{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{prev_checkpoint_id}"
- );
+ let prev_remote_path =
+ format!("{remote_bucket_namespace}/cohort_stream_state/0/{prev_checkpoint_id}");
let prev_sst1_remote_path = format!("{prev_remote_path}/00001.sst");
prev_metadata.track_file(
@@ -376,7 +357,6 @@ mod tests {
let attempt_timestamp = Utc::now();
let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let sequence = 1001;
let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
@@ -388,9 +368,8 @@ mod tests {
let plan = plan_checkpoint(
&local_checkpoint_attempt_dir,
+ metadata_at(attempt_timestamp),
remote_bucket_namespace.to_string(),
- attempt_timestamp,
- sequence,
Some(&prev_metadata),
None,
)
@@ -406,10 +385,8 @@ mod tests {
assert_eq!(plan.info.metadata.files.len(), 3);
- let hash = store_hash_prefix();
- let current_attempt_remote_path = format!(
- "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}"
- );
+ let current_attempt_remote_path =
+ remote_attempt_dir(remote_bucket_namespace, &checkpoint_id);
let sst1_remote_path = format!("{prev_remote_path}/00001.sst");
let sst2_remote_path = format!("{prev_remote_path}/00002.sst");
@@ -450,16 +427,8 @@ mod tests {
let remote_bucket_namespace = "checkpoints";
let prev_attempt_timestamp = Utc::now() - Duration::hours(1);
let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
- let prev_sequence = 1000;
-
- let mut prev_metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- prev_attempt_timestamp,
- prev_sequence,
- 0,
- 0,
- );
+
+ let mut prev_metadata = metadata_at(prev_attempt_timestamp);
let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
@@ -475,9 +444,8 @@ mod tests {
let expected_prev_sst3 =
build_candidate_file(&prev_local_attempt_dir.join("00003.sst"), None).unwrap();
- let prev_remote_path = format!(
- "{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{prev_checkpoint_id}"
- );
+ let prev_remote_path =
+ format!("{remote_bucket_namespace}/cohort_stream_state/0/{prev_checkpoint_id}");
let prev_sst1_remote_path = format!("{prev_remote_path}/00001.sst");
let prev_sst2_remote_path = format!("{prev_remote_path}/00002.sst");
let prev_sst3_remote_path = format!("{prev_remote_path}/00003.sst");
@@ -497,7 +465,6 @@ mod tests {
let attempt_timestamp = Utc::now();
let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let sequence = 1001;
let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
@@ -507,9 +474,8 @@ mod tests {
let plan = plan_checkpoint(
&local_checkpoint_attempt_dir,
+ metadata_at(attempt_timestamp),
remote_bucket_namespace.to_string(),
- attempt_timestamp,
- sequence,
Some(&prev_metadata),
None,
)
@@ -551,16 +517,8 @@ mod tests {
let remote_bucket_namespace = "checkpoints";
let prev_attempt_timestamp = Utc::now() - Duration::hours(1);
let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
- let prev_sequence = 1000;
-
- let mut prev_metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- prev_attempt_timestamp,
- prev_sequence,
- 0,
- 0,
- );
+
+ let mut prev_metadata = metadata_at(prev_attempt_timestamp);
let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
@@ -585,9 +543,8 @@ mod tests {
let expected_prev_log =
build_candidate_file(&prev_local_attempt_dir.join("00001.log"), None).unwrap();
- let prev_remote_path = format!(
- "{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{prev_checkpoint_id}"
- );
+ let prev_remote_path =
+ format!("{remote_bucket_namespace}/cohort_stream_state/0/{prev_checkpoint_id}");
let prev_sst1_remote_path = format!("{prev_remote_path}/00001.sst");
let prev_sst2_remote_path = format!("{prev_remote_path}/00002.sst");
let prev_manifest_remote_path = format!("{prev_remote_path}/MANIFEST-000000");
@@ -622,7 +579,6 @@ mod tests {
let attempt_timestamp = Utc::now();
let checkpoint_id = CheckpointMetadata::generate_id(attempt_timestamp);
- let sequence = 1001;
let local_checkpoint_attempt_dir = attempt_dir(temp_dir.path(), &checkpoint_id);
std::fs::create_dir_all(&local_checkpoint_attempt_dir).unwrap();
@@ -648,9 +604,8 @@ mod tests {
let plan = plan_checkpoint(
&local_checkpoint_attempt_dir,
+ metadata_at(attempt_timestamp),
remote_bucket_namespace.to_string(),
- attempt_timestamp,
- sequence,
Some(&prev_metadata),
None,
)
@@ -670,10 +625,8 @@ mod tests {
assert_eq!(plan.info.metadata.files.len(), 7);
// New files (sst3, CURRENT, log) use the hashed path; retained files keep the previous path.
- let hash = store_hash_prefix();
- let current_attempt_remote_path = format!(
- "{hash}/{remote_bucket_namespace}/{STORE_TOPIC}/{STORE_PARTITION}/{checkpoint_id}"
- );
+ let current_attempt_remote_path =
+ remote_attempt_dir(remote_bucket_namespace, &checkpoint_id);
let sst1_remote_path = format!("{prev_remote_path}/00001.sst");
let sst2_remote_path = format!("{prev_remote_path}/00002.sst");
let sst3_remote_path = format!("{current_attempt_remote_path}/00003.sst");
@@ -741,9 +694,8 @@ mod tests {
let err = plan_checkpoint(
&local_checkpoint_attempt_dir,
+ metadata_at(attempt_timestamp),
"checkpoints".to_string(),
- attempt_timestamp,
- 1000,
None,
Some(&cancel_token),
)
diff --git a/rust/cohort-stream-processor/src/store/durability/recovery.rs b/rust/cohort-stream-processor/src/store/durability/recovery.rs
index 36bab1ed8f4f..fb1d36a35db1 100644
--- a/rust/cohort-stream-processor/src/store/durability/recovery.rs
+++ b/rust/cohort-stream-processor/src/store/durability/recovery.rs
@@ -1,618 +1,1095 @@
-//! Boot-time restore decision + materialization, run **before** `CohortStore::open`.
+//! Boot-time choice of the live store, run before `CohortStore::open`.
//!
-//! The entry point is [`run_boot_restore`] (distinct from the top-level `crate::recovery` cold-start
-//! stub). It decides where the live store should come from and, for the disaster paths, materializes
-//! it at `store_path` so the existing `effective_wipe_on_start` logic then sees `db_dir_exists ==
-//! true` and keeps the restored data.
+//! ## Order
//!
-//! ## Precedence
+//! 1. A leftover staging directory from a killed restore is deleted.
+//! 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.
+//! 4. **Created.** Nothing is restorable: no candidate, or only unusable ones. Every slice then
+//! begins when its worker spawns, behind the coverage fence.
//!
-//! 1. **ReopenLive** — an intact, non-stale live store already sits at `store_path`. A normal restart
-//! with an intact PVC lands here; it needs no manifest, because resume-from-committed
-//! (`Offset::Stored`) is safe under the `committed <= durable` invariant.
-//! 2. **PvcCheckpoint(dir)** — the live store is gone/stale (lost or corrupt PVC) but a recent local
-//! checkpoint with a readable `offsets.json` exists within `checkpoint_local_max_staleness`.
-//! 3. **S3** — no usable local source; restore from the most recent S3 checkpoint.
-//! 4. **ColdStart** — nothing to restore; the wipe+replay path takes over.
-//!
-//! The PVC/S3 branches are **gated behind `checkpoint_enabled`**: with the gate off,
-//! [`decide_restore_source`] returns only `ReopenLive` or `ColdStart`.
+//! A candidate that fails, and any listing or local error, blocks the boot instead of creating the
+//! store: a created store would quietly drop the history the checkpoint holds. The boot retries
+//! until the operator fixes the cause or turns checkpoints off.
+use std::collections::HashSet;
+use std::io;
+use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
-use std::time::Instant;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
-use anyhow::Result;
-use chrono::Utc;
-use tracing::{info, warn};
+use chrono::{DateTime, Utc};
+use metrics::{counter, gauge, histogram};
+use rdkafka::error::KafkaError;
+use tracing::{error, info, warn};
-use super::{
- CheckpointImporter, DirCleanupGuard, OffsetManifest, S3Downloader, MANIFEST_FILENAME,
- METADATA_FILENAME,
+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::stage::{
+ link_checkpoint, staging_path, PendingRestore, RestoredFrom, ResumeError, ValidatedStage,
};
+use super::{DirCleanupGuard, S3Downloader};
use crate::config::Config;
use crate::observability::metrics::{
+ CHECKPOINT_RESTORE_BLOCKED, CHECKPOINT_RESTORE_CANDIDATES_TOTAL,
CHECKPOINT_RESTORE_DURATION_SECONDS, CHECKPOINT_RESTORE_TOTAL,
};
+use crate::partitions::{InputGroups, InputTopic};
+use crate::store::{CohortStore, StoreError, STORE_SCHEMA_VERSION};
+
+const RETRY_START: Duration = Duration::from_secs(30);
+const RETRY_MAX: Duration = Duration::from_secs(300);
+
+/// Where the live store came from.
+#[derive(Debug)]
+enum BootStore {
+ /// The live store reopened. The groups' commits are its positions.
+ Reopened,
+ /// A checkpoint is published at the store path. Nothing folds until the restore finishes.
+ Restored(Box<PendingRestore>),
+ /// No store and nothing usable to restore. Every slice begins when its worker spawns.
+ Created,
+}
+
+#[derive(Debug, thiserror::Error)]
+enum RestoreBlocked {
+ #[error("listing checkpoints failed")]
+ Listing(#[source] anyhow::Error),
+ #[error("no checkpoint candidate restored: {0:?}")]
+ Candidates(Vec<CandidateFailure>),
+ #[error("reading or committing input positions failed")]
+ Positions(#[source] KafkaError),
+ #[error("staging or publishing the restore failed")]
+ Local(#[source] io::Error),
+}
-/// Where the live store should be sourced from on this boot. Resolved by [`decide_restore_source`]
-/// before the store is opened.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum RestoreSource {
- /// Reopen the intact live store already at `store_path`. No materialization, no manifest.
- ReopenLive,
- /// Recursive-copy this local PVC checkpoint dir into `store_path`, then read its `offsets.json`.
- PvcCheckpoint(PathBuf),
- /// Download the most recent S3 checkpoint directly into `store_path`, then read its `offsets.json`.
- S3,
- /// Nothing to restore; fall through to the wipe+replay cold path.
- ColdStart,
+#[derive(Debug)]
+struct CandidateFailure {
+ checkpoint_id: String,
+ reason: String,
}
-impl RestoreSource {
- /// The `source` metric label (`reopen_live` | `pvc` | `s3` | `cold`).
- fn metric_label(&self) -> &'static str {
- match self {
- RestoreSource::ReopenLive => "reopen_live",
- RestoreSource::PvcCheckpoint(_) => "pvc",
- RestoreSource::S3 => "s3",
- RestoreSource::ColdStart => "cold",
+impl CandidateFailure {
+ fn new(checkpoint_id: &str, reason: impl std::fmt::Display) -> Self {
+ Self {
+ checkpoint_id: checkpoint_id.to_owned(),
+ reason: format!("{reason:#}"),
}
}
}
-/// The result of [`run_boot_restore`]: the chosen source plus the offset manifest that the events
-/// consumer seeks to. `manifest` is `None` for the paths with no checkpoint (`ReopenLive`,
-/// `ColdStart`) and `Some` for the disaster paths (`PvcCheckpoint`, `S3`).
#[derive(Debug)]
-pub struct RestoreOutcome {
- pub source: RestoreSource,
- pub manifest: Option<OffsetManifest>,
+enum Verdict {
+ Published(PendingRestore),
+ Unusable(Unusable),
+ Failed(CandidateFailure),
+ /// Its download outlasted the import timeout. Older candidates are about as large, so the
+ /// search stops instead of downloading each of them for as long.
+ TimedOut(CandidateFailure),
}
-/// True when `path` looks like a valid, non-empty RocksDB store: the directory exists and contains a
-/// `CURRENT` file (RocksDB's manifest pointer, present in every opened DB). A bare or partially-wiped
-/// directory without `CURRENT` is treated as absent so reopen-live never resumes from a torn store.
-fn live_store_is_intact(path: &Path) -> bool {
- path.is_dir() && path.join("CURRENT").is_file()
+/// Candidates that no retry can restore. Older candidates are no better, so a search that finds
+/// only these creates the store.
+#[derive(Debug, thiserror::Error)]
+enum Unusable {
+ #[error("its upload never wrote metadata.json")]
+ Unfinished,
+ #[error("store schema {found}, and COHORT_WIPE_ON_SCHEMA_MISMATCH passes over it")]
+ SchemaMismatch { found: u32 },
+ #[error("metadata format {found}")]
+ MetadataFormat { found: u32 },
+ #[error("manifest format {found}")]
+ ManifestFormat { found: u32 },
}
-/// Decide the restore source. Runs before `CohortStore::open`. Touches the filesystem.
-///
-/// `checkpoint_enabled == false` is the inert default: it can only return `ReopenLive` (intact live
-/// store) or `ColdStart` (no live store), never `PvcCheckpoint`/`S3`. When the live store is intact
-/// and not slated for a wipe, reopen-live always wins (it takes precedence even over a fresh PVC
-/// checkpoint).
-pub fn decide_restore_source(config: &Config) -> RestoreSource {
- let store_path = PathBuf::from(&config.store_path);
-
- // `effective_wipe_on_start()` is `false` exactly when durable restore is on and a store exists;
- // paired with an intact on-disk store, that means reopen-live is safe.
- if !config.effective_wipe_on_start() && live_store_is_intact(&store_path) {
- return RestoreSource::ReopenLive;
- }
+/// A candidate whose stage failed validation, so later rounds fail it without downloading it
+/// again. A local attempt and its S3 upload share one id, so the source is part of the key.
+#[derive(Debug, PartialEq, Eq, Hash)]
+enum Rejected {
+ Local(String),
+ S3(String),
+}
- if !config.checkpoint_enabled {
- return RestoreSource::ColdStart;
+impl Rejected {
+ fn of(source: &RestoredFrom) -> Self {
+ match source {
+ RestoredFrom::Local { checkpoint_id } => Self::Local(checkpoint_id.clone()),
+ RestoredFrom::S3 { candidate } => Self::S3(candidate.id.clone()),
+ }
}
+}
- if let Some(dir) = newest_fresh_local_checkpoint(config) {
- return RestoreSource::PvcCheckpoint(dir);
+fn failed(checkpoint_id: &str, reason: impl std::fmt::Display) -> Verdict {
+ Verdict::Failed(CandidateFailure::new(checkpoint_id, reason))
+}
+
+/// The live store's rule: a store of another schema blocks the boot unless the operator allowed
+/// wiping it.
+fn schema_mismatch(checkpoint_id: &str, found: u32, wipe_on_schema_mismatch: bool) -> Verdict {
+ if wipe_on_schema_mismatch {
+ Verdict::Unusable(Unusable::SchemaMismatch { found })
+ } else {
+ failed(
+ checkpoint_id,
+ format_args!(
+ "store schema {found}, this build writes {STORE_SCHEMA_VERSION}; set \
+ COHORT_WIPE_ON_SCHEMA_MISMATCH=true to pass over it"
+ ),
+ )
}
+}
- // Return S3 here; `run_boot_restore` downgrades to cold if no S3 checkpoint is found, keeping
- // the network-free `decide_restore_source` cheap.
- RestoreSource::S3
+/// The failed candidates of one search, newest first.
+#[derive(Debug, Default)]
+struct Search {
+ failed: Vec<CandidateFailure>,
}
-/// Scan `checkpoint_local_dir` for the newest checkpoint attempt directory that (a) carries a
-/// readable `offsets.json` and (b) was captured within `checkpoint_local_max_staleness`. A
-/// manifest-less directory is unusable (we cannot align offsets) and is skipped; a too-old directory
-/// is distrusted (another pod likely advanced the partitions while we were down) and falls through to
-/// S3.
-fn newest_fresh_local_checkpoint(config: &Config) -> Option<PathBuf> {
- let base = PathBuf::from(&config.checkpoint_local_dir);
- let max_staleness = config.checkpoint_local_max_staleness();
- let now = Utc::now();
-
- let mut best: Option<(chrono::DateTime<Utc>, PathBuf)> = None;
- for dir in checkpoint_attempt_dirs(&base) {
- // The manifest is authoritative for the capture instant and is required for the seek; a dir
- // without a readable, version-matching one is unusable.
- let Ok(manifest) = OffsetManifest::load_from_dir(&dir) else {
- continue;
+impl Search {
+ /// Breaks with the restore once a candidate publishes, so no older candidate is downloaded.
+ fn record(&mut self, verdict: Verdict) -> ControlFlow<Box<PendingRestore>> {
+ let label = match &verdict {
+ Verdict::Published(_) => "published",
+ Verdict::Unusable(_) => "unusable",
+ Verdict::Failed(_) | Verdict::TimedOut(_) => "failed",
};
- let age = now.signed_duration_since(manifest.captured_at);
- // A future-dated capture (clock skew) maps to a negative duration, which is treated as 0 → fresh.
- let within_bound = age
- .to_std()
- .map(|elapsed| elapsed <= max_staleness)
- .unwrap_or(true);
- if !within_bound {
- continue;
- }
- match &best {
- Some((best_at, _)) if *best_at >= manifest.captured_at => {}
- _ => best = Some((manifest.captured_at, dir)),
+ counter!(CHECKPOINT_RESTORE_CANDIDATES_TOTAL, "verdict" => label).increment(1);
+ match verdict {
+ Verdict::Published(pending) => ControlFlow::Break(Box::new(pending)),
+ Verdict::Unusable(reason) => {
+ info!(%reason, "passing over an unusable checkpoint");
+ ControlFlow::Continue(())
+ }
+ Verdict::Failed(failure) | Verdict::TimedOut(failure) => {
+ warn!(
+ checkpoint = %failure.checkpoint_id,
+ reason = %failure.reason,
+ "checkpoint candidate failed",
+ );
+ self.failed.push(failure);
+ ControlFlow::Continue(())
+ }
}
}
- best.map(|(_, dir)| dir)
-}
-/// Enumerate candidate checkpoint attempt directories under `base`. A checkpoint attempt dir is the
-/// leaf that holds the RocksDB files + `metadata.json` + `offsets.json`; the planner lays them out as
-/// `<base>/<topic>/<partition>/<checkpoint_id>`, so the candidates are the directories that contain a
-/// `metadata.json`. Walks defensively: any unreadable level yields no candidates rather than erroring.
-fn checkpoint_attempt_dirs(base: &Path) -> Vec<PathBuf> {
- let mut out = Vec::new();
- let mut stack = vec![base.to_path_buf()];
- while let Some(dir) = stack.pop() {
- let Ok(entries) = std::fs::read_dir(&dir) else {
- continue;
- };
- // A dir that directly holds metadata.json is an attempt leaf; otherwise descend.
- if dir.join(METADATA_FILENAME).is_file() {
- out.push(dir);
- continue;
- }
- for entry in entries.flatten() {
- let path = entry.path();
- if path.is_dir() {
- stack.push(path);
- }
+ /// With nothing published, any failure blocks; only unusable candidates, or none at all, create
+ /// the store.
+ fn conclude(self) -> Result<BootStore, RestoreBlocked> {
+ if self.failed.is_empty() {
+ Ok(BootStore::Created)
+ } else {
+ Err(RestoreBlocked::Candidates(self.failed))
}
}
- out
}
-/// Materialize `store_path` from the decided source and return the outcome (source + manifest).
+/// The store this boot runs on: reopened, restored or created, with a restore's unreplayable slices
+/// reset. A restore comes back with it, for the events consumer to finish before anything folds.
///
-/// - `ReopenLive` → no-op (store already in place), `manifest: None`.
-/// - `PvcCheckpoint(dir)` → recursive-copy `dir` into `store_path`, read `offsets.json`.
-/// - `S3` → import the newest S3 checkpoint into `store_path`, read the downloaded `offsets.json`;
-/// if no S3 checkpoint is usable, downgrade to a cold start.
-/// - `ColdStart` → no-op, `manifest: None`.
+/// 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.
+pub async fn open_store(
+ config: &Config,
+ lineage: Option<CheckpointLineage>,
+ groups: Arc<InputGroups>,
+) -> Result<(CohortStore, Option<PendingRestore>), StoreError> {
+ let boot = restore_until_ready(config.clone(), lineage, groups).await;
+
+ // A published restore leaves a store at the path, so `effective_wipe_on_start` keeps it.
+ let store_config = config.store_config();
+ info!(
+ durable_restore_enabled = config.durable_restore_enabled,
+ wipe_store_on_start = config.wipe_store_on_start,
+ effective_wipe = store_config.wipe_on_start,
+ store_path = %config.store_path,
+ mode = if store_config.wipe_on_start { "wipe+replay" } else { "reopen-live" },
+ "opening RocksDB state store",
+ );
+ let store = CohortStore::open(&store_config)?;
+ let restore = match boot {
+ BootStore::Restored(pending) => {
+ pending.reset_slices(&store)?;
+ Some(*pending)
+ }
+ BootStore::Reopened | BootStore::Created => None,
+ };
+ Ok((store, restore))
+}
+
+/// Retries [`prepare_store`] with backoff until the boot has a store, and positions the follower
+/// groups of a restore before returning it.
+///
+/// The restore runs on a blocking thread: staging, validation and the Kafka position calls block,
+/// and the health server must keep answering meanwhile. A SIGTERM here kills the process; staging
+/// survives a kill.
+async fn restore_until_ready(
+ config: Config,
+ lineage: Option<CheckpointLineage>,
+ groups: Arc<InputGroups>,
+) -> BootStore {
+ let runtime = tokio::runtime::Handle::current();
+ let restore = tokio::task::spawn_blocking(move || {
+ runtime.block_on(async {
+ let mut rejected = HashSet::new();
+ // Every round measures the candidate windows up to the first round's start. If the
+ // windows moved, a candidate that failed could leave them between rounds, and a round
+ // that finds nothing creates the store without the history the checkpoint holds.
+ let searched_at = Utc::now();
+ let mut backoff = RETRY_START;
+ loop {
+ let started = Instant::now();
+ let attempt = match prepare_store(&config, lineage, searched_at, &mut rejected).await
+ {
+ Ok((BootStore::Restored(pending), source)) => pending
+ .position_followers(&groups)
+ .map(|()| (BootStore::Restored(pending), source))
+ .map_err(RestoreBlocked::Positions),
+ other => other,
+ };
+ match attempt {
+ Ok((store, source)) => {
+ gauge!(CHECKPOINT_RESTORE_BLOCKED).set(0.0);
+ return prepared(store, source, started);
+ }
+ Err(blocked) => {
+ gauge!(CHECKPOINT_RESTORE_BLOCKED).set(1.0);
+ error!(
+ error = format!("{:#}", anyhow::Error::new(blocked)),
+ retry_in_secs = backoff.as_secs(),
+ "boot restore blocked; fix the cause, or set CHECKPOINT_ENABLED=false to \
+ create the store behind the coverage fence",
+ );
+ tokio::time::sleep(backoff).await;
+ backoff = (backoff * 2).min(RETRY_MAX);
+ }
+ }
+ }
+ })
+ });
+ match restore.await {
+ Ok(store) => store,
+ Err(err) => std::panic::resume_unwind(err.into_panic()),
+ }
+}
+
+/// Decide where the live store comes from, and materialize it for a restore. Returns the store with
+/// its `source` label for `checkpoint_restore_total`. The local staleness window and the S3 listing
+/// window both end at `searched_at`. `rejected` holds the candidates that failed validation after
+/// their download, so a later round fails them without downloading them again.
///
-/// Always emits `CHECKPOINT_RESTORE_TOTAL{source}` + `CHECKPOINT_RESTORE_DURATION_SECONDS` and a
-/// one-line boot summary.
-pub async fn run_boot_restore(config: &Config, store_path: &Path) -> RestoreOutcome {
- let started = Instant::now();
- let decided = decide_restore_source(config);
-
- let outcome = match decided {
- RestoreSource::ReopenLive => RestoreOutcome {
- source: RestoreSource::ReopenLive,
- manifest: None,
- },
- RestoreSource::ColdStart => RestoreOutcome {
- source: RestoreSource::ColdStart,
- manifest: None,
- },
- RestoreSource::PvcCheckpoint(dir) => restore_from_pvc(&dir, store_path),
- RestoreSource::S3 => restore_from_s3(config, store_path).await,
+/// Blocks on file and Kafka I/O; see [`restore_until_ready`].
+async fn prepare_store(
+ config: &Config,
+ lineage: Option<CheckpointLineage>,
+ searched_at: DateTime<Utc>,
+ rejected: &mut HashSet<Rejected>,
+) -> Result<(BootStore, &'static str), RestoreBlocked> {
+ let live = PathBuf::from(&config.store_path);
+ let stage = staging_path(&live);
+ 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()) {
+ Ok(Some(pending)) => return Ok((BootStore::Restored(Box::new(pending)), "pending")),
+ Ok(None) => return Ok((BootStore::Reopened, "reopen_live")),
+ Err(ResumeError::Undecodable(err)) => {
+ warn!(
+ error = %err,
+ store = %live.display(),
+ "the pending restore's marker is unreadable, so its positions are unknown; \
+ deleting the store and restoring again",
+ );
+ // Renamed first, because a deletion cut short could leave `CURRENT` without the
+ // marker, which would reopen at the broker's old offsets. The next boot deletes a
+ // leftover stage.
+ std::fs::rename(&live, &stage).map_err(RestoreBlocked::Local)?;
+ remove_dir_if_present(&stage).map_err(RestoreBlocked::Local)?;
+ }
+ Err(ResumeError::Io(err)) => return Err(RestoreBlocked::Local(err)),
+ }
+ }
+
+ let Some(lineage) = lineage else {
+ return Ok((BootStore::Created, "cold"));
};
+ // A store directory without `CURRENT` is a torn leftover; the rename that publishes a restore
+ // needs the path free.
+ remove_dir_if_present(&live).map_err(RestoreBlocked::Local)?;
- let label = outcome.source.metric_label();
- metrics::counter!(CHECKPOINT_RESTORE_TOTAL, "source" => label).increment(1);
- metrics::histogram!(CHECKPOINT_RESTORE_DURATION_SECONDS)
- .record(started.elapsed().as_secs_f64());
+ let durability = config.durability_config();
+ let local_dir = lineage.local_dir(Path::new(&durability.local_checkpoint_dir));
+ let mut restore = Restore {
+ live: &live,
+ stage,
+ lineage,
+ events_topic: InputTopic::new(&config.cohort_stream_events_topic),
+ partition_count: config.partition_count(),
+ wipe_on_schema_mismatch: config.cohort_wipe_on_schema_mismatch,
+ rejected,
+ };
+ let mut search = Search::default();
+ let local = newest_fresh_local_checkpoint(
+ &local_dir,
+ durability.local_checkpoint_max_staleness,
+ searched_at,
+ );
+ if let Some(attempt) = local {
+ let verdict = match attempt {
+ Ok(attempt) => restore.local(attempt)?,
+ Err(failure) => Verdict::Failed(failure),
+ };
+ if let ControlFlow::Break(pending) = search.record(verdict) {
+ return Ok((BootStore::Restored(pending), "local"));
+ }
+ }
+
+ let downloader = S3Downloader::new(&durability, lineage)
+ .await
+ .map_err(RestoreBlocked::Listing)?;
+ let importer =
+ CheckpointImporter::new(Box::new(downloader), durability.checkpoint_import_timeout);
+ if let ControlFlow::Break(pending) = restore
+ .search_s3(
+ &importer,
+ durability.checkpoint_import_attempt_depth,
+ searched_at,
+ &mut search,
+ )
+ .await?
+ {
+ return Ok((BootStore::Restored(pending), "s3"));
+ }
+ search.conclude().map(|store| (store, "cold"))
+}
+
+fn prepared(store: BootStore, source: &'static str, started: Instant) -> BootStore {
+ counter!(CHECKPOINT_RESTORE_TOTAL, "source" => source).increment(1);
+ histogram!(CHECKPOINT_RESTORE_DURATION_SECONDS).record(started.elapsed().as_secs_f64());
info!(
- source = label,
- store_path = %store_path.display(),
- seek_topics = outcome
- .manifest
- .as_ref()
- .map_or(0, |m| m.topics.len()),
+ source,
elapsed_secs = started.elapsed().as_secs_f64(),
- "boot restore decided",
+ "boot store prepared"
);
+ store
+}
+
+/// A complete local checkpoint attempt: both its manifest and its `metadata.json`, which the
+/// sweeper writes last, decode.
+struct LocalAttempt {
+ dir: PathBuf,
+ manifest: OffsetManifest,
+ metadata: CheckpointMetadata,
+}
- outcome
+/// One round's restore of candidates into the staging directory.
+struct Restore<'a> {
+ live: &'a Path,
+ stage: PathBuf,
+ lineage: CheckpointLineage,
+ events_topic: InputTopic,
+ partition_count: u16,
+ wipe_on_schema_mismatch: bool,
+ rejected: &'a mut HashSet<Rejected>,
}
-/// Recursive-copy a local PVC checkpoint into `store_path`, then read its manifest. On any copy or
-/// manifest failure, downgrade to a cold start (the wipe+replay path is always safe).
-fn restore_from_pvc(checkpoint_dir: &Path, store_path: &Path) -> RestoreOutcome {
- // Remove any partial store before copying so the restored DB is the only content.
- if store_path.exists() {
- if let Err(e) = std::fs::remove_dir_all(store_path) {
- warn!(error = %e, store_path = %store_path.display(), "failed to clear store before PVC restore; cold start");
- return cold_downgrade();
+impl Restore<'_> {
+ fn local(&mut self, attempt: LocalAttempt) -> Result<Verdict, RestoreBlocked> {
+ let LocalAttempt {
+ dir,
+ manifest,
+ metadata,
+ } = attempt;
+ let source = RestoredFrom::Local {
+ checkpoint_id: metadata.id.clone(),
+ };
+ if self.rejected.contains(&Rejected::of(&source)) {
+ return Ok(failed(
+ &metadata.id,
+ "failed validation earlier in this process",
+ ));
+ }
+ if let Some(verdict) = self.admit(&metadata.id, metadata.store_schema, &manifest) {
+ return Ok(verdict);
+ }
+
+ let guard = DirCleanupGuard::new(self.stage.clone());
+ if let Err(err) = link_checkpoint(&dir, &self.stage) {
+ return Ok(failed(
+ &metadata.id,
+ format_args!("linking its files into the stage failed: {err}"),
+ ));
}
+ self.publish(guard, source, manifest)
}
- // `copy_dir_recursive` is non-atomic: a mid-copy failure (disk full, transient I/O) leaves a
- // half-written dir at `store_path`. Without cleanup the next boot would keep it (the wipe is
- // skipped once the dir exists) and `decide_restore_source` would pick ReopenLive over a fresh
- // restore — silently empty if `CURRENT` was missed, crash-looping if its SSTs were. The guard
- // wipes the partial dir on every early return so a cold-start *outcome* actually starts cold.
- //
- // Residual: a SIGKILL *mid-copy* runs no Rust code, so the guard cannot fire; closing that needs
- // a crash-safe copy (temp dir + atomic rename, or copy `CURRENT` last). Deferred follow-up.
- let guard = DirCleanupGuard::new(store_path.to_path_buf());
-
- if let Err(e) = copy_dir_recursive(checkpoint_dir, store_path) {
- warn!(error = %e, from = %checkpoint_dir.display(), "PVC checkpoint copy failed; cold start");
- return cold_downgrade();
+ /// 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.
+ async fn search_s3(
+ &mut self,
+ importer: &CheckpointImporter,
+ depth: usize,
+ searched_at: DateTime<Utc>,
+ search: &mut Search,
+ ) -> Result<ControlFlow<Box<PendingRestore>>, RestoreBlocked> {
+ let candidates = importer
+ .candidates(searched_at)
+ .await
+ .map_err(RestoreBlocked::Listing)?;
+ let mut tried = 0;
+ for metadata_key in &candidates {
+ if tried == depth {
+ break;
+ }
+ let verdict = self.s3(importer, metadata_key).await?;
+ if !matches!(verdict, Verdict::Unusable(Unusable::Unfinished)) {
+ tried += 1;
+ }
+ let timed_out = matches!(verdict, Verdict::TimedOut(_));
+ if let ControlFlow::Break(pending) = search.record(verdict) {
+ return Ok(ControlFlow::Break(pending));
+ }
+ if timed_out {
+ break;
+ }
+ }
+ Ok(ControlFlow::Continue(()))
}
- match OffsetManifest::load_from_dir(store_path) {
- Ok(manifest) => {
- guard.defuse();
- RestoreOutcome {
- source: RestoreSource::PvcCheckpoint(checkpoint_dir.to_path_buf()),
- manifest: Some(manifest),
+
+ async fn s3(
+ &mut self,
+ importer: &CheckpointImporter,
+ metadata_key: &str,
+ ) -> Result<Verdict, RestoreBlocked> {
+ let checkpoint_id = metadata_key.rsplit('/').nth(1).unwrap_or(metadata_key);
+ if self
+ .rejected
+ .contains(&Rejected::S3(checkpoint_id.to_owned()))
+ {
+ return Ok(failed(
+ checkpoint_id,
+ "failed validation earlier in this process",
+ ));
+ }
+ let metadata = match importer.metadata(metadata_key).await {
+ Ok(metadata) => metadata,
+ Err(ImportError::Unfinished) => return Ok(Verdict::Unusable(Unusable::Unfinished)),
+ Err(ImportError::Metadata(MetadataError::UnsupportedFormat { found })) => {
+ return Ok(Verdict::Unusable(Unusable::MetadataFormat { found }))
+ }
+ Err(err) => return Ok(failed(checkpoint_id, err)),
+ };
+ let manifest = match importer.manifest(&metadata).await {
+ Ok(manifest) => manifest,
+ Err(ImportError::Manifest(ManifestError::UnsupportedFormat { found })) => {
+ return Ok(Verdict::Unusable(Unusable::ManifestFormat { found }))
}
+ Err(err) => return Ok(failed(checkpoint_id, err)),
+ };
+ if let Some(verdict) = self.admit(checkpoint_id, metadata.store_schema, &manifest) {
+ return Ok(verdict);
}
- Err(e) => {
- warn!(error = %e, "PVC checkpoint manifest unreadable after copy; cold start");
- cold_downgrade()
+
+ std::fs::create_dir(&self.stage).map_err(RestoreBlocked::Local)?;
+ let guard = DirCleanupGuard::new(self.stage.clone());
+ match importer.fetch_files(&metadata, &self.stage).await {
+ Ok(()) => {}
+ Err(err @ ImportError::Timeout(_)) => {
+ return Ok(Verdict::TimedOut(CandidateFailure::new(checkpoint_id, err)))
+ }
+ Err(err) => return Ok(failed(checkpoint_id, err)),
}
+ self.publish(
+ guard,
+ RestoredFrom::S3 {
+ candidate: metadata,
+ },
+ manifest,
+ )
}
-}
-/// Import the newest usable S3 checkpoint directly into `store_path`, then read the downloaded
-/// manifest. On any failure (no S3 config, no usable checkpoint, unreadable manifest), downgrade to a
-/// cold start.
-async fn restore_from_s3(config: &Config, store_path: &Path) -> RestoreOutcome {
- let durability = config.durability_config();
- let downloader = match S3Downloader::new(&durability).await {
- Ok(downloader) => downloader,
- Err(e) => {
- warn!(error = %e, "S3 downloader unavailable; cold start");
- return cold_downgrade();
+ /// The checks that run before a candidate's bulk download. `Some` is the candidate's verdict.
+ fn admit(
+ &self,
+ checkpoint_id: &str,
+ store_schema: u32,
+ manifest: &OffsetManifest,
+ ) -> Option<Verdict> {
+ if store_schema != STORE_SCHEMA_VERSION {
+ return Some(schema_mismatch(
+ checkpoint_id,
+ store_schema,
+ self.wipe_on_schema_mismatch,
+ ));
}
- };
- let importer = CheckpointImporter::new(
- Box::new(downloader),
- durability.checkpoint_import_attempt_depth,
- durability.checkpoint_import_timeout,
- );
+ if manifest.ordinal() != self.lineage.ordinal() {
+ return 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(
+ checkpoint_id,
+ format_args!("its manifest records no position on {}", self.events_topic),
+ ));
+ }
+ None
+ }
- match importer.import_checkpoint(store_path).await {
- Ok(_imported_path) => match OffsetManifest::load_from_dir(store_path) {
- Ok(manifest) => RestoreOutcome {
- source: RestoreSource::S3,
- manifest: Some(manifest),
- },
- Err(e) => {
- warn!(error = %e, "S3 checkpoint imported but {MANIFEST_FILENAME} unreadable; cold start");
- cold_downgrade()
+ fn publish(
+ &mut self,
+ guard: DirCleanupGuard,
+ source: RestoredFrom,
+ manifest: OffsetManifest,
+ ) -> Result<Verdict, RestoreBlocked> {
+ let checkpoint_id = source.checkpoint_id().to_owned();
+ let rejected = Rejected::of(&source);
+ let staged = match ValidatedStage::validate(self.stage.clone(), source) {
+ Ok(staged) => staged,
+ Err(err) => {
+ self.rejected.insert(rejected);
+ return Ok(failed(&checkpoint_id, err));
}
- },
- Err(e) => {
- warn!(error = %e, "no usable S3 checkpoint to restore; cold start");
- cold_downgrade()
- }
+ };
+ let plan = RestorePlan::check(&manifest, self.partition_count);
+ let pending = staged
+ .publish(manifest, plan, self.live)
+ .map_err(RestoreBlocked::Local)?;
+ guard.defuse();
+ info!(
+ checkpoint = %checkpoint_id,
+ source = pending.source().label(),
+ resets = pending.plan().resets().count(),
+ "checkpoint restore published",
+ );
+ Ok(Verdict::Published(pending))
}
}
-/// A failed disaster-restore path falls back to a cold start: no manifest, wipe+replay takes over.
-fn cold_downgrade() -> RestoreOutcome {
- RestoreOutcome {
- source: RestoreSource::ColdStart,
- manifest: None,
- }
+/// True when `path` is an opened RocksDB store: the directory holds `CURRENT`, RocksDB's manifest
+/// pointer. A directory without it is torn and never reopens.
+fn live_store_is_intact(path: &Path) -> bool {
+ path.is_dir() && path.join("CURRENT").is_file()
}
-/// Recursively copy `from` into `to` (creating `to`).
-fn copy_dir_recursive(from: &Path, to: &Path) -> Result<()> {
- std::fs::create_dir_all(to)?;
- for entry in std::fs::read_dir(from)? {
- let entry = entry?;
- let src = entry.path();
- let dst = to.join(entry.file_name());
- if entry.file_type()?.is_dir() {
- copy_dir_recursive(&src, &dst)?;
- } else {
- std::fs::copy(&src, &dst)?;
+fn remove_dir_if_present(path: &Path) -> io::Result<()> {
+ match std::fs::remove_dir_all(path) {
+ Ok(()) => {
+ info!(path = %path.display(), "removed a leftover directory before choosing the store");
+ Ok(())
}
+ Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(()),
+ Err(err) => Err(err),
}
- Ok(())
+}
+
+/// The newest attempt under `lineage_dir` whose id is within `max_staleness` before `now`. An older
+/// one is distrusted, because the broker has likely moved past what it would replay. An attempt cut
+/// short before its `metadata.json`, or written in a format this build does not read, is passed
+/// over for the one before. Any other unreadable file fails the attempt, and so does a listing error
+/// other than a missing `lineage_dir`, so the boot blocks instead of creating a store without the
+/// history the attempt may hold.
+fn newest_fresh_local_checkpoint(
+ lineage_dir: &Path,
+ max_staleness: Duration,
+ now: DateTime<Utc>,
+) -> Option<Result<LocalAttempt, CandidateFailure>> {
+ let listed = std::fs::read_dir(lineage_dir).and_then(|entries| {
+ entries
+ .map(|entry| Ok(entry?.path()))
+ .collect::<io::Result<Vec<_>>>()
+ });
+ let paths = match listed {
+ Ok(paths) => paths,
+ Err(err) if err.kind() == io::ErrorKind::NotFound => return None,
+ Err(err) => {
+ return Some(Err(CandidateFailure::new(
+ &lineage_dir.to_string_lossy(),
+ format_args!("listing local checkpoints failed: {err}"),
+ )))
+ }
+ };
+ paths
+ .into_iter()
+ .filter(|path| path.is_dir())
+ .filter_map(|dir| {
+ let id = dir.file_name()?.to_str()?.to_owned();
+ let attempted = CheckpointMetadata::parse_id(&id)?;
+ // A future-dated attempt (clock skew) has no positive age and counts as fresh.
+ let fresh = now
+ .signed_duration_since(attempted)
+ .to_std()
+ .map_or(true, |age| age <= max_staleness);
+ if !fresh {
+ return None;
+ }
+ let metadata = match CheckpointMetadata::load(&dir.join(METADATA_FILENAME)) {
+ Ok(metadata) => metadata,
+ Err(MetadataError::Io(err)) if err.kind() == io::ErrorKind::NotFound => {
+ return None
+ }
+ Err(MetadataError::UnsupportedFormat { .. }) => return None,
+ Err(err) => return Some((attempted, Err(CandidateFailure::new(&id, err)))),
+ };
+ let attempt = match OffsetManifest::load_from_dir(&dir) {
+ Ok(manifest) => Ok(LocalAttempt {
+ dir,
+ manifest,
+ metadata,
+ }),
+ Err(ManifestError::UnsupportedFormat { .. }) => return None,
+ Err(err) => Err(CandidateFailure::new(&id, err)),
+ };
+ Some((attempted, attempt))
+ })
+ .max_by_key(|(attempted, _)| *attempted)
+ .map(|(_, attempt)| attempt)
}
#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
mod tests {
use super::*;
- use crate::store::durability::{CheckpointMetadata, STORE_PARTITION, STORE_TOPIC};
- use chrono::Duration as ChronoDuration;
+ use std::collections::{BTreeMap, BTreeSet, HashMap};
+
+ use async_trait::async_trait;
use envconfig::Envconfig;
- use std::collections::BTreeMap;
use tempfile::TempDir;
+ use tokio_util::sync::CancellationToken;
- fn config_with(checkpoint_enabled: bool, store_path: &Path, checkpoint_dir: &Path) -> Config {
- let mut config = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
- config.checkpoint_enabled = checkpoint_enabled;
- // Durable restore must be on for reopen-live to ever beat a wipe (effective_wipe folds it in).
- config.durable_restore_enabled = true;
- config.wipe_store_on_start = true;
- config.store_path = store_path.to_string_lossy().into_owned();
- config.checkpoint_local_dir = checkpoint_dir.to_string_lossy().into_owned();
- config
- }
+ use crate::partitions::{InputPositions, InputTopic, ResumeOffset};
+ use crate::store::durability::lineage::PodOrdinal;
+ use crate::store::durability::stage::MARKER_FILENAME;
+ use crate::store::durability::{CheckpointDownloader, CheckpointInfo};
+ use crate::store::StoreConfig;
- fn make_live_store(path: &Path) {
- std::fs::create_dir_all(path).unwrap();
- std::fs::write(path.join("CURRENT"), b"MANIFEST-000001\n").unwrap();
- }
+ const EVENTS: &str = "cohort_stream_events";
- fn make_local_checkpoint(base: &Path, id: &str, age: ChronoDuration) -> PathBuf {
- let attempt = base
- .join(STORE_TOPIC)
- .join(STORE_PARTITION.to_string())
- .join(id);
- std::fs::create_dir_all(&attempt).unwrap();
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- Utc::now(),
- 1,
- 0,
- 0,
- );
- let json = metadata.to_json().unwrap();
- std::fs::write(attempt.join(METADATA_FILENAME), json).unwrap();
- let mut topics = BTreeMap::new();
- topics.insert(
- "cohort_stream_events".to_string(),
- BTreeMap::from([(0, 42)]),
- );
- let manifest = OffsetManifest {
- version: super::super::manifest::MANIFEST_VERSION,
- captured_at: Utc::now() - age,
- topics,
- };
- manifest.write_to_dir(&attempt).unwrap();
- attempt
+ fn failure() -> Verdict {
+ failed("2026-10-09T16-00-00-000Z", "download failed")
}
#[test]
- fn reopen_live_takes_precedence_over_a_fresh_checkpoint() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
- make_live_store(&store_path);
- make_local_checkpoint(
- &checkpoint_dir,
- "2026-06-17T00-00-00Z",
- ChronoDuration::minutes(1),
- );
+ fn only_unusable_candidates_or_none_create_the_store_and_any_failure_blocks() {
+ let cases: [(&str, Vec<Verdict>, bool); 6] = [
+ ("no candidate", vec![], true),
+ (
+ "only unusable",
+ vec![
+ Verdict::Unusable(Unusable::Unfinished),
+ Verdict::Unusable(Unusable::ManifestFormat { found: 1 }),
+ ],
+ true,
+ ),
+ (
+ "a failure among unusable ones",
+ vec![
+ Verdict::Unusable(Unusable::Unfinished),
+ failure(),
+ Verdict::Unusable(Unusable::MetadataFormat { found: 0 }),
+ ],
+ false,
+ ),
+ ("one failure", vec![failure()], false),
+ (
+ "a schema mismatch the operator lets the boot wipe",
+ vec![schema_mismatch("id", STORE_SCHEMA_VERSION - 1, true)],
+ true,
+ ),
+ (
+ "a schema mismatch without the wipe flag",
+ vec![schema_mismatch("id", STORE_SCHEMA_VERSION - 1, false)],
+ false,
+ ),
+ ];
+ for (name, verdicts, creates) in cases {
+ let mut search = Search::default();
+ for verdict in verdicts {
+ assert!(search.record(verdict).is_continue(), "{name}");
+ }
+ match search.conclude() {
+ Ok(BootStore::Created) => assert!(creates, "{name}"),
+ Err(RestoreBlocked::Candidates(failures)) => {
+ assert!(!creates, "{name}");
+ assert!(!failures.is_empty(), "{name}");
+ }
+ other => panic!("{name}: {other:?}"),
+ }
+ }
+ }
- let config = config_with(true, &store_path, &checkpoint_dir);
- assert_eq!(decide_restore_source(&config), RestoreSource::ReopenLive);
+ struct Boot {
+ root: TempDir,
+ config: Config,
}
- #[test]
- fn pvc_checkpoint_chosen_when_live_store_is_gone() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
- let attempt = make_local_checkpoint(
- &checkpoint_dir,
- "2026-06-17T00-00-00Z",
- ChronoDuration::minutes(5),
- );
+ impl Boot {
+ fn new() -> Self {
+ let root = TempDir::new().unwrap();
+ let mut config = Config::init_from_hashmap(&std::collections::HashMap::new()).unwrap();
+ config.checkpoint_enabled = true;
+ config.durable_restore_enabled = true;
+ config.wipe_store_on_start = true;
+ 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 }
+ }
- let config = config_with(true, &store_path, &checkpoint_dir);
- assert_eq!(
- decide_restore_source(&config),
- RestoreSource::PvcCheckpoint(attempt),
- );
+ fn live(&self) -> PathBuf {
+ PathBuf::from(&self.config.store_path)
+ }
+
+ fn lineage_dir(&self) -> PathBuf {
+ CheckpointLineage::new(PodOrdinal::STANDALONE)
+ .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 {
+ 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());
+ 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();
+ metadata.save(&dir.join(METADATA_FILENAME)).unwrap();
+ metadata
+ }
+
+ fn local_checkpoint(&self) -> CheckpointMetadata {
+ self.checkpoint_attempt(&self.lineage_dir())
+ }
+
+ /// An uploaded checkpoint, listed after a newer attempt whose upload never finished.
+ fn uploaded_checkpoint(&self) -> (FakeS3, String) {
+ let parent = self.root.path().join("uploaded");
+ let mut metadata = self.checkpoint_attempt(&parent);
+ 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);
+ }
+ }
+ metadata.files = info.metadata.files.clone();
+ let metadata_file = parent.join("uploaded-metadata.json");
+ metadata.save(&metadata_file).unwrap();
+ objects.insert(info.get_metadata_key(), metadata_file);
+
+ let unfinished = CheckpointInfo::new(
+ CheckpointMetadata::new(
+ PodOrdinal::STANDALONE,
+ metadata.attempt_timestamp + chrono::Duration::minutes(15),
+ ),
+ "checkpoints".to_string(),
+ );
+ let listing = vec![unfinished.get_metadata_key(), info.get_metadata_key()];
+ let s3 = FakeS3 {
+ listing,
+ objects,
+ stalled: false,
+ };
+ (s3, metadata.id)
+ }
+
+ fn restore<'a>(&'a self, rejected: &'a mut HashSet<Rejected>) -> Restore<'a> {
+ 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),
+ partition_count: 1,
+ wipe_on_schema_mismatch: false,
+ rejected,
+ }
+ }
+
+ async fn prepare(&self) -> Result<BootStore, RestoreBlocked> {
+ prepare_store(
+ &self.config,
+ Some(CheckpointLineage::new(PodOrdinal::STANDALONE)),
+ Utc::now(),
+ &mut HashSet::new(),
+ )
+ .await
+ .map(|(store, _)| store)
+ }
}
- #[test]
- fn the_newest_fresh_checkpoint_is_chosen() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
- let _older = make_local_checkpoint(
- &checkpoint_dir,
- "2026-06-17T00-00-00Z",
- ChronoDuration::minutes(30),
- );
- let newer = make_local_checkpoint(
- &checkpoint_dir,
- "2026-06-17T01-00-00Z",
- ChronoDuration::minutes(2),
- );
+ /// S3 at its boundary: a listing, and objects read from local files. A stalled one never
+ /// finishes a bulk download.
+ #[derive(Debug)]
+ struct FakeS3 {
+ listing: Vec<String>,
+ objects: HashMap<String, PathBuf>,
+ stalled: bool,
+ }
- let config = config_with(true, &store_path, &checkpoint_dir);
- assert_eq!(
- decide_restore_source(&config),
- RestoreSource::PvcCheckpoint(newer),
- );
+ #[async_trait]
+ impl CheckpointDownloader for FakeS3 {
+ async fn list_recent_checkpoints(
+ &self,
+ _now: DateTime<Utc>,
+ ) -> anyhow::Result<Vec<String>> {
+ Ok(self.listing.clone())
+ }
+
+ async fn download_file(&self, remote_key: &str) -> anyhow::Result<Vec<u8>> {
+ match self.objects.get(remote_key) {
+ Some(path) => Ok(std::fs::read(path)?),
+ // Wrapped in context as the real downloader wraps it.
+ None => Err(anyhow::Error::new(object_store::Error::NotFound {
+ path: remote_key.to_owned(),
+ source: "no such key".into(),
+ })
+ .context(format!("Failed to get object: {remote_key}"))),
+ }
+ }
+
+ async fn download_and_store_file_cancellable(
+ &self,
+ remote_key: &str,
+ local_filepath: &Path,
+ _cancel_token: Option<&CancellationToken>,
+ ) -> anyhow::Result<()> {
+ std::fs::write(local_filepath, self.download_file(remote_key).await?)?;
+ Ok(())
+ }
+
+ async fn download_files_cancellable(
+ &self,
+ remote_keys: &[String],
+ local_base_path: &Path,
+ _cancel_token: Option<&CancellationToken>,
+ ) -> anyhow::Result<()> {
+ if self.stalled {
+ std::future::pending::<()>().await;
+ }
+ for key in remote_keys {
+ let name = key.rsplit('/').next().unwrap_or(key);
+ self.download_and_store_file_cancellable(key, &local_base_path.join(name), None)
+ .await?;
+ }
+ Ok(())
+ }
}
- #[test]
- fn a_stale_checkpoint_falls_through_to_s3() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let max_staleness_secs = 7200;
-
- let stale_dir = tmp.path().join("ckpt_stale");
- make_local_checkpoint(
- &stale_dir,
- "2026-06-17T00-00-00Z",
- ChronoDuration::seconds(max_staleness_secs as i64 + 60),
- );
- let mut config = config_with(true, &store_path, &stale_dir);
- config.checkpoint_local_max_staleness_secs = max_staleness_secs;
- assert_eq!(
- decide_restore_source(&config),
- RestoreSource::S3,
- "a checkpoint older than max_staleness must not be trusted",
- );
+ #[tokio::test]
+ async fn an_unfinished_upload_does_not_count_toward_the_depth_and_a_local_rejection_spares_the_s3_copy(
+ ) {
+ let boot = Boot::new();
+ let (s3, checkpoint_id) = boot.uploaded_checkpoint();
+ let importer = CheckpointImporter::new(Box::new(s3), Duration::from_secs(60));
+ let mut rejected = HashSet::from([Rejected::Local(checkpoint_id.clone())]);
+ let mut search = Search::default();
- let fresh_dir = tmp.path().join("ckpt_fresh");
- let fresh = make_local_checkpoint(
- &fresh_dir,
- "2026-06-17T00-30-00Z",
- ChronoDuration::seconds(max_staleness_secs as i64 - 60),
- );
- config.checkpoint_local_dir = fresh_dir.to_string_lossy().into_owned();
- assert_eq!(
- decide_restore_source(&config),
- RestoreSource::PvcCheckpoint(fresh),
- );
+ let outcome = boot
+ .restore(&mut rejected)
+ .search_s3(&importer, 1, Utc::now(), &mut search)
+ .await
+ .unwrap();
+
+ let ControlFlow::Break(pending) = outcome else {
+ panic!("the complete upload behind the unfinished one restores");
+ };
+ assert_eq!(pending.source().label(), "s3");
+ assert_eq!(pending.source().checkpoint_id(), checkpoint_id);
+ assert!(search.failed.is_empty(), "{:?}", search.failed);
}
- #[test]
- fn a_manifest_less_checkpoint_dir_is_skipped() {
- // A dir with metadata.json but no offsets.json cannot align offsets → unusable.
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
- let attempt = checkpoint_dir
- .join(STORE_TOPIC)
- .join(STORE_PARTITION.to_string())
- .join("2026-06-17T00-00-00Z");
- std::fs::create_dir_all(&attempt).unwrap();
- let metadata = CheckpointMetadata::new(
- STORE_TOPIC.to_string(),
- STORE_PARTITION,
- Utc::now(),
- 1,
- 0,
- 0,
- );
- std::fs::write(attempt.join(METADATA_FILENAME), metadata.to_json().unwrap()).unwrap();
- // offsets.json intentionally absent
+ #[tokio::test(start_paused = true)]
+ async fn a_download_timeout_ends_the_search_because_older_candidates_are_as_large() {
+ let boot = Boot::new();
+ let (mut s3, _) = boot.uploaded_checkpoint();
+ let complete = s3.listing[1].clone();
+ s3.listing = vec![complete.clone(), complete];
+ s3.stalled = true;
+ let importer = CheckpointImporter::new(Box::new(s3), Duration::from_secs(60));
+ let mut search = Search::default();
- let config = config_with(true, &store_path, &checkpoint_dir);
- assert_eq!(decide_restore_source(&config), RestoreSource::S3);
+ let outcome = boot
+ .restore(&mut HashSet::new())
+ .search_s3(&importer, 10, Utc::now(), &mut search)
+ .await
+ .unwrap();
+
+ assert!(outcome.is_continue());
+ assert_eq!(search.failed.len(), 1, "{:?}", search.failed);
}
- #[test]
- fn cold_start_when_no_store_no_checkpoint_and_gate_on() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
-
- let config = config_with(true, &store_path, &checkpoint_dir);
- // Gate on but no live store or local checkpoint → S3 (importer downgrades to cold if empty).
- assert_eq!(decide_restore_source(&config), RestoreSource::S3);
+ #[tokio::test]
+ async fn a_leftover_stage_is_deleted_and_an_intact_store_reopens() {
+ let boot = Boot::new();
+ drop(CohortStore::open(&StoreConfig {
+ path: boot.live(),
+ ..StoreConfig::default()
+ }));
+ let stage = staging_path(&boot.live());
+ 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!(!stage.exists());
}
- #[test]
- fn gate_off_never_picks_a_disaster_path() {
- let tmp = TempDir::new().unwrap();
- let checkpoint_dir = tmp.path().join("ckpt");
- make_local_checkpoint(
- &checkpoint_dir,
- "2026-06-17T00-00-00Z",
- ChronoDuration::minutes(1),
- );
+ #[tokio::test]
+ async fn a_local_checkpoint_publishes_and_stays_pending_on_the_next_boot() {
+ let boot = Boot::new();
+ boot.local_checkpoint();
- let absent = tmp.path().join("absent");
- let config_absent = config_with(false, &absent, &checkpoint_dir);
- assert_eq!(
- decide_restore_source(&config_absent),
- RestoreSource::ColdStart
- );
+ let Ok(BootStore::Restored(published)) = boot.prepare().await else {
+ panic!("a fresh local checkpoint restores");
+ };
+ assert_eq!(published.source().label(), "local");
+ assert!(boot.live().join(MARKER_FILENAME).is_file());
- let present = tmp.path().join("present");
- make_live_store(&present);
- let config_present = config_with(false, &present, &checkpoint_dir);
- assert_eq!(
- decide_restore_source(&config_present),
- RestoreSource::ReopenLive
- );
+ let Ok(BootStore::Restored(resumed)) = boot.prepare().await else {
+ panic!("a store with a marker resumes its restore instead of reopening");
+ };
+ assert_eq!(resumed.plan(), published.plan());
}
#[tokio::test]
- async fn run_boot_restore_reopen_live_is_a_noop_with_no_manifest() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
- make_live_store(&store_path);
- let config = config_with(true, &store_path, &checkpoint_dir);
-
- let outcome = run_boot_restore(&config, &store_path).await;
- assert_eq!(outcome.source, RestoreSource::ReopenLive);
- assert!(
- outcome.manifest.is_none(),
- "reopen-live needs no manifest (resume-from-committed)",
- );
- assert!(store_path.join("CURRENT").is_file());
+ async fn an_unreadable_marker_deletes_the_store_and_restores_again() {
+ let boot = Boot::new();
+ boot.local_checkpoint();
+ drop(CohortStore::open(&StoreConfig {
+ path: boot.live(),
+ ..StoreConfig::default()
+ }));
+ std::fs::write(boot.live().join(MARKER_FILENAME), b"{\"version\": 1").unwrap();
+
+ let Ok(BootStore::Restored(pending)) = boot.prepare().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)
+ .unwrap()
+ .expect("the new restore carries a readable marker");
}
#[tokio::test]
- async fn run_boot_restore_copies_a_pvc_checkpoint_into_the_store_path() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- let checkpoint_dir = tmp.path().join("ckpt");
- let attempt = make_local_checkpoint(
- &checkpoint_dir,
- "2026-06-17T00-00-00Z",
- ChronoDuration::minutes(3),
- );
- std::fs::write(attempt.join("000001.sst"), b"sst-bytes").unwrap();
+ async fn the_newest_fresh_local_attempt_restores_and_an_unreadable_one_fails() {
+ let boot = Boot::new();
+ boot.local_checkpoint();
+ let newest = boot.local_checkpoint();
+ let torn = boot.local_checkpoint();
+ std::fs::remove_file(boot.lineage_dir().join(&torn.id).join(METADATA_FILENAME)).unwrap();
- let config = config_with(true, &store_path, &checkpoint_dir);
- let outcome = run_boot_restore(&config, &store_path).await;
+ let Ok(BootStore::Restored(pending)) = boot.prepare().await else {
+ panic!("the newest complete attempt restores");
+ };
+ assert_eq!(pending.source().checkpoint_id(), newest.id);
- assert!(matches!(outcome.source, RestoreSource::PvcCheckpoint(_)));
- let manifest = outcome.manifest.expect("PVC restore yields a manifest");
- assert_eq!(manifest.offset_for("cohort_stream_events", 0), Some(42));
- assert!(store_path.join("000001.sst").is_file());
- assert!(store_path.join(MANIFEST_FILENAME).is_file());
- }
+ let later = Utc::now() + chrono::Duration::hours(2);
+ assert!(
+ newest_fresh_local_checkpoint(&boot.lineage_dir(), Duration::from_secs(3600), later)
+ .is_none(),
+ "an attempt captured before the staleness bound is distrusted",
+ );
- #[test]
- fn restore_from_pvc_wipes_a_partial_store_when_the_copy_fails() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- // A leftover partial store from a prior torn restore that the copy must not preserve.
- std::fs::create_dir_all(&store_path).unwrap();
- std::fs::write(store_path.join("000001.sst"), b"torn").unwrap();
-
- // A non-existent checkpoint dir makes `copy_dir_recursive`'s `read_dir` fail mid-restore.
- let missing = tmp.path().join("nonexistent_checkpoint");
-
- let outcome = restore_from_pvc(&missing, &store_path);
- assert_eq!(outcome.source, RestoreSource::ColdStart);
+ std::fs::write(
+ boot.lineage_dir().join(&newest.id).join(METADATA_FILENAME),
+ b"{\"version\": 2",
+ )
+ .unwrap();
assert!(
- !store_path.exists(),
- "the guard must wipe the partial store so the cold-start outcome actually starts cold",
+ matches!(
+ newest_fresh_local_checkpoint(
+ &boot.lineage_dir(),
+ Duration::from_secs(3600),
+ Utc::now()
+ ),
+ Some(Err(_))
+ ),
+ "a newest attempt that cannot be read fails rather than giving way to an older one",
);
- }
- #[test]
- fn restore_from_pvc_wipes_the_store_when_the_manifest_is_unreadable() {
- let tmp = TempDir::new().unwrap();
- let store_path = tmp.path().join("store");
- // A checkpoint dir that copies cleanly but carries no offsets.json → manifest load fails.
- let checkpoint_dir = tmp.path().join("ckpt");
- std::fs::create_dir_all(&checkpoint_dir).unwrap();
- std::fs::write(checkpoint_dir.join("CURRENT"), b"MANIFEST-000001\n").unwrap();
-
- let outcome = restore_from_pvc(&checkpoint_dir, &store_path);
- assert_eq!(outcome.source, RestoreSource::ColdStart);
+ let not_a_directory = boot.lineage_dir().join(&newest.id).join(METADATA_FILENAME);
assert!(
- !store_path.exists(),
- "an unreadable manifest after copy must leave no partial store behind",
+ matches!(
+ newest_fresh_local_checkpoint(
+ &not_a_directory,
+ Duration::from_secs(3600),
+ Utc::now()
+ ),
+ Some(Err(_))
+ ),
+ "a lineage directory that cannot be listed fails rather than reading as empty",
);
}
#[test]
- fn manifest_is_none_for_reopen_live_and_cold_some_for_disaster_paths() {
- let reopen = RestoreOutcome {
- source: RestoreSource::ReopenLive,
- manifest: None,
- };
- let cold = RestoreOutcome {
- source: RestoreSource::ColdStart,
- manifest: None,
- };
- let pvc = RestoreOutcome {
- source: RestoreSource::PvcCheckpoint(PathBuf::from("/x")),
- manifest: Some(OffsetManifest {
- version: super::super::manifest::MANIFEST_VERSION,
- captured_at: Utc::now(),
- topics: BTreeMap::new(),
+ fn a_local_attempt_that_cannot_restore_fails_and_leaves_the_search_to_s3() {
+ type BreakAttempt = fn(&mut LocalAttempt);
+ let cases: [(&str, BreakAttempt); 2] = [
+ ("its files are gone", |attempt| {
+ std::fs::remove_dir_all(&attempt.dir).unwrap()
}),
- };
- assert!(reopen.manifest.is_none());
- assert!(cold.manifest.is_none());
- assert!(pvc.manifest.is_some());
+ ("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())]),
+ )],
+ )
+ .unwrap()
+ }),
+ ];
+ for (name, break_attempt) in cases {
+ let boot = Boot::new();
+ boot.local_checkpoint();
+ let Some(Ok(mut attempt)) = newest_fresh_local_checkpoint(
+ &boot.lineage_dir(),
+ Duration::from_secs(3600),
+ Utc::now(),
+ ) else {
+ panic!("{name}: the attempt is complete before it breaks");
+ };
+ break_attempt(&mut attempt);
+
+ let verdict = boot.restore(&mut HashSet::new()).local(attempt);
+
+ assert!(
+ matches!(verdict, Ok(Verdict::Failed(_))),
+ "{name}: {verdict:?}"
+ );
+ }
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/restore_plan.rs b/rust/cohort-stream-processor/src/store/durability/restore_plan.rs
new file mode 100644
index 000000000000..132a4b945d25
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/restore_plan.rs
@@ -0,0 +1,148 @@
+//! 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.
+
+use std::collections::BTreeMap;
+
+use super::manifest::OffsetManifest;
+use crate::partitions::{InputTopic, ResumeOffset};
+
+/// What a restore does with one partition's slice.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum SliceRestore {
+ /// Keep the slice and replay each input from its checkpoint position.
+ Resume(BTreeMap<InputTopic, ResumeOffset>),
+ /// Drop the slice so it begins again behind the coverage fence.
+ Reset(ResetReason),
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum ResetReason {
+ NotInCheckpoint,
+}
+
+impl ResetReason {
+ pub fn label(&self) -> &'static str {
+ match self {
+ Self::NotInCheckpoint => "not_in_checkpoint",
+ }
+ }
+}
+
+/// One [`SliceRestore`] per partition of the topic, built only by [`Self::check`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+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(),
+ )
+ }
+
+ pub fn resets(&self) -> impl Iterator<Item = (u16, &ResetReason)> {
+ self.0.iter().filter_map(|(&partition, slice)| match slice {
+ SliceRestore::Reset(reason) => Some((partition, reason)),
+ SliceRestore::Resume(_) => None,
+ })
+ }
+
+ /// Where `topic` resumes on every slice the plan keeps.
+ pub fn positions(&self, topic: &InputTopic) -> BTreeMap<u16, ResumeOffset> {
+ self.0
+ .iter()
+ .filter_map(|(&partition, slice)| match slice {
+ SliceRestore::Resume(positions) => Some((partition, *positions.get(topic)?)),
+ SliceRestore::Reset(_) => None,
+ })
+ .collect()
+ }
+}
+
+#[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";
+
+ fn offset(value: i64) -> ResumeOffset {
+ ResumeOffset::try_from(value).unwrap()
+ }
+
+ fn manifest(slices: &[(u16, &[(&str, i64)])]) -> OffsetManifest {
+ let topics: BTreeSet<&str> = slices
+ .iter()
+ .flat_map(|(_, positions)| positions.iter().map(|(topic, _)| *topic))
+ .collect();
+ let owned = slices.iter().map(|(partition, _)| *partition).collect();
+ let positions = topics
+ .into_iter()
+ .map(|topic| {
+ InputPositions::new(
+ InputTopic::new(topic),
+ slices
+ .iter()
+ .flat_map(|(partition, positions)| {
+ positions
+ .iter()
+ .filter(move |(t, _)| *t == topic)
+ .map(move |&(_, value)| (*partition, offset(value)))
+ })
+ .collect(),
+ )
+ })
+ .collect();
+ OffsetManifest::capture(PodOrdinal::STANDALONE, &owned, positions).unwrap()
+ }
+
+ #[test]
+ fn a_slice_the_manifest_lacks_resets_and_every_other_resumes_from_its_positions() {
+ let recorded = manifest(&[
+ (0, &[(EVENTS, 10), (MERGES, 5)]),
+ (2, &[(EVENTS, 7), (MERGES, 1)]),
+ ]);
+
+ let plan = RestorePlan::check(&recorded, 3);
+
+ assert_eq!(
+ plan.0,
+ BTreeMap::from([
+ (
+ 0,
+ SliceRestore::Resume(BTreeMap::from([
+ (InputTopic::new(EVENTS), offset(10)),
+ (InputTopic::new(MERGES), offset(5)),
+ ])),
+ ),
+ (1, SliceRestore::Reset(ResetReason::NotInCheckpoint)),
+ (
+ 2,
+ SliceRestore::Resume(BTreeMap::from([
+ (InputTopic::new(EVENTS), offset(7)),
+ (InputTopic::new(MERGES), offset(1)),
+ ])),
+ ),
+ ]),
+ );
+ assert_eq!(
+ plan.positions(&InputTopic::new(EVENTS)),
+ BTreeMap::from([(0, offset(10)), (2, offset(7))]),
+ );
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/durability/s3_client.rs b/rust/cohort-stream-processor/src/store/durability/s3_client.rs
index e03fadd2d264..9b197d5ef432 100644
--- a/rust/cohort-stream-processor/src/store/durability/s3_client.rs
+++ b/rust/cohort-stream-processor/src/store/durability/s3_client.rs
@@ -18,13 +18,15 @@ use super::config::DurabilityConfig;
/// Short timeout for bucket validation so misconfiguration fails fast.
const VALIDATION_TIMEOUT: Duration = Duration::from_secs(10);
-/// Build an S3 client wrapped in a `LimitStore` for bounded concurrency.
+/// Build an S3 client wrapped in a `LimitStore` for bounded concurrency, and check that it can list
+/// `lineage_dir`.
///
/// Credential priority: explicit config (local dev) → IRSA (`AWS_WEB_IDENTITY_TOKEN_FILE` +
/// `AWS_ROLE_ARN`) → default AWS credential chain.
pub async fn create_s3_client(
config: &DurabilityConfig,
max_concurrent_requests: usize,
+ lineage_dir: &str,
) -> Result<Arc<LimitStore<AmazonS3>>> {
let mut builder = AmazonS3Builder::from_env()
.with_bucket_name(&config.s3_bucket)
@@ -76,19 +78,22 @@ pub async fn create_s3_client(
let store = Arc::new(LimitStore::new(base_store, max_concurrent_requests));
- validate_bucket_access(&store, &config.s3_bucket, &config.aws_region).await?;
+ validate_bucket_access(&store, &config.s3_bucket, &config.aws_region, lineage_dir).await?;
Ok(store)
}
+/// Lists the lineage's own prefix rather than the bucket root, so the role needs `ListBucket` only
+/// on what the pod reads.
async fn validate_bucket_access(
store: &LimitStore<AmazonS3>,
bucket: &str,
region: &Option<String>,
+ lineage_dir: &str,
) -> Result<()> {
- info!(bucket = %bucket, "Validating S3 bucket access...");
+ info!(bucket = %bucket, prefix = %lineage_dir, "Validating S3 bucket access...");
- let prefix = ObjectPath::from("");
+ let prefix = ObjectPath::from(lineage_dir);
let mut stream = store.list(Some(&prefix));
match tokio::time::timeout(VALIDATION_TIMEOUT, stream.next()).await {
diff --git a/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs b/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs
index b721bd7895a2..bace4467668e 100644
--- a/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs
+++ b/rust/cohort-stream-processor/src/store/durability/s3_downloader.rs
@@ -7,9 +7,9 @@ use tokio_util::bytes::Bytes;
use super::config::DurabilityConfig;
use super::downloader::CheckpointDownloader;
use super::error::DownloadCancelledError;
-use super::metadata::{store_hash_prefix, DATE_PLUS_HOURS_ONLY_FORMAT, METADATA_FILENAME};
+use super::lineage::CheckpointLineage;
+use super::metadata::{CheckpointMetadata, METADATA_FILENAME};
use super::s3_client::create_s3_client;
-use super::{STORE_PARTITION, STORE_TOPIC};
use crate::observability::metrics::{
CHECKPOINT_FILES_DOWNLOADED_TOTAL, CHECKPOINT_FILES_FETCH_DURATION_SECONDS,
CHECKPOINT_FILE_FETCH_DURATION_SECONDS, CHECKPOINT_FILE_FETCH_STORE_DURATION_SECONDS,
@@ -18,7 +18,7 @@ use crate::observability::metrics::{
use anyhow::{Context, Result};
use async_trait::async_trait;
-use chrono::{Duration, Utc};
+use chrono::{DateTime, Duration, Utc};
use futures::stream;
use futures::{StreamExt, TryStreamExt};
use object_store::limit::LimitStore;
@@ -65,14 +65,27 @@ where
}
}
-/// Build the S3 key prefix for listing checkpoints. Includes the deterministic hash prefix so
-/// metadata and object files share a path. The trailing slash makes it a clean folder boundary, so a
-/// sibling namespace under the same hash can never prefix-match.
-fn format_checkpoint_list_prefix(s3_key_prefix: &str) -> String {
- format!(
- "{}/{s3_key_prefix}/{STORE_TOPIC}/{STORE_PARTITION}/",
- store_hash_prefix()
- )
+/// The metadata keys of the attempt folders at or after `now - window`, newest first. Ids are parsed
+/// and compared as instants. A folder whose name is not an attempt id is skipped.
+fn recent_metadata_keys<'a>(
+ folders: impl IntoIterator<Item = &'a str>,
+ now: DateTime<Utc>,
+ window: Duration,
+) -> Vec<String> {
+ let cutoff = now - window;
+ let mut attempts: Vec<(DateTime<Utc>, &str)> = folders
+ .into_iter()
+ .filter_map(|folder| {
+ let id = folder.rsplit('/').find(|segment| !segment.is_empty())?;
+ let attempted_at = CheckpointMetadata::parse_id(id)?;
+ (attempted_at >= cutoff).then_some((attempted_at, folder.trim_end_matches('/')))
+ })
+ .collect();
+ attempts.sort_by(|a, b| b.0.cmp(&a.0));
+ attempts
+ .into_iter()
+ .map(|(_, folder)| format!("{folder}/{METADATA_FILENAME}"))
+ .collect()
}
/// Classify an object_store error into a short, searchable label for structured logging.
@@ -93,15 +106,21 @@ fn s3_error_kind(e: &object_store::Error) -> &'static str {
pub struct S3Downloader {
store: Arc<LimitStore<object_store::aws::AmazonS3>>,
s3_bucket: String,
- s3_key_prefix: String,
+ /// The lineage's remote directory: every attempt this downloader lists lives under it.
+ remote_dir: String,
checkpoint_import_window_hours: u32,
max_concurrent_file_downloads: usize,
}
impl S3Downloader {
- pub async fn new(config: &DurabilityConfig) -> Result<Self> {
- let store =
- create_s3_client(config, config.max_concurrent_checkpoint_file_downloads).await?;
+ pub async fn new(config: &DurabilityConfig, lineage: CheckpointLineage) -> Result<Self> {
+ let remote_dir = lineage.remote_dir(&config.s3_key_prefix);
+ let store = create_s3_client(
+ config,
+ config.max_concurrent_checkpoint_file_downloads,
+ &remote_dir,
+ )
+ .await?;
info!(
"S3 downloader initialized for bucket '{}' with max {} concurrent downloads",
@@ -111,7 +130,7 @@ impl S3Downloader {
Ok(Self {
store,
s3_bucket: config.s3_bucket.clone(),
- s3_key_prefix: config.s3_key_prefix.clone(),
+ remote_dir,
checkpoint_import_window_hours: config.checkpoint_import_window_hours,
max_concurrent_file_downloads: config.max_concurrent_checkpoint_file_downloads,
})
@@ -131,15 +150,22 @@ impl CheckpointDownloader for S3Downloader {
result
}
Err(e) => {
- let error_kind = s3_error_kind(&e);
- error!(
- remote_key,
- bucket = %self.s3_bucket,
- error_kind,
- error = %e,
- "S3 object download failed"
- );
- metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => "error")
+ // An attempt whose upload never finished has no metadata.json, and a restore
+ // expects to meet some, so a missing object is not a download error.
+ let status = if matches!(e, object_store::Error::NotFound { .. }) {
+ info!(remote_key, bucket = %self.s3_bucket, "S3 object not found");
+ "not_found"
+ } else {
+ error!(
+ remote_key,
+ bucket = %self.s3_bucket,
+ error_kind = s3_error_kind(&e),
+ error = %e,
+ "S3 object download failed"
+ );
+ "error"
+ };
+ metrics::counter!(CHECKPOINT_FILES_DOWNLOADED_TOTAL, "status" => status)
.increment(1);
return Err(anyhow::anyhow!(e)).with_context(|| {
format!(
@@ -327,95 +353,63 @@ impl CheckpointDownloader for S3Downloader {
Ok(())
}
- async fn list_recent_checkpoints(&self) -> Result<Vec<String>> {
+ async fn list_recent_checkpoints(&self, now: DateTime<Utc>) -> Result<Vec<String>> {
let start_time = Instant::now();
- let import_window_hours = Duration::hours(i64::from(self.checkpoint_import_window_hours));
- let remote_key_prefix = format_checkpoint_list_prefix(&self.s3_key_prefix);
- let cutoff = Utc::now() - import_window_hours;
- let cutoff_id = cutoff.format(DATE_PLUS_HOURS_ONLY_FORMAT).to_string();
-
- info!(
- "Listing checkpoint folders newer than {cutoff_id} from S3 bucket: {}",
- self.s3_bucket
- );
+ let window = Duration::hours(i64::from(self.checkpoint_import_window_hours));
// Shallow list (delimiter="/"): returns only the common prefixes (checkpoint folders).
- let prefix = ObjectPath::from(remote_key_prefix.as_str());
+ let prefix = ObjectPath::from(self.remote_dir.as_str());
let result = self
.store
.list_with_delimiter(Some(&prefix))
.await
.context("listing checkpoint folders from S3")?;
+ let metadata_keys = recent_metadata_keys(
+ result.common_prefixes.iter().map(|folder| folder.as_ref()),
+ now,
+ window,
+ );
- // Keep folders at or after the cutoff and map them to their metadata.json keys.
- let mut metadata_keys: Vec<String> = result
- .common_prefixes
- .into_iter()
- .filter(|cp| {
- let path_str = cp.as_ref();
- let checkpoint_id = path_str.rsplit('/').find(|s| !s.is_empty()).unwrap_or("");
- checkpoint_id >= cutoff_id.as_str()
- })
- .map(|cp| format!("{}/{}", cp.as_ref(), METADATA_FILENAME))
- .collect();
-
- // Checkpoint IDs are timestamps, so reverse lexicographic order = newest first.
- metadata_keys.sort_unstable();
- metadata_keys.reverse();
-
- let elapsed = start_time.elapsed();
- metrics::histogram!(CHECKPOINT_LIST_DURATION_SECONDS).record(elapsed.as_secs_f64());
+ metrics::histogram!(CHECKPOINT_LIST_DURATION_SECONDS)
+ .record(start_time.elapsed().as_secs_f64());
info!(
- "Found {} checkpoint folders at or after {cutoff_id}",
- metadata_keys.len(),
+ bucket = %self.s3_bucket,
+ prefix = %self.remote_dir,
+ window_hours = self.checkpoint_import_window_hours,
+ candidates = metadata_keys.len(),
+ "listed checkpoint attempts",
);
Ok(metadata_keys)
}
-
- async fn is_available(&self) -> bool {
- !self.s3_bucket.is_empty()
- }
}
#[cfg(test)]
mod tests {
use super::*;
+ use chrono::TimeZone;
#[test]
- fn format_checkpoint_list_prefix_uses_the_single_db_identity() {
- let hash = store_hash_prefix();
- let prefix = format_checkpoint_list_prefix("checkpoints");
- assert_eq!(
- prefix,
- format!("{hash}/checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/")
- );
- }
+ fn the_listing_keeps_attempts_inside_the_window_newest_first() {
+ let dir = "819f7b67/checkpoints/cohort_stream_state/0";
+ let folders = [
+ format!("{dir}/2026-10-09T01-00-00-000Z"),
+ format!("{dir}/2026-10-09T05-00-00-000Z"),
+ format!("{dir}/2026-10-09T03-00-00-000Z"),
+ format!("{dir}/2026-10-09T15-30-00-250Z"),
+ format!("{dir}/scratch"),
+ ];
+ let now = Utc.with_ymd_and_hms(2026, 10, 9, 16, 0, 0).unwrap();
+
+ let keys =
+ recent_metadata_keys(folders.iter().map(String::as_str), now, Duration::hours(12));
- #[test]
- fn format_checkpoint_list_prefix_has_a_trailing_slash_folder_boundary() {
- let prefix = format_checkpoint_list_prefix("checkpoints");
- assert!(prefix.ends_with('/'));
-
- let hash = store_hash_prefix();
- // A real key under this prefix matches; a key with a longer trailing namespace does not.
- let key = format!(
- "{hash}/checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/2026-01-22T12-00-00Z/metadata.json"
- );
- let sibling = format!(
- "{hash}/checkpoints-other/{STORE_TOPIC}/{STORE_PARTITION}/2026-01-22T12-00-00Z/metadata.json"
- );
- assert!(key.starts_with(&prefix));
- assert!(!sibling.starts_with(&prefix));
- }
-
- #[test]
- fn format_checkpoint_list_prefix_with_namespaced_key_prefix() {
- let hash = store_hash_prefix();
- let prefix = format_checkpoint_list_prefix("env/prod/checkpoints");
assert_eq!(
- prefix,
- format!("{hash}/env/prod/checkpoints/{STORE_TOPIC}/{STORE_PARTITION}/")
+ keys,
+ [
+ format!("{dir}/2026-10-09T15-30-00-250Z/metadata.json"),
+ format!("{dir}/2026-10-09T05-00-00-000Z/metadata.json"),
+ ],
);
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs b/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
index 1ea99f70c77d..0173ee5062f9 100644
--- a/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
+++ b/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
@@ -14,6 +14,7 @@ use tracing::{info, warn};
use super::config::DurabilityConfig;
use super::error::UploadCancelledError;
+use super::lineage::CheckpointLineage;
use super::s3_client::create_s3_client;
use super::uploader::CheckpointUploader;
use crate::observability::metrics::CHECKPOINT_FILES_UPLOADED_TOTAL;
@@ -62,9 +63,13 @@ pub struct S3Uploader {
}
impl S3Uploader {
- pub async fn new(config: DurabilityConfig) -> Result<Self> {
- let store =
- create_s3_client(&config, config.max_concurrent_checkpoint_file_uploads).await?;
+ pub async fn new(config: DurabilityConfig, lineage: CheckpointLineage) -> Result<Self> {
+ let store = create_s3_client(
+ &config,
+ config.max_concurrent_checkpoint_file_uploads,
+ &lineage.remote_dir(&config.s3_key_prefix),
+ )
+ .await?;
info!(
"S3 uploader initialized for bucket '{}' with max {} concurrent uploads",
diff --git a/rust/cohort-stream-processor/src/store/durability/stage.rs b/rust/cohort-stream-processor/src/store/durability/stage.rs
new file mode 100644
index 000000000000..c073c7154cdc
--- /dev/null
+++ b/rust/cohort-stream-processor/src/store/durability/stage.rs
@@ -0,0 +1,426 @@
+//! A checkpoint restore in two moves, each safe against a kill.
+//!
+//! 1. The checkpoint is materialized in a staging directory beside the live store and validated
+//! there. A kill leaves only the stage, which the next boot deletes.
+//! 2. Publishing writes a `restore.json` marker into the stage and renames the stage onto the store
+//! path. Until the events group commits the restored positions, the marker keeps every later
+//! boot on the restore path, so a crash never reopens the restored store at the broker's old
+//! offsets.
+
+use std::fs::File;
+use std::io;
+use std::path::{Path, PathBuf};
+
+use metrics::counter;
+use rdkafka::error::{KafkaError, KafkaResult};
+use serde::{Deserialize, Serialize};
+use tracing::warn;
+
+use super::manifest::OffsetManifest;
+use super::metadata::CheckpointMetadata;
+use super::restore_plan::RestorePlan;
+use crate::observability::metrics::CHECKPOINT_RESTORE_SLICES_RESET_TOTAL;
+use crate::partitions::InputGroups;
+use crate::store::{CohortStore, StoreError};
+
+/// The marker a published restore carries inside the store directory. RocksDB ignores files it
+/// does not name, so the store opens with it in place.
+pub const MARKER_FILENAME: &str = "restore.json";
+
+const RECORD_VERSION: u32 = 1;
+
+/// `<store>.restore`: a sibling of the store on the same mount, so a rename publishes it.
+pub fn staging_path(live: &Path) -> PathBuf {
+ let mut name = live.file_name().unwrap_or_default().to_os_string();
+ name.push(".restore");
+ live.with_file_name(name)
+}
+
+/// Where a restored store came from.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "snake_case")]
+pub enum RestoredFrom {
+ /// A local checkpoint.
+ Local { checkpoint_id: String },
+ /// An uploaded checkpoint.
+ S3 { candidate: CheckpointMetadata },
+}
+
+impl RestoredFrom {
+ pub fn label(&self) -> &'static str {
+ match self {
+ Self::Local { .. } => "local",
+ Self::S3 { .. } => "s3",
+ }
+ }
+
+ pub fn checkpoint_id(&self) -> &str {
+ match self {
+ Self::Local { checkpoint_id } => checkpoint_id,
+ Self::S3 { candidate } => &candidate.id,
+ }
+ }
+}
+
+/// What `restore.json` holds. The manifest travels with it, so a resumed restore rebuilds its plan
+/// from it.
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RestoreRecord {
+ version: u32,
+ source: RestoredFrom,
+ manifest: OffsetManifest,
+}
+
+/// A store materialized in the staging directory that opened read-only, holds every SST its
+/// MANIFEST names at the recorded size, and carries this build's schema stamp. Only a validated
+/// stage can be published.
+#[derive(Debug)]
+pub struct ValidatedStage {
+ dir: PathBuf,
+ source: RestoredFrom,
+}
+
+impl ValidatedStage {
+ pub fn validate(dir: PathBuf, source: RestoredFrom) -> Result<Self, StoreError> {
+ CohortStore::validate_read_only(&dir)?;
+ Ok(Self { dir, source })
+ }
+
+ pub fn source(&self) -> &RestoredFrom {
+ &self.source
+ }
+
+ /// 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.
+ pub fn publish(
+ self,
+ manifest: OffsetManifest,
+ plan: RestorePlan,
+ live: &Path,
+ ) -> io::Result<PendingRestore> {
+ for entry in std::fs::read_dir(&self.dir)? {
+ File::open(entry?.path())?.sync_all()?;
+ }
+ let record = RestoreRecord {
+ version: RECORD_VERSION,
+ source: self.source,
+ manifest,
+ };
+ let json = serde_json::to_vec_pretty(&record).map_err(io::Error::other)?;
+ let staged_marker = self.dir.join(MARKER_FILENAME);
+ std::fs::write(&staged_marker, json)?;
+ File::open(&staged_marker)?.sync_all()?;
+ sync_dir(&self.dir)?;
+ std::fs::rename(&self.dir, live)?;
+ sync_dir(parent_dir(live))?;
+ Ok(PendingRestore {
+ marker: live.join(MARKER_FILENAME),
+ record,
+ plan,
+ })
+ }
+}
+
+/// Hard-links the SSTs of a local checkpoint into a new `stage` and copies every other file.
+/// RocksDB never rewrites an SST, so a link costs no space, and the stage shares the store's mount.
+pub fn link_checkpoint(checkpoint: &Path, stage: &Path) -> io::Result<()> {
+ std::fs::create_dir(stage)?;
+ for entry in std::fs::read_dir(checkpoint)? {
+ let entry = entry?;
+ if !entry.file_type()?.is_file() {
+ continue;
+ }
+ let target = stage.join(entry.file_name());
+ if entry.path().extension().is_some_and(|ext| ext == "sst") {
+ std::fs::hard_link(entry.path(), target)?;
+ } else {
+ std::fs::copy(entry.path(), target)?;
+ }
+ }
+ Ok(())
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ResumeError {
+ /// Positions are unknown, so the store cannot be trusted: the boot deletes it and restores
+ /// again.
+ #[error("the restore marker is unreadable")]
+ Undecodable(#[source] serde_json::Error),
+ #[error(transparent)]
+ Io(#[from] io::Error),
+}
+
+/// A published restore whose inputs are not all positioned. `restore.json` keeps every later boot
+/// on this path until [`Self::finish`].
+#[derive(Debug)]
+pub struct PendingRestore {
+ marker: PathBuf,
+ record: RestoreRecord,
+ plan: RestorePlan,
+}
+
+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> {
+ let marker = live.join(MARKER_FILENAME);
+ let bytes = match std::fs::read(&marker) {
+ Ok(bytes) => bytes,
+ Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
+ Err(err) => return Err(err.into()),
+ };
+ let record: RestoreRecord =
+ serde_json::from_slice(&bytes).map_err(ResumeError::Undecodable)?;
+ if record.version != RECORD_VERSION {
+ return Err(ResumeError::Undecodable(serde::de::Error::custom(
+ format_args!("restore record version {}", record.version),
+ )));
+ }
+ let plan = RestorePlan::check(&record.manifest, partition_count);
+ Ok(Some(Self {
+ marker,
+ record,
+ plan,
+ }))
+ }
+
+ pub fn plan(&self) -> &RestorePlan {
+ &self.plan
+ }
+
+ pub fn source(&self) -> &RestoredFrom {
+ &self.record.source
+ }
+
+ /// Commits each follower's planned positions. Safe to repeat: nothing consumes a follower
+ /// before the restore finishes.
+ pub(crate) fn position_followers(&self, groups: &InputGroups) -> KafkaResult<()> {
+ for follower in groups.followers() {
+ follower.commit(&self.plan.positions(follower.topic()))?;
+ }
+ Ok(())
+ }
+
+ /// Deletes the slices the plan cannot replay. Runs right after the store opens, before anything
+ /// reads it.
+ // Called once at startup, before any task reads the store, like `CohortStore::open`.
+ #[allow(clippy::disallowed_methods)]
+ pub(crate) fn reset_slices(&self, store: &CohortStore) -> Result<(), StoreError> {
+ store.reset_slices(self.plan.resets().map(|(partition, _)| partition))?;
+ for (partition, reason) in self.plan.resets() {
+ counter!(CHECKPOINT_RESTORE_SLICES_RESET_TOTAL, "reason" => reason.label())
+ .increment(1);
+ warn!(
+ partition,
+ ?reason,
+ "checkpoint restore reset a slice it cannot replay; it begins again behind the coverage fence",
+ );
+ }
+ 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.
+ pub(crate) fn finish(
+ &self,
+ commit_events: impl FnOnce() -> KafkaResult<()>,
+ ) -> Result<(), FinishError> {
+ commit_events().map_err(FinishError::Commit)?;
+ match std::fs::remove_file(&self.marker) {
+ Ok(()) => {}
+ Err(err) if err.kind() == io::ErrorKind::NotFound => {}
+ Err(err) => return Err(err.into()),
+ }
+ Ok(sync_dir(parent_dir(&self.marker))?)
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum FinishError {
+ #[error("committing the events group's restored positions failed")]
+ Commit(#[source] KafkaError),
+ #[error("deleting the restore marker failed")]
+ Io(#[from] io::Error),
+}
+
+/// Creates the checkpoint directory and checks that it shares a filesystem with the store: a
+/// RocksDB checkpoint and a local restore both hard-link SSTs between the two.
+pub fn ensure_one_filesystem(checkpoint_dir: &Path, store_path: &Path) -> io::Result<()> {
+ use std::os::unix::fs::MetadataExt;
+
+ let store_parent = parent_dir(store_path);
+ std::fs::create_dir_all(checkpoint_dir)?;
+ std::fs::create_dir_all(store_parent)?;
+ let checkpoint_device = std::fs::metadata(checkpoint_dir)?.dev();
+ let store_device = std::fs::metadata(store_parent)?.dev();
+ if checkpoint_device != store_device {
+ return Err(io::Error::other(format!(
+ "{} and {} are on different filesystems; checkpoints hard-link SSTs between them",
+ checkpoint_dir.display(),
+ store_parent.display(),
+ )));
+ }
+ Ok(())
+}
+
+pub(super) fn parent_dir(path: &Path) -> &Path {
+ match path.parent() {
+ Some(parent) if !parent.as_os_str().is_empty() => parent,
+ _ => Path::new("."),
+ }
+}
+
+fn sync_dir(dir: &Path) -> io::Result<()> {
+ File::open(dir)?.sync_all()
+}
+
+#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
+mod tests {
+ use super::*;
+ use std::collections::{BTreeMap, BTreeSet};
+
+ use rdkafka::types::RDKafkaErrorCode;
+ use tempfile::TempDir;
+
+ use crate::partitions::{InputPositions, InputTopic, ResumeOffset};
+ use crate::store::durability::lineage::PodOrdinal;
+ use crate::store::keyspace::{Behavioral, BehavioralKey, Meta, META_SCHEMA_VERSION};
+ use crate::store::{LeafStateKey, StoreConfig};
+
+ const EVENTS: &str = "cohort_stream_events";
+ const MERGES: &str = "person_merge_events";
+
+ /// Slice 0 resumes the events at 42 and the merges at 5.
+ fn manifest() -> OffsetManifest {
+ let at = |topic: &str, offset: i64| {
+ InputPositions::new(
+ InputTopic::new(topic),
+ BTreeMap::from([(0, ResumeOffset::try_from(offset).unwrap())]),
+ )
+ };
+ OffsetManifest::capture(
+ PodOrdinal::STANDALONE,
+ &BTreeSet::from([0]),
+ vec![at(EVENTS, 42), at(MERGES, 5)],
+ )
+ .unwrap()
+ }
+
+ fn key() -> BehavioralKey {
+ BehavioralKey::new(0, 7, uuid::Uuid::from_u128(1), LeafStateKey([0xAB; 16]))
+ }
+
+ /// A checkpoint of a store holding one flushed row, so its MANIFEST names at least one SST.
+ fn checkpoint(root: &Path) -> PathBuf {
+ let store = CohortStore::open(&StoreConfig {
+ path: root.join("source"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ store
+ .write_batch(|b| b.put::<Behavioral>(&key(), b"restored"))
+ .unwrap();
+ store.flush().unwrap();
+ let checkpoint = root.join("checkpoint");
+ store.create_checkpoint(&checkpoint).unwrap();
+ checkpoint
+ }
+
+ fn staged(root: &Path) -> PathBuf {
+ let stage = staging_path(&root.join("store"));
+ link_checkpoint(&checkpoint(root), &stage).unwrap();
+ stage
+ }
+
+ fn local() -> RestoredFrom {
+ RestoredFrom::Local {
+ checkpoint_id: "2026-10-09T16-00-00-000Z".to_string(),
+ }
+ }
+
+ #[test]
+ fn a_stage_missing_an_sst_its_manifest_names_fails_validation() {
+ let root = TempDir::new().unwrap();
+ let stage = staged(root.path());
+ let sst = std::fs::read_dir(&stage)
+ .unwrap()
+ .map(|entry| entry.unwrap().path())
+ .find(|path| path.extension().is_some_and(|ext| ext == "sst"))
+ .expect("the checkpoint holds an SST");
+ std::fs::remove_file(&sst).unwrap();
+ let missing = sst.file_name().unwrap().to_string_lossy().into_owned();
+
+ let err = ValidatedStage::validate(stage, local()).unwrap_err();
+ assert!(
+ matches!(err, StoreError::Open { .. }) && err.to_string().contains(&missing),
+ "{err:?}"
+ );
+ }
+
+ #[test]
+ fn a_stage_with_another_schema_stamp_fails_validation() {
+ let root = TempDir::new().unwrap();
+ let stage = staged(root.path());
+ {
+ let store = CohortStore::open(&StoreConfig {
+ path: stage.clone(),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ store
+ .write_batch(|b| b.put::<Meta>(&META_SCHEMA_VERSION, &0u32.to_be_bytes()))
+ .unwrap();
+ }
+
+ let err = ValidatedStage::validate(stage, local()).unwrap_err();
+ assert!(
+ matches!(err, StoreError::SchemaMismatch { found: Some(0), .. }),
+ "{err:?}"
+ );
+ }
+
+ #[test]
+ fn a_published_restore_stays_pending_until_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 published = ValidatedStage::validate(stage.clone(), local())
+ .unwrap()
+ .publish(manifest(), plan.clone(), &live)
+ .unwrap();
+ assert!(!stage.exists());
+ let store = CohortStore::open(&StoreConfig {
+ path: live.clone(),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_eq!(
+ store.get_behavioral(&key()).unwrap().as_deref(),
+ Some(b"restored".as_slice())
+ );
+ drop(store);
+
+ let resumed = PendingRestore::resume(&live, 1)
+ .unwrap()
+ .expect("the marker survives the store's open");
+ assert_eq!(resumed.plan(), &plan);
+ assert_eq!(resumed.source(), &local());
+
+ let refused = || Err(KafkaError::OffsetFetch(RDKafkaErrorCode::RequestTimedOut));
+ assert!(matches!(
+ published.finish(refused),
+ Err(FinishError::Commit(_))
+ ));
+ assert!(
+ PendingRestore::resume(&live, 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());
+ }
+}
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
index 0292c7ce5c67..30412a25e313 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -52,9 +52,9 @@ use crate::observability::metrics::{
/// by `open_cf_descriptors` (see [`CohortStore::open_inner`]).
///
/// The same version is also stamped into checkpoint `metadata.json` and checked on restore
-/// (`store/durability/import.rs`), which has *different* failure semantics: a mismatched checkpoint is
-/// silently skipped (falling through to the next candidate, then to a cold start), never a hard fail.
-/// A future bump must keep both guards in mind.
+/// (`store/durability/recovery.rs`) with the live store's rule: a mismatched checkpoint blocks the
+/// boot, unless `wipe_on_schema_mismatch` lets the restore pass over it as unusable. A future bump
+/// must keep both guards in mind.
pub const STORE_SCHEMA_VERSION: u32 = 3;
const OP_OPEN: &str = "open";
@@ -63,6 +63,7 @@ const OP_GET: &str = "get";
const OP_MULTI_GET: &str = "multi_get";
const OP_WRITE_BATCH: &str = "write_batch";
const OP_DELETE_PARTITION: &str = "delete_partition";
+const OP_RESET_SLICES: &str = "reset_slices";
const OP_FLUSH: &str = "flush";
const OP_FLUSH_WAL: &str = "flush_wal";
const OP_SCAN: &str = "scan";
@@ -393,13 +394,47 @@ impl CohortStore {
}
})?;
- Ok(Self {
+ Ok(Self::from_db(db, db_opts, config))
+ }
+
+ fn from_db(
+ db: DBWithThreadMode<SingleThreaded>,
+ db_opts: &Options,
+ config: &StoreConfig,
+ ) -> Self {
+ Self {
db: Arc::new(db),
db_opts: Arc::new(db_opts.clone()),
// Floor at 1: `next % ratio` must not divide by zero.
read_sample_ratio: config.read_sample_ratio.max(1),
dirty_tracking: Arc::new(Stage2DirtyTracking::default()),
- })
+ }
+ }
+
+ /// Check that the store at `path` is whole and of this build's schema, without writing to it: it
+ /// opens read-only with this build's column families and carries [`STORE_SCHEMA_VERSION`]. The
+ /// open's consistency check, on under RocksDB's default `paranoid_checks`, refuses a store
+ /// missing any SST its MANIFEST names or holding one at another size.
+ pub fn validate_read_only(path: &Path) -> Result<(), StoreError> {
+ let config = StoreConfig {
+ path: path.to_path_buf(),
+ ..StoreConfig::default()
+ };
+ let db_opts = db_options(&config);
+ let cache = Cache::new_lru_cache(config.block_cache_bytes);
+ let db = DBWithThreadMode::<SingleThreaded>::open_cf_descriptors_read_only(
+ &db_opts,
+ path,
+ column_families::descriptors(&config, &cache),
+ false,
+ )
+ .map_err(|source| StoreError::Open {
+ path: path.to_path_buf(),
+ source,
+ })?;
+ let store = Self::from_db(db, &db_opts, &config);
+ store.check_schema(true, false)?;
+ Ok(())
}
/// Compare the `cf_meta` schema stamp against [`STORE_SCHEMA_VERSION`]. A fresh store (one that
@@ -1057,16 +1092,40 @@ impl CohortStore {
/// their short literal keys collide with an arbitrary partition's byte range, so a range delete
/// would wipe store-wide guards like the schema stamp.
pub fn delete_partition(&self, partition_id: u16) -> Result<(), StoreError> {
- let (start, end) = keys::partition_range(partition_id);
let mut batch = WriteBatch::default();
+ self.delete_partition_ranges(&mut batch, partition_id)?;
+ self.commit(batch, OP_DELETE_PARTITION)
+ }
+
+ /// Delete the slices a checkpoint restore cannot replay, with their coverage records, so each
+ /// begins again behind the coverage fence. The fsync makes the deletes outlive a crash: a
+ /// restore ends by deleting its marker, and a reset still in the async WAL would come back with
+ /// a `Complete` coverage record and positions past the events it lost.
+ pub fn reset_slices(
+ &self,
+ partitions: impl IntoIterator<Item = u16>,
+ ) -> Result<(), StoreError> {
+ let mut batch = WriteBatch::default();
+ for partition_id in partitions {
+ self.delete_partition_ranges(&mut batch, partition_id)?;
+ }
+ self.commit(batch, OP_RESET_SLICES)?;
+ self.flush_wal_sync()
+ }
+
+ fn delete_partition_ranges(
+ &self,
+ batch: &mut WriteBatch,
+ partition_id: u16,
+ ) -> Result<(), StoreError> {
+ let (start, end) = keys::partition_range(partition_id);
for cf in Cf::ALL {
if !cf.partitioned() {
continue;
}
- let handle = self.cf(cf)?;
- batch.delete_range_cf(handle, start.as_slice(), end.as_slice());
+ batch.delete_range_cf(self.cf(cf)?, start.as_slice(), end.as_slice());
}
- self.commit(batch, OP_DELETE_PARTITION)
+ Ok(())
}
/// Flush all CF memtables to SST. Checkpoint path and tests only.
@@ -2798,6 +2857,52 @@ mod tests {
);
}
+ #[test]
+ fn reset_slices_deletes_each_slice_and_its_coverage_record_durably() {
+ let dir = TempDir::new().unwrap();
+ let config = StoreConfig {
+ path: dir.path().join("db"),
+ ..StoreConfig::default()
+ };
+ let start = CoverageStartMs(1_791_547_200_000);
+ {
+ let store = CohortStore::open(&config).unwrap();
+ for partition in [4, 5, 6] {
+ store
+ .write_batch(|b| {
+ b.put::<Behavioral>(&behavioral_key_for(partition, 1), b"state")
+ })
+ .unwrap();
+ store.resume_or_begin_slice(partition, start).unwrap();
+ }
+ store.reset_slices([4, 6]).unwrap();
+ }
+
+ let reopened = CohortStore::open(&config).unwrap();
+ for partition in [4, 6] {
+ assert_eq!(
+ reopened
+ .get_behavioral(&behavioral_key_for(partition, 1))
+ .unwrap(),
+ None,
+ "partition {partition}",
+ );
+ assert_eq!(
+ reopened.slice_coverage(partition).unwrap(),
+ None,
+ "partition {partition}",
+ );
+ }
+ assert!(reopened
+ .get_behavioral(&behavioral_key_for(5, 1))
+ .unwrap()
+ .is_some());
+ assert_eq!(
+ reopened.slice_coverage(5).unwrap(),
+ Some(SliceCoverage::Since(start)),
+ );
+ }
+
#[test]
fn tuned_block_options_preserve_scan_semantics_across_flushed_ssts() {
// Partitioned filters + two-level index change SST metadata layout only, not scan order.
diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rs
index b01d54960896..6a3cd9d965aa 100644
--- a/rust/cohort-stream-processor/tests/events_consumer.rs
+++ b/rust/cohort-stream-processor/tests/events_consumer.rs
@@ -9,7 +9,7 @@
//! ```
//!
//! The S3/PVC disaster-recovery e2e
-//! ([`s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant_left`]) additionally
+//! ([`s3_restore_replays_past_the_checkpoint_after_the_broker_moved_on`]) additionally
//! needs an S3-compatible store. The compose stack's SeaweedFS (`objectstorage`) serves one:
//!
//! ```sh
@@ -43,16 +43,15 @@ use cohort_stream_processor::filters::{
CatalogHandle, CohortId, FilterCatalog, TeamFiltersBuilder, TeamId,
};
use cohort_stream_processor::partitions::{
- run_rebalance_worker, CohortConsumerContext, OffsetTracker, PartitionMirror, PartitionRouter,
- ShuffleMessage, WorkerInbox,
+ run_rebalance_worker, CohortConsumerContext, InputGroups, InputTopic, OffsetTracker,
+ PartitionMirror, PartitionRouter, ShuffleMessage, WorkerInbox,
};
use cohort_stream_processor::producer::{
CaptureSink, CohortMembershipChange, KafkaMembershipSink, MembershipSink, MembershipStatus,
};
use cohort_stream_processor::stage1::{Stage1State, StatefulRecord};
use cohort_stream_processor::store::durability::{
- run_boot_restore, store_hash_prefix, upload_cadence, CheckpointExporter, CheckpointSweeper,
- OffsetManifest, RestoreSource, S3Uploader,
+ open_store, CheckpointLineage, CheckpointSweeper, PendingRestore, PodOrdinal, MARKER_FILENAME,
};
use cohort_stream_processor::store::{
BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,
@@ -1244,11 +1243,12 @@ async fn durable_restart_reopens_live_state_and_fires_a_dormant_left() {
/// Build a `Config` for the disaster-recovery e2e. `store_path` and `checkpoint_local_dir` must be
/// separate temp subtrees: rocksdb hard-links SSTs into the checkpoint, so it must be a *sibling* of
-/// the store, never nested.
+/// the store, never nested. Every input topic and group is the test's own.
fn s3_restore_config(
store_path: &std::path::Path,
checkpoint_dir: &std::path::Path,
prefix: &str,
+ topics: &RestoreTopics,
) -> Config {
let mut env: HashMap<String, String> = HashMap::new();
env.insert("CHECKPOINT_ENABLED".into(), "true".into());
@@ -1276,13 +1276,45 @@ fn s3_restore_config(
env.insert(key.into(), value);
}
}
- Config::init_from_hashmap(&env).expect("build s3-restore config")
+ let mut config = Config::init_from_hashmap(&env).expect("build s3-restore config");
+ config.cohort_partition_count = NUM_PARTITIONS as u32;
+ config.cohort_stream_events_topic = topics.events.clone();
+ config.kafka_consumer_group = topics.group.clone();
+ config.person_merge_events_topic = topics.merges.clone();
+ config.kafka_merge_consumer_group = format!("{}-merges", topics.group);
+ config.cohort_merge_state_transfer_topic = topics.transfers.clone();
+ config.kafka_merge_apply_consumer_group = format!("{}-transfers", topics.group);
+ config
}
-/// Like [`build_consumer_with_restore`], but threads the restore `manifest` into the consumer so it
-/// seeks the events topic to the restored committed offsets on boot.
+/// The e2e's own input topics: the events topic and the two follower topics every processor reads.
+struct RestoreTopics {
+ events: String,
+ merges: String,
+ transfers: String,
+ group: String,
+}
+
+impl RestoreTopics {
+ fn unique() -> Self {
+ let suffix = Uuid::new_v4();
+ Self {
+ events: format!("cohort_stream_events_s3restore_{suffix}"),
+ merges: format!("person_merge_events_s3restore_{suffix}"),
+ transfers: format!("cohort_merge_state_transfer_s3restore_{suffix}"),
+ group: format!("cohort-stream-processor-s3restore-{suffix}"),
+ }
+ }
+
+ fn all(&self) -> [&str; 3] {
+ [&self.events, &self.merges, &self.transfers]
+ }
+}
+
+/// Like [`build_consumer_with_restore`] with durable restore on, but hands the consumer a pending
+/// checkpoint restore to finish on boot.
#[allow(clippy::too_many_arguments)]
-fn build_consumer_with_manifest(
+fn build_consumer_finishing_restore(
topic: &str,
group: &str,
store: CohortStore,
@@ -1290,7 +1322,7 @@ fn build_consumer_with_manifest(
handle: lifecycle::Handle,
sink: Arc<dyn MembershipSink>,
offset_commit_interval: Duration,
- manifest: Option<OffsetManifest>,
+ restore: PendingRestore,
) -> CohortStreamEventsConsumer {
let dispatcher = Arc::new(EventDispatcher::new(
PartitionRouter::new(64),
@@ -1334,28 +1366,18 @@ fn build_consumer_with_manifest(
offset_commit_interval,
NUM_PARTITIONS as usize,
consumer_command_rx,
- manifest,
+ Some(restore),
)
}
-/// Read each partition's committed offset from the broker into a `partition -> next-offset` map — the
-/// next-to-consume position the manifest must carry.
-fn committed_offsets_map(consumer: &StreamConsumer, topic: &str) -> HashMap<i32, i64> {
- let mut tpl = TopicPartitionList::new();
- for partition in 0..NUM_PARTITIONS {
- tpl.add_partition(topic, partition);
- }
- let committed = consumer
- .committed_offsets(tpl, Duration::from_secs(5))
- .expect("fetch committed offsets");
+/// Each partition's high watermark.
+fn high_watermarks(consumer: &StreamConsumer, topic: &str) -> HashMap<i32, i64> {
(0..NUM_PARTITIONS)
- .filter_map(|partition| {
- committed
- .find_partition(topic, partition)
- .and_then(|elem| match elem.offset() {
- Offset::Offset(value) => Some((partition, value)),
- _ => None,
- })
+ .map(|partition| {
+ let (_, high) = consumer
+ .fetch_watermarks(topic, partition, Duration::from_secs(5))
+ .expect("fetch watermarks");
+ (partition, high)
})
.collect()
}
@@ -1395,42 +1417,47 @@ async fn delete_s3_prefix(config: &Config) {
Ok(store) => store,
Err(_) => return,
};
- // Checkpoint SSTs are keyed under `<hash>/<s3_key_prefix>/…`; metadata.json at the bare prefix.
- let hashed = format!("{}/{}", store_hash_prefix(), d.s3_key_prefix);
- for raw_prefix in [d.s3_key_prefix.as_str(), hashed.as_str()] {
- let prefix = ObjPath::from(raw_prefix);
- let mut stream = store.list(Some(&prefix));
- while let Some(entry) = stream.next().await {
- if let Ok(meta) = entry {
- let _result = store.delete(&meta.location).await;
- }
+ let lineage = CheckpointLineage::new(PodOrdinal::STANDALONE);
+ let prefix = ObjPath::from(lineage.remote_dir(&d.s3_key_prefix).as_str());
+ let mut stream = store.list(Some(&prefix));
+ while let Some(entry) = stream.next().await {
+ if let Ok(meta) = entry {
+ let _result = store.delete(&meta.location).await;
}
}
}
-/// Full disaster-recovery path through a real broker + S3: fold + checkpoint to S3 (tenure 1), delete
-/// the store + checkpoint dirs (PVC loss), then restore from S3 and seek the manifest offsets (tenure
-/// 2). Asserts state is restored (not cold-replayed), the resume neither skips nor re-folds, and a
-/// dormant `Left` fires from the eviction queue rebuilt over the restored `cf_behavioral`.
+/// Runbook item A's case through a real broker and S3: fold, checkpoint with positions read from
+/// the broker, fold more and commit past the checkpoint, then lose the volume. The restore must
+/// replay exactly the events after the checkpoint even though the events group already committed
+/// past them, record the idle partition, finish by committing, and fire a dormant `Left` from the
+/// eviction queue rebuilt over the restored `cf_behavioral`.
///
/// Asserting count-exact (not mere presence) sidesteps the documented fast-broker flake.
-#[tokio::test]
+// Multi-threaded: finishing the restore commits with `block_in_place`.
+#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires a running Kafka broker (KAFKA_HOSTS) AND an S3-compatible store (CHECKPOINT_S3_*); see module docs"]
-async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant_left() {
- let suffix = Uuid::new_v4();
- let topic = format!("cohort_stream_events_s3restore_{suffix}");
- let group = format!("cohort-stream-processor-s3restore-{suffix}");
- let prefix = format!("cohort-stream-checkpoints-itest/{suffix}");
-
- create_topic(&topic).await;
- let total = produce_events(&topic).await;
+async fn s3_restore_replays_past_the_checkpoint_after_the_broker_moved_on() {
+ let topics = RestoreTopics::unique();
+ let topic = topics.events.clone();
+ let group = topics.group.clone();
+ let prefix = format!("cohort-stream-checkpoints-itest/{}", Uuid::new_v4());
+ for name in topics.all() {
+ create_topic(name).await;
+ }
+ let before_checkpoint = produce_events(&topic).await;
+ // Nothing consumes the merges topic here, so its group never commits.
+ produce_events(&topics.merges).await;
// Store and checkpoint dirs must be sibling subtrees, never nested (see `s3_restore_config`).
let root = TempDir::new().unwrap();
let store_path = root.path().join("db");
let checkpoint_dir = root.path().join("checkpoints");
- let config = s3_restore_config(&store_path, &checkpoint_dir, &prefix);
+ let config = s3_restore_config(&store_path, &checkpoint_dir, &prefix, &topics);
+ let lineage = config.checkpoint_lineage().expect("standalone lineage");
+ let groups = Arc::new(InputGroups::new(&config));
let lsk = behavioral_lsk(&behavioral_catalog());
+ let total_persons = (PERSONS + NEW_PERSONS) as usize;
// Reads committed offsets without joining the group.
let verifier: StreamConsumer = ClientConfig::new()
@@ -1439,8 +1466,13 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
.set("enable.auto.commit", "false")
.create()
.expect("create verifier consumer");
+ // PERSONS keys over NUM_PARTITIONS partitions leave at least one partition without an event.
+ let idle_partition = high_watermarks(&verifier, &topic)
+ .into_iter()
+ .find_map(|(partition, high)| (high == 0).then_some(partition))
+ .expect("an events partition with no event");
- // --- Tenure 1: fold + fsync-commit, then checkpoint + upload to S3. ---
+ // --- Tenure 1: fold, checkpoint through the sweeper, then fold and commit past it. ---
{
let store = CohortStore::open(&config.store_config()).expect("open tenure-1 store");
let mut manager = Manager::builder("s3restore-itest-1")
@@ -1452,7 +1484,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
);
let shutdown_handle = handle.clone();
let _monitor = manager.monitor_background();
- let (consumer, _dispatcher) = build_consumer_with_restore(
+ let (consumer, dispatcher) = build_consumer_with_restore(
&topic,
&group,
store.clone(),
@@ -1466,87 +1498,85 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
let task = tokio::spawn(consumer.process());
let start = Instant::now();
- while committed_sum(&verifier, &topic) != total as i64 {
+ while committed_sum(&verifier, &topic) != before_checkpoint as i64 {
assert!(
start.elapsed() < Duration::from_secs(60),
- "tenure 1: timed out waiting for committed offsets to reach {total}",
+ "tenure 1: timed out waiting for committed offsets to reach {before_checkpoint}",
);
tokio::time::sleep(Duration::from_millis(200)).await;
}
- shutdown_handle.request_shutdown();
- task.await.expect("tenure-1 consumer panicked");
- assert_eq!(
- entered_persons(&store, lsk),
- PERSONS as usize,
- "tenure 1 folded every produced person",
- );
- // Drive one checkpoint tick directly: a dispatcher owning all partitions + an events tracker
- // seeded from the broker's committed offsets, so the captured manifest carries the resume
- // positions. upload_every_n = 1 ⇒ the first tick uploads.
- let ckpt_dispatcher = Arc::new(EventDispatcher::new(
- PartitionRouter::new(64),
- Arc::new(OffsetTracker::new()),
- test_handle(&store),
- Arc::new(behavioral_catalog()),
- Arc::new(CaptureSink::new()),
- MergeWorkerDeps::capture(),
- ));
- let events_tracker = Arc::new(OffsetTracker::new());
- for (partition, next_offset) in committed_offsets_map(&verifier, &topic) {
- ckpt_dispatcher.assign_partition(partition);
- // Seed committed so `OffsetManifest::capture` (which reads committed_offset) records it.
- events_tracker.mark_dispatched(partition, next_offset);
- let _ = events_tracker.mark_processed(partition, next_offset);
- events_tracker.mark_committed(partition, next_offset);
- }
- let uploader = S3Uploader::new(config.durability_config())
- .await
- .expect("build S3 uploader (is the bucket reachable?)");
- let exporter = CheckpointExporter::new(Box::new(uploader));
+ // upload_every_n = 1, so the tick uploads.
let sweeper = CheckpointSweeper::new(
store.clone(),
- ckpt_dispatcher,
- vec![(topic.clone(), events_tracker)],
- exporter,
+ dispatcher,
+ groups.clone(),
+ lineage,
config.durability_config(),
- checkpoint_dir.clone(),
- upload_cadence(
- config.checkpoint_interval_ms,
- config.checkpoint_s3_upload_interval_ms,
- ),
+ 1,
);
sweeper.run_once().await;
+
+ let total = before_checkpoint + produce_new_persons(&topic, NEW_PERSONS).await;
+ let start = Instant::now();
+ while committed_sum(&verifier, &topic) != total as i64 {
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "tenure 1: timed out waiting for committed offsets to reach {total}",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ shutdown_handle.request_shutdown();
+ task.await.expect("tenure-1 consumer panicked");
+ assert_eq!(
+ entered_persons_range(&store, lsk, total_persons),
+ total_persons
+ );
} // tenure-1 store + dispatcher drop here, releasing the RocksDB lock
+ let total = committed_sum(&verifier, &topic);
- // --- PVC loss: delete BOTH the live store and the local checkpoint dir. ---
+ // --- Volume loss: delete BOTH the live store and the local checkpoint dir. ---
std::fs::remove_dir_all(&store_path).expect("remove store_path (simulate PVC loss)");
std::fs::remove_dir_all(&checkpoint_dir)
.expect("remove checkpoint_local_dir (simulate PVC loss)");
- // --- Tenure 2: restore from S3 + seek the manifest offsets. ---
- let restore = run_boot_restore(&config, &store_path).await;
+ // --- Tenure 2: the boot restores from S3, then the consumer finishes the restore. ---
+ let (store2, restore) = open_store(&config, Some(lineage), groups.clone())
+ .await
+ .expect("open the restored store");
+ let restore = restore
+ .expect("with the live store and local checkpoint gone, the boot restores a checkpoint");
+ assert_eq!(restore.source().label(), "s3");
+ let resumed = restore.plan().positions(&InputTopic::new(topic.as_str()));
assert_eq!(
- restore.source,
- RestoreSource::S3,
- "with the live store and local checkpoint gone, the restore must come from S3",
+ resumed
+ .get(&(idle_partition as u16))
+ .map(|offset| offset.get()),
+ Some(0),
+ "the manifest records the idle partition at its low watermark",
);
- let manifest = restore
- .manifest
- .clone()
- .expect("an S3 restore yields an offset manifest to seek");
-
- let store2 = CohortStore::open(&StoreConfig {
- path: store_path.clone(),
- wipe_on_start: false,
- ..StoreConfig::default()
- })
- .expect("open restored store");
- // (a) Full state present — restored from S3, not cold-replayed. Count-exact (not mere presence).
+ let (merges_with_events, _) = high_watermarks(&verifier, &topics.merges)
+ .into_iter()
+ .find(|&(_, high)| high > 0)
+ .expect("a merges partition holding events");
assert_eq!(
- entered_persons(&store2, lsk),
+ restore
+ .plan()
+ .positions(&InputTopic::new(topics.merges.as_str()))
+ .get(&(merges_with_events as u16))
+ .map(|offset| offset.get()),
+ Some(0),
+ "a group without a commit resumes at the low watermark, before the events it never read",
+ );
+ assert_eq!(
+ resumed.len(),
+ NUM_PARTITIONS as usize,
+ "every partition resumes"
+ );
+ assert_eq!(
+ entered_persons_range(&store2, lsk, total_persons),
PERSONS as usize,
- "the S3 restore re-seeded every member's state (a cold start would read 0)",
+ "the restore holds exactly the state at the checkpoint",
);
let mut manager = Manager::builder("s3restore-itest-2")
@@ -1558,7 +1588,7 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
);
let shutdown_handle = handle.clone();
let _monitor = manager.monitor_background();
- let consumer = build_consumer_with_manifest(
+ let consumer = build_consumer_finishing_restore(
&topic,
&group,
store2.clone(),
@@ -1566,27 +1596,35 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
handle,
Arc::new(CaptureSink::new()),
Duration::from_millis(250),
- Some(manifest),
+ restore,
);
let task = tokio::spawn(consumer.process());
- // (b) Resumes at the manifest offset: no skip and no re-fold. Let the loop settle, seek, and idle;
- // with no events past `total`, committed must stay exactly `total`.
- tokio::time::sleep(Duration::from_secs(5)).await;
+ let start = Instant::now();
+ while entered_persons_range(&store2, lsk, total_persons) != total_persons {
+ assert!(
+ start.elapsed() < Duration::from_secs(60),
+ "tenure 2: timed out replaying the events after the checkpoint",
+ );
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
shutdown_handle.request_shutdown();
task.await.expect("tenure-2 consumer panicked");
assert_eq!(
committed_sum(&verifier, &topic),
- total as i64,
- "resumed exactly at the manifest offset — no skip, no re-fold past the committed position",
+ total,
+ "the replay ends where tenure 1 committed: no skip, no event past the topic's end",
);
assert_eq!(
- entered_persons(&store2, lsk),
- PERSONS as usize,
- "state count is still exact after the restore-seek resume",
+ entered_persons_range(&store2, lsk, total_persons),
+ total_persons
+ );
+ assert!(
+ !store_path.join(MARKER_FILENAME).exists(),
+ "the restore finished after the events group committed",
);
- // (c) Dormant Left: workers re-seed the eviction queue from the restored cf_behavioral, then a sweep
+ // Dormant Left: workers re-seed the eviction queue from the restored cf_behavioral, then a sweep
// past the window evicts every now-dormant member.
let catalog = Arc::new(behavioral_catalog());
let readiness = BootReadiness::new(catalog.clone());
@@ -1619,11 +1657,13 @@ async fn s3_restore_reseeds_state_resumes_at_manifest_offset_and_fires_a_dormant
.filter(|change| change.status == MembershipStatus::Left)
.count();
assert_eq!(
- lefts, PERSONS as usize,
+ lefts, total_persons,
"every restored-then-dormant member emits a Left from the eviction queue rebuilt over the S3-restored cf_behavioral",
);
- // --- Cleanup: delete the topic and the S3 prefix. ---
- delete_topic(&topic).await;
+ // --- Cleanup: delete the topics and the S3 prefix. ---
+ for name in topics.all() {
+ delete_topic(name).await;
+ }
delete_s3_prefix(&config).await;
}
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
index 17244b0aae0f..966f694818b8 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -40,7 +40,7 @@ use cohort_stream_processor::merge::transfer::{
};
use cohort_stream_processor::partitions::{
merge_partition_key, partition_of, run_rebalance_worker, CohortConsumerContext, Follower,
- FollowerSet, OffsetTracker, PartitionRouter, COHORT_PARTITION_COUNT,
+ FollowerSet, InputGroups, InputTopic, OffsetTracker, PartitionRouter, COHORT_PARTITION_COUNT,
};
use cohort_stream_processor::producer::{
CohortMembershipChange, KafkaCascadeSink, KafkaMembershipSink, KafkaStreamEventSink,
@@ -48,12 +48,10 @@ use cohort_stream_processor::producer::{
};
use cohort_stream_processor::stage1::{Stage1State, StatefulRecord};
use cohort_stream_processor::store::durability::{
- run_boot_restore, store_hash_prefix, upload_cadence, CheckpointExporter, CheckpointSweeper,
- OffsetManifest, RestoreSource, S3Uploader,
+ open_store, CheckpointLineage, CheckpointSweeper, PendingRestore, PodOrdinal,
};
use cohort_stream_processor::store::{
- BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreConfig, StoreHandle,
- TombstoneKey,
+ BehavioralKey, CohortStore, LeafStateKey, OffloadConfig, OffloadMode, StoreHandle, TombstoneKey,
};
use cohort_stream_processor::sweep::Sweeper;
use cohort_stream_processor::workers::{
@@ -65,7 +63,7 @@ use futures::FutureExt;
use lifecycle::{ComponentOptions, Handle, Manager};
use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
use rdkafka::client::DefaultClientContext;
-use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};
+use rdkafka::consumer::{Consumer, StreamConsumer};
use rdkafka::message::Message;
use rdkafka::producer::{FutureProducer, FutureRecord};
use rdkafka::util::Timeout;
@@ -504,15 +502,6 @@ async fn produce_merge(producer: &FutureProducer, topic: &str, event: &PersonMer
);
}
-fn open_restored_store(path: &Path) -> CohortStore {
- CohortStore::open(&StoreConfig {
- path: path.to_path_buf(),
- wipe_on_start: false,
- ..StoreConfig::default()
- })
- .expect("open restored store")
-}
-
fn stage1_state(
store: &CohortStore,
partition_id: u16,
@@ -632,12 +621,6 @@ struct Instance {
store: CohortStore,
dispatcher: Arc<EventDispatcher>,
tasks: Vec<JoinHandle<()>>,
- /// Cloned before the originals move into deps/dispatcher so the sweeper reads the same tracker
- /// instances the running consumers mutate (manifest captures follower offsets with content).
- events_tracker: Arc<OffsetTracker>,
- merge_tracker: Arc<OffsetTracker>,
- transfer_tracker: Arc<OffsetTracker>,
- cascade_tracker: Arc<OffsetTracker>,
}
impl Instance {
@@ -652,8 +635,8 @@ impl Instance {
}
}
-/// An optional restore `manifest` seeds follower group committed offsets before the rebalance worker
-/// assigns, so each `incremental_assign(Offset::Stored)` resolves to the restored position.
+/// An optional pending `restore` is finished by the events consumer's boot. Its follower positions
+/// must already be committed, so each `incremental_assign(Offset::Stored)` resolves to them.
#[allow(clippy::too_many_arguments)]
async fn spawn_instance(
topics: &Topics,
@@ -662,7 +645,7 @@ async fn spawn_instance(
catalog: CatalogHandle,
handles: [Handle; 4],
durable_restore: bool,
- manifest: Option<OffsetManifest>,
+ restore: Option<PendingRestore>,
) -> Instance {
let [events_handle, merge_handle, transfer_handle, cascade_handle] = handles;
let kafka_config = producer_kafka_config();
@@ -693,11 +676,6 @@ async fn spawn_instance(
let transfer_tracker = Arc::new(OffsetTracker::new());
let cascade_tracker = Arc::new(OffsetTracker::new());
- let events_tracker_for_instance = events_tracker.clone();
- let merge_tracker_for_instance = merge_tracker.clone();
- let transfer_tracker_for_instance = transfer_tracker.clone();
- let cascade_tracker_for_instance = cascade_tracker.clone();
-
let merge_deps = Arc::new(MergeWorkerDeps {
transfer_sink,
stream_event_sink,
@@ -755,12 +733,6 @@ async fn spawn_instance(
.expect("create cascade follower consumer"),
);
- if let Some(manifest) = manifest.as_ref() {
- commit_follower_offsets_from_manifest(&merges_consumer, &topics.merges, manifest);
- commit_follower_offsets_from_manifest(&transfers_consumer, &topics.transfers, manifest);
- commit_follower_offsets_from_manifest(&cascade_consumer, &topics.cascade, manifest);
- }
-
let followers = Arc::new(FollowerSet::new([
Follower::new(merges_consumer.clone(), topics.merges.clone()),
Follower::new(transfers_consumer.clone(), topics.transfers.clone()),
@@ -832,7 +804,7 @@ async fn spawn_instance(
COMMIT_INTERVAL,
NUM_PARTITIONS as usize,
command_rx,
- manifest,
+ restore,
);
tasks.push(tokio::spawn(events_consumer.process()));
@@ -840,35 +812,6 @@ async fn spawn_instance(
store,
dispatcher,
tasks,
- events_tracker: events_tracker_for_instance,
- merge_tracker: merge_tracker_for_instance,
- transfer_tracker: transfer_tracker_for_instance,
- cascade_tracker: cascade_tracker_for_instance,
- }
-}
-
-/// Seeds a follower group's committed offsets from the manifest so `incremental_assign(Offset::Stored)`
-/// resolves to the restored position. No-op when the manifest has no entries for `topic`.
-fn commit_follower_offsets_from_manifest(
- consumer: &StreamConsumer,
- topic: &str,
- manifest: &OffsetManifest,
-) {
- let Some(partitions) = manifest.topics.get(topic) else {
- return;
- };
- if partitions.is_empty() {
- return;
- }
- let mut tpl = TopicPartitionList::new();
- for (&partition, &next_offset) in partitions {
- tpl.add_partition_offset(topic, partition, Offset::Offset(next_offset))
- .expect("add follower partition to manifest commit TPL");
- }
- if tpl.count() > 0 {
- consumer
- .commit(&tpl, CommitMode::Sync)
- .expect("seed follower group offsets from restore manifest");
}
}
@@ -887,9 +830,10 @@ fn merge_durability_config(
env.insert("DURABLE_RESTORE_ENABLED".into(), "true".into());
env.insert("COHORT_CASCADE_ENABLED".into(), "true".into());
env.insert("DURABLE_RESTORE_SINGLE_POD".into(), "true".into());
+ // Ends in a StatefulSet ordinal, which checkpoints require.
env.insert(
"POD_NAME".into(),
- format!("merge-durability-{}", Uuid::new_v4()),
+ format!("merge-durability-{}-0", Uuid::new_v4()),
);
env.insert("KAFKA_HOSTS".into(), bootstrap_servers());
env.insert(
@@ -941,8 +885,8 @@ fn merge_durability_config(
config
}
-/// Deletes all S3 objects written by this run: hash-prefixed checkpoint files and bare-prefix
-/// metadata.json. Best-effort; errors are ignored so cleanup never fails a passing test.
+/// Deletes all S3 objects written by this run, all under the lineage's directory. Best-effort; errors
+/// are ignored so cleanup never fails a passing test.
async fn delete_s3_prefix(config: &Config) {
use futures::StreamExt;
use object_store::aws::AmazonS3Builder;
@@ -975,47 +919,26 @@ async fn delete_s3_prefix(config: &Config) {
Ok(store) => store,
Err(_) => return,
};
- // Checkpoint SSTs are keyed under `<hash>/<s3_key_prefix>/…`; metadata.json at the bare prefix.
- let hashed = format!("{}/{}", store_hash_prefix(), d.s3_key_prefix);
- for raw_prefix in [d.s3_key_prefix.as_str(), hashed.as_str()] {
- let prefix = ObjPath::from(raw_prefix);
- let mut stream = store.list(Some(&prefix));
- while let Some(entry) = stream.next().await {
- if let Ok(meta) = entry {
- let _result = store.delete(&meta.location).await;
- }
+ let lineage = CheckpointLineage::new(PodOrdinal::STANDALONE);
+ let prefix = ObjPath::from(lineage.remote_dir(&d.s3_key_prefix).as_str());
+ let mut stream = store.list(Some(&prefix));
+ while let Some(entry) = stream.next().await {
+ if let Ok(meta) = entry {
+ let _result = store.delete(&meta.location).await;
}
}
}
-/// Runs one checkpoint tick against the live trackers + running dispatcher and uploads to S3.
-/// `upload_cadence` resolves to 1 so this first tick always uploads.
-async fn checkpoint_to_s3(
- instance: &Instance,
- config: &Config,
- topics: &Topics,
- checkpoint_dir: &Path,
-) {
- let uploader = S3Uploader::new(config.durability_config())
- .await
- .expect("build S3 uploader (is the bucket reachable?)");
- let exporter = CheckpointExporter::new(Box::new(uploader));
+/// 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>) {
let sweeper = CheckpointSweeper::new(
instance.store.clone(),
instance.dispatcher.clone(),
- vec![
- (topics.events.clone(), instance.events_tracker.clone()),
- (topics.merges.clone(), instance.merge_tracker.clone()),
- (topics.transfers.clone(), instance.transfer_tracker.clone()),
- (topics.cascade.clone(), instance.cascade_tracker.clone()),
- ],
- exporter,
+ groups.clone(),
+ config.checkpoint_lineage().expect("ordinal pod name"),
config.durability_config(),
- checkpoint_dir.to_path_buf(),
- upload_cadence(
- config.checkpoint_interval_ms,
- config.checkpoint_s3_upload_interval_ms,
- ),
+ 1,
);
sweeper.run_once().await;
}
@@ -1189,7 +1112,8 @@ 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, &topics, &checkpoint_dir).await;
+ let input_groups = Arc::new(InputGroups::new(&config));
+ checkpoint_to_s3(&instance, &config, &input_groups).await;
shutdown.request_shutdown();
instance.join().await;
@@ -1199,32 +1123,31 @@ async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {
std::fs::remove_dir_all(&checkpoint_dir)
.expect("remove checkpoint_local_dir (simulate PVC loss)");
- // Tenure 2: restore from S3, then verify the manifest and restored state.
- let restore = run_boot_restore(&config, &store_path).await;
- assert!(
- matches!(restore.source, RestoreSource::S3),
- "with the live store and local checkpoint gone, the restore must come from S3 (got {:?})",
- restore.source,
- );
- let manifest = restore
- .manifest
- .clone()
- .expect("an S3 restore yields an offset manifest to seek");
-
- // Follower manifest maps are non-empty: merge offset on P_old's partition, transfer on P_new's.
+ // Tenure 2: the boot restores from S3 and positions the follower groups; verify the state.
+ let (store2, restore) = open_store(
+ &config,
+ Some(config.checkpoint_lineage().expect("ordinal pod name")),
+ input_groups.clone(),
+ )
+ .await
+ .expect("open the restored store");
+ let restore = restore
+ .expect("with the live store and local checkpoint gone, the boot restores a checkpoint");
+ assert_eq!(restore.source().label(), "s3");
+
+ // The followers resume past the merge on P_old's partition and the transfer on P_new's.
+ let merge_resume = restore.plan().positions(&InputTopic::new(topics.merges.as_str()));
+ let transfer_resume = restore
+ .plan()
+ .positions(&InputTopic::new(topics.transfers.as_str()));
assert!(
- manifest.offset_for(&topics.merges, part(p_old) as i32) >= Some(1),
- "the restored manifest must carry the merge follower's offset on P_old's partition \
- (non-empty follower map): {:?}",
- manifest.offset_for(&topics.merges, part(p_old) as i32),
+ merge_resume.get(&part(p_old)).map(|offset| offset.get()) >= Some(1),
+ "the merge follower resumes past the merge on P_old's partition: {merge_resume:?}",
);
assert!(
- manifest.offset_for(&topics.transfers, part(p_new) as i32) >= Some(1),
- "the restored manifest must carry the transfer follower's offset on P_new's partition: {:?}",
- manifest.offset_for(&topics.transfers, part(p_new) as i32),
+ transfer_resume.get(&part(p_new)).map(|offset| offset.get()) >= Some(1),
+ "the transfer follower resumes past the transfer on P_new's partition: {transfer_resume:?}",
);
-
- let store2 = open_restored_store(&store_path);
assert_eq!(
daily_total(&store2, daily_lsk, p_new),
Some(2),
@@ -1259,7 +1182,6 @@ async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {
"B's (cohort 3) cf_stage2 membership bit for P_new survived the restore",
);
- drop(store2); // release the read-only handle so the consumer can reopen it live
let mut manager2 = Manager::builder("merge-durability-itest-2")
.with_trap_signals(false)
.build();
@@ -1267,15 +1189,14 @@ async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {
let shutdown2 = handles2[0].clone();
let _monitor2 = manager2.monitor_background();
- let store2_live = open_restored_store(&store_path);
let instance2 = spawn_instance(
&topics,
&groups,
- store2_live,
+ store2,
merge_catalog(),
handles2,
config.durable_restore_enabled,
- Some(manifest.clone()),
+ Some(restore),
)
.await;
wait_for(
@@ -1336,7 +1257,7 @@ async fn merge_and_cascade_state_survive_an_s3_disaster_restore() {
assert_eq!(
committed_sum(&events_verifier, &topics.events),
topic_message_count(&topics.events),
- "events resumed exactly at the manifest offset — no skip, no re-fold",
+ "events resumed exactly at the restored positions — no skip, no re-fold",
);
// Direct changes are exact. Cascade-origin cohort 3 is at-least-once, bounded [1, 2]: