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): incremental checkpoint uploads and a final one on stop (#114761)

Matheus Batista925fa1e12e3a
diff --git a/docs/internal/realtime-cohorts/processor-runtime.md b/docs/internal/realtime-cohorts/processor-runtime.md
index 2c016c25344e..987adc01e395 100644
--- a/docs/internal/realtime-cohorts/processor-runtime.md
+++ b/docs/internal/realtime-cohorts/processor-runtime.md
@@ -235,8 +235,14 @@ So follower work that finishes during the drain is committed, not replayed on th
They commit only for the partitions recorded at the drain, because closing the events consumer revokes every partition from the live ownership.
A follower that waits longer than 35 seconds commits for the partitions it owned when shutdown began.
-The events consumer gets 30 seconds to drain and each follower 45 seconds, inside the process's 90-second ceiling.
-Kubernetes kills the pod when its termination grace period ends, so a grace period shorter than that ceiling can cut the drain off, and the uncommitted work replays on the next boot.
+With checkpoints enabled, a final checkpoint follows once every consumer and follower has finished.
+It captures positions for the partitions recorded at the drain and uploads within `CHECKPOINT_FINAL_UPLOAD_TIMEOUT_SECS` of the drain, after shutdown cancels any periodic upload in flight.
+A plan that would upload in full stays local, because it cannot finish in that budget, and the next start uploads in full anyway.
+It is skipped when boot never ended or the drain never finished, because positions are not settled then.
+
+The events consumer gets 30 seconds to drain, each follower 45 seconds, and the final checkpoint 60 seconds after them, inside the process's 110-second ceiling.
+Kubernetes kills the pod when its termination grace period ends, and that period also covers the chart's 5-second preStop sleep before the shutdown starts.
+So a grace period of 115 seconds or less can cut the drain or the final checkpoint off, and the uncommitted work replays on the next boot.
## Store access lanes
diff --git a/docs/internal/realtime-cohorts/state-store-and-durability.md b/docs/internal/realtime-cohorts/state-store-and-durability.md
index 37d63aeb3667..402629e16960 100644
--- a/docs/internal/realtime-cohorts/state-store-and-durability.md
+++ b/docs/internal/realtime-cohorts/state-store-and-durability.md
@@ -166,7 +166,7 @@ A remote one is downloaded there, within `CHECKPOINT_IMPORT_TIMEOUT_SECS`.
A download that times out fails, and the search stops there, because older candidates are about as large.
The stage must open read-only with this build's column families and schema, and RocksDB's open checks that every SST its MANIFEST names is present at the recorded size.
The replay window is then checked again, because a download can outlast part of it.
-The restore writes the `restore.json` marker into the stage and renames the stage onto the store path.
+The restore rewrites `uploaded.json` for the restored store, 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.
@@ -246,9 +246,21 @@ Checkpoints require durable restore, a bucket, and an absolute checkpoint direct
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.
+ An upload sends only the files its predecessor in the chain lacks.
+ A restarted process builds on the last upload, recorded locally in `uploaded.json`, only while the store's RocksDB DB id matches it, because a created store reuses SST file names.
+ `uploaded.json` also records the bucket, so a change of `CHECKPOINT_S3_BUCKET` starts a new chain instead of naming objects in the old bucket.
+ A restored store also reuses the SST numbers written after its checkpoint, so a restore from object storage makes the restored checkpoint the baseline, and a local restore removes the baseline, which makes the next upload full.
+ Once a chain is older than `CHECKPOINT_FULL_UPLOAD_INTERVAL_SECS`, the next upload is full, which bounds the age of the oldest object a restore needs.
+- **Paced uploads.**
+ One upload reads at most `CHECKPOINT_UPLOAD_MAX_BYTES_PER_SEC` from the store's disk across all its files, so a full upload does not starve the live path.
+- **A final checkpoint.**
+ A graceful stop cancels a periodic upload in flight, takes one more checkpoint once every consumer has made its final commit, and uploads it when the plan is incremental.
+ A full plan stays local, because it cannot finish in the budget, and the next start uploads in full anyway.
+ The upload is cancelled `CHECKPOINT_FINAL_UPLOAD_TIMEOUT_SECS` after the drain, but an S3 request in flight runs to its end, so the checkpoint component's shutdown window is the hard limit.
+ An upload stopped before its `metadata.json` is not restorable, so the last finished upload stays the newest restorable one.
- **No expiry.**
- Objects are not expired, because a chain of incremental uploads can reference an object of any age.
+ Objects are not expired.
+ An expiry, when one is set, must exceed the full-upload interval plus the import window.
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.
@@ -256,8 +268,8 @@ A failed build counts `checkpoint_uploads_total{result="unavailable"}`, and the
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_last_capture_timestamp_seconds` and `checkpoint_last_full_upload_timestamp_seconds` are the last captured manifest and the start of the newest upload's chain,
+- `checkpoint_uploads_total{result, trigger}` and `checkpoint_uploaded_bytes_total{kind}` count uploads and the bytes they sent,
- `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,
diff --git a/rust/cohort-stream-processor/src/config.rs b/rust/cohort-stream-processor/src/config.rs
index c39d0bf80ebc..f3d39ece6956 100644
--- a/rust/cohort-stream-processor/src/config.rs
+++ b/rust/cohort-stream-processor/src/config.rs
@@ -601,6 +601,22 @@ pub struct Config {
/// 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,
+
+ /// Age of an upload chain past which the next upload is full (secs). Bounds how old the oldest
+ /// object a restore needs can be.
+ #[envconfig(default = "86400")]
+ pub checkpoint_full_upload_interval_secs: u64,
+
+ /// Average rate one upload may read from the store's disk (bytes per second).
+ #[envconfig(default = "67108864")]
+ pub checkpoint_upload_max_bytes_per_sec: u64,
+
+ /// Budget for the final checkpoint on a graceful stop, from the drain to the end of its upload
+ /// (secs). Past it the upload is cancelled, but an S3 request in flight runs to its end, so the
+ /// checkpoint component's shutdown window is the hard limit. An upload stopped before its
+ /// `metadata.json` leaves the last finished upload the newest restorable one.
+ #[envconfig(default = "45")]
+ pub checkpoint_final_upload_timeout_secs: u64,
}
/// librdkafka consumer fetch-queue bounds: an aggregate byte cap across all partitions and a
@@ -807,6 +823,9 @@ impl Config {
max_upload_buffers: self.checkpoint_max_upload_buffers,
checkpoint_import_timeout: Duration::from_secs(self.checkpoint_import_timeout_secs),
local_checkpoint_max_staleness: self.checkpoint_local_max_staleness(),
+ full_upload_interval: Duration::from_secs(self.checkpoint_full_upload_interval_secs),
+ upload_max_bytes_per_sec: self.checkpoint_upload_max_bytes_per_sec,
+ final_upload_timeout: Duration::from_secs(self.checkpoint_final_upload_timeout_secs),
}
}
@@ -952,12 +971,16 @@ impl Config {
!self.checkpoint_s3_bucket.is_empty(),
"CHECKPOINT_ENABLED requires CHECKPOINT_S3_BUCKET.",
);
- let knobs: [(&str, u64); 11] = [
+ let knobs: [(&str, u64); 14] = [
("CHECKPOINT_INTERVAL_MS", self.checkpoint_interval_ms),
(
"CHECKPOINT_S3_UPLOAD_INTERVAL_MS",
self.checkpoint_s3_upload_interval_ms,
),
+ (
+ "CHECKPOINT_FULL_UPLOAD_INTERVAL_SECS",
+ self.checkpoint_full_upload_interval_secs,
+ ),
(
"CHECKPOINT_MAX_CONCURRENT_UPLOADS",
self.checkpoint_max_concurrent_uploads as u64,
@@ -994,6 +1017,14 @@ impl Config {
"CHECKPOINT_IMPORT_TIMEOUT_SECS",
self.checkpoint_import_timeout_secs,
),
+ (
+ "CHECKPOINT_FINAL_UPLOAD_TIMEOUT_SECS",
+ self.checkpoint_final_upload_timeout_secs,
+ ),
+ (
+ "CHECKPOINT_UPLOAD_MAX_BYTES_PER_SEC",
+ self.checkpoint_upload_max_bytes_per_sec,
+ ),
];
for (name, value) in knobs {
ensure!(value > 0, "{name} must be greater than zero.");
@@ -1340,6 +1371,9 @@ mod tests {
checkpoint_import_window_hours: 20,
checkpoint_import_attempt_depth: 10,
checkpoint_import_timeout_secs: 7200,
+ checkpoint_full_upload_interval_secs: 86_400,
+ checkpoint_upload_max_bytes_per_sec: 64 * 1024 * 1024,
+ checkpoint_final_upload_timeout_secs: 45,
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(),
@@ -2041,7 +2075,7 @@ mod tests {
enabled().validate_startup().unwrap();
type Misconfigure = fn(&mut Config);
- let cases: [(&str, Misconfigure, &str); 9] = [
+ let cases: [(&str, Misconfigure, &str); 10] = [
(
"no bucket",
|c| c.checkpoint_s3_bucket.clear(),
@@ -2052,6 +2086,11 @@ mod tests {
|c| c.checkpoint_interval_ms = 0,
"CHECKPOINT_INTERVAL_MS",
),
+ (
+ "a zero final upload budget",
+ |c| c.checkpoint_final_upload_timeout_secs = 0,
+ "CHECKPOINT_FINAL_UPLOAD_TIMEOUT_SECS",
+ ),
(
"a relative checkpoint dir",
|c| c.checkpoint_local_dir = "checkpoints".to_string(),
@@ -2184,6 +2223,9 @@ mod tests {
config.checkpoint_import_window_hours = 6;
config.checkpoint_import_attempt_depth = 4;
config.checkpoint_import_timeout_secs = 90;
+ config.checkpoint_full_upload_interval_secs = 3601;
+ config.checkpoint_upload_max_bytes_per_sec = 1024;
+ config.checkpoint_final_upload_timeout_secs = 12;
let durability = config.durability_config();
assert_eq!(durability.local_checkpoint_dir, "/data/ckpt");
@@ -2212,6 +2254,9 @@ mod tests {
durability.checkpoint_import_timeout,
Duration::from_secs(90)
);
+ assert_eq!(durability.full_upload_interval, Duration::from_secs(3601));
+ assert_eq!(durability.upload_max_bytes_per_sec, 1024);
+ assert_eq!(durability.final_upload_timeout, Duration::from_secs(12));
}
#[test]
diff --git a/rust/cohort-stream-processor/src/consumers/events.rs b/rust/cohort-stream-processor/src/consumers/events.rs
index e7ac7785227a..d72f13d4b0c9 100644
--- a/rust/cohort-stream-processor/src/consumers/events.rs
+++ b/rust/cohort-stream-processor/src/consumers/events.rs
@@ -97,6 +97,11 @@ impl DrainedOwnership {
pub(crate) fn partitions(&self) -> &HashSet<i32> {
&self.0
}
+
+ #[cfg(test)]
+ pub(crate) fn for_test(partitions: impl IntoIterator<Item = i32>) -> Self {
+ Self(partitions.into_iter().collect())
+ }
}
pub(crate) enum DrainWait {
@@ -2973,6 +2978,13 @@ mod tests {
panic!("the drain finished once the blocked produce was released");
};
assert_eq!(drained.partitions(), &HashSet::from([0, 1]));
+ assert!(
+ matches!(
+ dispatcher.wait_for_worker_drain(Duration::ZERO).await,
+ DrainWait::Drained(_)
+ ),
+ "the final checkpoint waits with no budget, so a finished drain must answer at once",
+ );
let follower_tracker = OffsetTracker::new();
for partition in [0, 1, 2] {
diff --git a/rust/cohort-stream-processor/src/main.rs b/rust/cohort-stream-processor/src/main.rs
index 4745444f3949..21be8a2bcb11 100644
--- a/rust/cohort-stream-processor/src/main.rs
+++ b/rust/cohort-stream-processor/src/main.rs
@@ -36,7 +36,7 @@ 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::checkpoint::run_checkpoints;
use cohort_stream_processor::store::durability::{
ensure_one_filesystem, open_store, upload_cadence, CheckpointSweeper,
};
@@ -79,8 +79,11 @@ async fn async_main(config: Config) -> Result<()> {
.then(|| config.checkpoint_lineage())
.transpose()?;
+ // Covers the 45 s follower windows, then the checkpoint component's 60 s. The pod's termination
+ // grace period must exceed it plus the chart's 5 s preStop sleep, so above 115 s, or Kubernetes
+ // cuts the final checkpoint off.
let mut manager = Manager::builder(SERVICE_NAME)
- .with_global_shutdown_timeout(Duration::from_secs(90))
+ .with_global_shutdown_timeout(Duration::from_secs(110))
.build();
let metrics_handle =
@@ -121,6 +124,17 @@ async fn async_main(config: Config) -> Result<()> {
ComponentOptions::new().with_graceful_shutdown(Duration::from_secs(45)),
)
});
+ // Phase 1: the final checkpoint starts after every consumer and follower has made its final
+ // commit. Its positions are then those final commits, so a restore from it replays no event
+ // folded before the stop.
+ let checkpoint_handle = lineage.map(|_| {
+ manager.register(
+ "checkpoint",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(60))
+ .with_shutdown_phase(1),
+ )
+ });
// Short graceful window: it holds no state and its next tick is disposable.
let tokio_monitor_handle = manager.register(
"tokio-runtime-monitor",
@@ -552,10 +566,11 @@ async fn async_main(config: Config) -> Result<()> {
.start_monitoring(tokio_monitor_handle),
);
- // 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(
+ // Whole-DB checkpoints to the local volume and S3, from boot to the final one on a graceful stop.
+ // The loop waits for boot: a capture before the events rewind would record the broker's old
+ // offsets of a pending restore.
+ if let (Some(lineage), Some(checkpoint_handle)) = (lineage, checkpoint_handle) {
+ let sweeper = Arc::new(CheckpointSweeper::new(
store_for_checkpoint,
dispatcher.clone(),
groups,
@@ -565,7 +580,8 @@ async fn async_main(config: Config) -> Result<()> {
config.checkpoint_interval_ms,
config.checkpoint_s3_upload_interval_ms,
),
- );
+ consumer_handle.shutdown_token(),
+ ));
let stop = consumer_handle.shutdown_token();
let interval = config.checkpoint_interval();
let checkpoint_readiness = boot_readiness.clone();
@@ -573,9 +589,9 @@ async fn async_main(config: Config) -> Result<()> {
tokio::select! {
biased;
// Boot never ended, so there are no settled positions to checkpoint.
- _ = stop.cancelled() => {}
+ _ = stop.cancelled() => checkpoint_handle.work_completed(),
_ = checkpoint_readiness.wait_until_dispatchable() => {
- run_sweep_loop(sweeper, interval, CHECKPOINT_LOOP_NAME, stop.clone()).await;
+ run_checkpoints(sweeper, interval, checkpoint_handle).await;
}
}
});
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 228b299bd4f9..c43026adad28 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -97,9 +97,13 @@ pub const CHECKPOINT_DURATION_SECONDS: &str = "checkpoint_duration_seconds";
pub const CHECKPOINT_SIZE_BYTES: &str = "checkpoint_size_bytes";
/// File count in a freshly-taken checkpoint directory (histogram).
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).
+/// Checkpoint S3 uploads, labelled by `result` (`success`|`error`|`cancelled`|`unavailable`) and
+/// `trigger` (`periodic`|`final`), plus checkpoint ticks skipped by a failed WAL fsync
+/// (`result=flush_failed`) (counter). A cancelled final upload ran out of its budget.
pub const CHECKPOINT_UPLOADS_TOTAL: &str = "checkpoint_uploads_total";
+/// Bytes a successful upload sent, labelled by `kind` (`full`|`incremental`) (counter). Sizes the
+/// bucket's growth for its expiry setting.
+pub const CHECKPOINT_UPLOADED_BYTES_TOTAL: &str = "checkpoint_uploaded_bytes_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 =
@@ -108,6 +112,9 @@ pub const CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS: &str =
/// **Alert on staleness**: no restorable checkpoint is getting newer.
pub const CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS: &str =
"checkpoint_last_upload_timestamp_seconds";
+/// `full_upload_at` of the newest upload: when its chain of incrementals began (gauge, seconds).
+pub const CHECKPOINT_LAST_FULL_UPLOAD_TIMESTAMP_SECONDS: &str =
+ "checkpoint_last_full_upload_timestamp_seconds";
/// Checkpoint ticks skipped before the checkpoint, labelled by `reason` (`positions`|`incomplete`)
/// (counter).
pub const CHECKPOINT_CAPTURE_FAILURES_TOTAL: &str = "checkpoint_capture_failures_total";
@@ -822,6 +829,10 @@ mod tests {
CHECKPOINT_IMPORT_DURATION_SECONDS,
"checkpoint_import_duration_seconds",
);
+ assert_eq!(
+ CHECKPOINT_UPLOADED_BYTES_TOTAL,
+ "checkpoint_uploaded_bytes_total"
+ );
assert_eq!(
CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS,
"checkpoint_last_capture_timestamp_seconds",
@@ -830,6 +841,10 @@ mod tests {
CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS,
"checkpoint_last_upload_timestamp_seconds",
);
+ assert_eq!(
+ CHECKPOINT_LAST_FULL_UPLOAD_TIMESTAMP_SECONDS,
+ "checkpoint_last_full_upload_timestamp_seconds",
+ );
assert_eq!(
CHECKPOINT_CAPTURE_FAILURES_TOTAL,
"checkpoint_capture_failures_total",
diff --git a/rust/cohort-stream-processor/src/partitions/positions.rs b/rust/cohort-stream-processor/src/partitions/positions.rs
index dfd5b4a8e17a..7a699482a854 100644
--- a/rust/cohort-stream-processor/src/partitions/positions.rs
+++ b/rust/cohort-stream-processor/src/partitions/positions.rs
@@ -257,7 +257,8 @@ impl FollowerGroup {
}
}
-/// Every enabled input, built once at startup and shared by the restore and the checkpoint sweeper.
+/// Every enabled input, built once at startup and shared by the restore, the checkpoint sweeper and
+/// the final checkpoint.
pub struct InputGroups {
events: GroupReader,
followers: Vec<FollowerGroup>,
diff --git a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
index d56098489aca..46e8be8aa669 100644
--- a/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
+++ b/rust/cohort-stream-processor/src/store/durability/checkpoint.rs
@@ -1,10 +1,10 @@
//! 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 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.
+//! [`CheckpointSweeper`] takes a frozen whole-DB RocksDB checkpoint to the local volume on every
+//! tick, beside an offset manifest read from the consumer groups, and uploads it to S3 every Nth
+//! tick and once more on a graceful stop, unless that upload would be full. [`run_checkpoints`]
+//! drives it. One `create_checkpoint` at a time, never two racing: the final checkpoint runs on the
+//! periodic loop's task, after the loop.
//!
//! ## Interior mutability without a lock across `.await`
//!
@@ -25,13 +25,19 @@
#![allow(clippy::disallowed_methods)]
use std::collections::BTreeSet;
+use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
+use std::time::Duration;
use async_trait::async_trait;
-use chrono::Utc;
+use chrono::{DateTime, Utc};
+use lifecycle::Handle;
+use serde::{Deserialize, Serialize};
use tokio::sync::OnceCell;
+use tokio::time::Instant;
+use tokio_util::sync::CancellationToken;
use tracing::{error, info, warn};
use super::lineage::CheckpointLineage;
@@ -39,19 +45,78 @@ use super::{
plan_checkpoint, CheckpointExporter, CheckpointMetadata, CheckpointPlan, DurabilityConfig,
OffsetManifest, S3Uploader, METADATA_FILENAME,
};
+use crate::consumers::events::{DrainWait, DrainedOwnership};
use crate::consumers::EventDispatcher;
use crate::observability::metrics::{
CHECKPOINT_CAPTURE_FAILURES_TOTAL, CHECKPOINT_FILE_COUNT,
- CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS, CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS,
- CHECKPOINT_SIZE_BYTES, CHECKPOINT_UPLOADS_TOTAL,
+ CHECKPOINT_LAST_CAPTURE_TIMESTAMP_SECONDS, CHECKPOINT_LAST_FULL_UPLOAD_TIMESTAMP_SECONDS,
+ CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS, CHECKPOINT_SIZE_BYTES,
+ CHECKPOINT_UPLOADED_BYTES_TOTAL, CHECKPOINT_UPLOADS_TOTAL,
};
use crate::partitions::InputGroups;
-use crate::store::CohortStore;
-use crate::sweep::Sweeper;
+use crate::store::{CohortStore, DbIdentity};
+use crate::sweep::{run_sweep_loop, Sweeper};
/// The loop-name label for the checkpoint sweep cycle metrics.
pub const CHECKPOINT_LOOP_NAME: &str = "checkpoint";
+/// The last successful upload's [`UploadBaseline`], in the lineage's local directory. A restarted
+/// process builds its first upload on it when the store's DB id and the bucket still match. A
+/// restore rewrites it, because a restored DB reuses the SST numbers written after its checkpoint.
+pub(crate) const UPLOADED_FILENAME: &str = "uploaded.json";
+
+/// An upload and the bucket it went to. An incremental upload names objects of the uploads before
+/// it, so it builds only on a baseline in the bucket it uploads to.
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub(crate) struct UploadBaseline {
+ s3_bucket: String,
+ metadata: CheckpointMetadata,
+}
+
+impl UploadBaseline {
+ /// Writes `path` atomically (tmp file + rename).
+ pub(crate) fn save(
+ path: &Path,
+ s3_bucket: &str,
+ metadata: CheckpointMetadata,
+ ) -> io::Result<()> {
+ let baseline = Self {
+ s3_bucket: s3_bucket.to_owned(),
+ metadata,
+ };
+ let tmp_path = path.with_extension("json.tmp");
+ std::fs::write(&tmp_path, serde_json::to_vec_pretty(&baseline)?)?;
+ std::fs::rename(&tmp_path, path)
+ }
+
+ /// The baseline at `path` when it went to `s3_bucket`. Any other baseline makes the next upload
+ /// full.
+ pub(crate) fn load(path: &Path, s3_bucket: &str) -> Option<CheckpointMetadata> {
+ let baseline: Self = match std::fs::read(path) {
+ Err(e) if e.kind() == io::ErrorKind::NotFound => return None,
+ read => match read
+ .map_err(serde_json::Error::io)
+ .and_then(|bytes| serde_json::from_slice(&bytes))
+ {
+ Ok(baseline) => baseline,
+ Err(e) => {
+ warn!(error = %e, path = %path.display(), "unreadable upload baseline; the next upload is full");
+ return None;
+ }
+ },
+ };
+ if baseline.s3_bucket != s3_bucket {
+ info!(
+ baseline_bucket = %baseline.s3_bucket,
+ "the upload baseline went to another bucket; the next upload is full",
+ );
+ return None;
+ }
+ Some(baseline.metadata)
+ }
+}
+
/// 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,6 +129,101 @@ pub fn upload_cadence(checkpoint_interval_ms: u64, s3_upload_interval_ms: u64) -
(s3_upload_interval_ms / checkpoint_interval_ms.max(1)).max(1)
}
+/// Why a checkpoint runs.
+#[derive(Debug)]
+pub(crate) enum Trigger {
+ Periodic,
+ /// A graceful stop, after every consumer's final commit. Its upload is cancelled at `deadline`.
+ Final {
+ drained: DrainedOwnership,
+ deadline: Instant,
+ },
+}
+
+impl Trigger {
+ fn label(&self) -> &'static str {
+ match self {
+ Self::Periodic => "periodic",
+ Self::Final { .. } => "final",
+ }
+ }
+
+ /// The slices to capture. A final checkpoint uses the ownership the workers drained under,
+ /// because closing the events consumer empties the live set.
+ fn owned(&self, live: impl FnOnce() -> Vec<i32>) -> BTreeSet<u16> {
+ let partitions = match self {
+ Self::Periodic => live(),
+ Self::Final { drained, .. } => drained.partitions().iter().copied().collect(),
+ };
+ partitions
+ .into_iter()
+ .filter_map(|partition| u16::try_from(partition).ok())
+ .collect()
+ }
+
+ /// A final checkpoint uploads off cadence, so a planned stop leaves nothing to replay past it.
+ /// It uploads only an incremental plan: a full one cannot finish within its budget, and the
+ /// next start uploads in full anyway.
+ fn uploads(&self, tick: u64, every_n: u64, kind: &UploadKind<'_>) -> bool {
+ match self {
+ Self::Periodic => should_upload(tick, every_n),
+ Self::Final { .. } => matches!(kind, UploadKind::Incremental(_)),
+ }
+ }
+}
+
+/// How the next upload treats the last one.
+#[derive(Debug, PartialEq)]
+enum UploadKind<'a> {
+ Full(FullReason),
+ Incremental(&'a CheckpointMetadata),
+}
+
+#[derive(Debug, PartialEq)]
+enum FullReason {
+ NoBaseline,
+ /// A created store restarts SST numbering, so a file name from another DB names other data.
+ OtherDb,
+ /// The chain is older than the full-upload interval, which bounds the age of what a restore
+ /// downloads.
+ ChainExpired,
+}
+
+impl UploadKind<'_> {
+ fn label(&self) -> &'static str {
+ match self {
+ Self::Full(_) => "full",
+ Self::Incremental(_) => "incremental",
+ }
+ }
+
+ fn previous(&self) -> Option<&CheckpointMetadata> {
+ match self {
+ Self::Full(_) => None,
+ Self::Incremental(baseline) => Some(baseline),
+ }
+ }
+}
+
+fn upload_kind<'a>(
+ baseline: Option<&'a CheckpointMetadata>,
+ db: &DbIdentity,
+ now: DateTime<Utc>,
+ full_max_age: Duration,
+) -> UploadKind<'a> {
+ let Some(baseline) = baseline else {
+ return UploadKind::Full(FullReason::NoBaseline);
+ };
+ if &baseline.db_identity != db {
+ return UploadKind::Full(FullReason::OtherDb);
+ }
+ let chain_age = now.signed_duration_since(baseline.full_upload_at).to_std();
+ if chain_age.is_ok_and(|age| age > full_max_age) {
+ return UploadKind::Full(FullReason::ChainExpired);
+ }
+ UploadKind::Incremental(baseline)
+}
+
/// Drives periodic whole-DB checkpoints to the local volume plus incremental S3 backup.
pub struct CheckpointSweeper {
store: CohortStore,
@@ -77,9 +237,13 @@ pub struct CheckpointSweeper {
upload_every_n: u64,
/// Baseline for the next incremental upload. Updated only after a successful upload.
baseline: Mutex<Option<CheckpointMetadata>>,
+ /// Cancels a periodic upload at shutdown, so the final checkpoint does not wait behind it.
+ stop: CancellationToken,
}
impl CheckpointSweeper {
+ /// The first baseline is the lineage's `uploaded.json` when it went to the configured bucket.
+ /// [`upload_kind`] uses it only for the same DB.
pub fn new(
store: CohortStore,
dispatcher: Arc<EventDispatcher>,
@@ -87,7 +251,14 @@ impl CheckpointSweeper {
lineage: CheckpointLineage,
config: DurabilityConfig,
upload_every_n: u64,
+ stop: CancellationToken,
) -> Self {
+ let baseline = UploadBaseline::load(
+ &lineage
+ .local_dir(Path::new(&config.local_checkpoint_dir))
+ .join(UPLOADED_FILENAME),
+ &config.s3_bucket,
+ );
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);
@@ -100,7 +271,8 @@ impl CheckpointSweeper {
exporter: OnceCell::new(),
tick: AtomicU64::new(0),
upload_every_n,
- baseline: Mutex::new(None),
+ baseline: Mutex::new(baseline),
+ stop,
}
}
@@ -109,7 +281,24 @@ impl CheckpointSweeper {
.local_dir(Path::new(&self.config.local_checkpoint_dir))
}
- async fn checkpoint_once(&self) {
+ /// The checkpoint a graceful stop takes once every consumer has made its final commit. Skipped
+ /// when the worker drain never finished, because the positions are then not settled.
+ pub async fn final_checkpoint(&self) {
+ // The budget starts before the WAL flush and the checkpoint, so the upload's cancel lands
+ // inside this component's shutdown window.
+ let deadline = Instant::now() + self.config.final_upload_timeout;
+ match self.dispatcher.wait_for_worker_drain(Duration::ZERO).await {
+ DrainWait::Drained(drained) => {
+ self.checkpoint_once(Trigger::Final { drained, deadline })
+ .await;
+ }
+ DrainWait::TimedOut => warn!(
+ "final checkpoint skipped: the worker drain did not finish, so positions are unsettled",
+ ),
+ }
+ }
+
+ async fn checkpoint_once(&self, trigger: Trigger) {
let tick = self.tick.fetch_add(1, Ordering::SeqCst);
// 1. fsync the WAL before the snapshot. The checkpoint must hold at least what the commits
@@ -134,14 +323,12 @@ impl CheckpointSweeper {
// 2. The slices to capture. A revoke after this point leaves a slice the manifest names but
// the checkpoint lacks, which a restore resumes as empty; an assign leaves one the
// checkpoint holds but the manifest lacks, which a restore resets. Both are safe.
- let owned: BTreeSet<u16> = self
- .dispatcher
- .owned_partitions()
- .into_iter()
- .filter_map(|partition| u16::try_from(partition).ok())
- .collect();
+ let owned = trigger.owned(|| self.dispatcher.owned_partitions());
if owned.is_empty() {
- info!("checkpoint tick: no owned slice; skipping tick");
+ info!(
+ trigger = trigger.label(),
+ "checkpoint tick: no owned slice; skipping tick"
+ );
return;
}
@@ -218,16 +405,30 @@ impl CheckpointSweeper {
}
// 7. Plan against the baseline, then write metadata.json.
+ let db = match self.store.db_identity() {
+ Ok(db) => db,
+ Err(e) => {
+ warn!(error = %e, "checkpoint tick: reading the DB id failed; skipping tick");
+ drop(tokio::fs::remove_dir_all(&attempt_dir).await);
+ return;
+ }
+ };
let baseline = self
.baseline
.lock()
.expect("the baseline lock is never held across a panic")
.clone();
+ let kind = upload_kind(
+ baseline.as_ref(),
+ &db,
+ attempt_timestamp,
+ self.config.full_upload_interval,
+ );
let plan = match plan_checkpoint(
&attempt_dir,
- CheckpointMetadata::new(self.lineage.ordinal(), attempt_timestamp),
+ CheckpointMetadata::new(self.lineage.ordinal(), attempt_timestamp, db),
self.config.s3_key_prefix.clone(),
- baseline.as_ref(),
+ kind.previous(),
None,
) {
Ok(plan) => plan,
@@ -255,6 +456,7 @@ impl CheckpointSweeper {
.set(manifest.captured_at().timestamp() as f64);
info!(
checkpoint_id,
+ trigger = trigger.label(),
dir = %attempt_dir.display(),
size_bytes,
file_count,
@@ -262,8 +464,24 @@ impl CheckpointSweeper {
);
// 9. Upload when due, and advance the baseline on success.
- if should_upload(tick, self.upload_every_n) {
- self.upload(&plan).await;
+ if trigger.uploads(tick, self.upload_every_n, &kind) {
+ match &kind {
+ UploadKind::Full(reason) => {
+ info!(checkpoint_id, ?reason, "uploading a full checkpoint")
+ }
+ UploadKind::Incremental(baseline) => info!(
+ checkpoint_id,
+ baseline = %baseline.id,
+ "uploading an incremental checkpoint",
+ ),
+ }
+ self.upload(&plan, kind.label(), &trigger).await;
+ } else if let (Trigger::Final { .. }, UploadKind::Full(reason)) = (&trigger, &kind) {
+ warn!(
+ checkpoint_id,
+ ?reason,
+ "final checkpoint kept local: a full upload cannot finish within its budget",
+ );
}
// 10. Prune older local checkpoint dirs (keep latest only) to avoid pinning SSTs that the live
@@ -271,7 +489,7 @@ impl CheckpointSweeper {
self.prune_old_checkpoints(&attempt_dir).await;
}
- async fn upload(&self, plan: &CheckpointPlan) {
+ async fn upload(&self, plan: &CheckpointPlan, kind: &'static str, trigger: &Trigger) {
let exporter = match self
.exporter
.get_or_try_init(|| async {
@@ -283,25 +501,78 @@ impl CheckpointSweeper {
{
Ok(exporter) => exporter,
Err(e) => {
- metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "unavailable").increment(1);
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "unavailable", "trigger" => trigger.label())
+ .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 {
+ // A cancelled upload never writes metadata.json, so the last finished upload stays the newest
+ // restorable one, and the baseline stays where it was.
+ let result = match trigger {
+ Trigger::Periodic => {
+ exporter
+ .export_checkpoint_with_plan_cancellable(
+ plan,
+ Some(&self.stop),
+ trigger.label(),
+ )
+ .await
+ }
+ Trigger::Final { deadline, .. } => {
+ let cancel = CancellationToken::new();
+ let upload = exporter.export_checkpoint_with_plan_cancellable(
+ plan,
+ Some(&cancel),
+ trigger.label(),
+ );
+ tokio::pin!(upload);
+ tokio::select! {
+ result = &mut upload => result,
+ // Cancel, then await, instead of dropping the upload with a timeout. A
+ // cancelled upload aborts its multipart writes, and S3 keeps the parts of a
+ // dropped one.
+ _ = tokio::time::sleep_until(*deadline) => {
+ cancel.cancel();
+ upload.await
+ }
+ }
+ }
+ };
+ if let Err(e) = result {
warn!(error = %format!("{e:#}"), "checkpoint S3 upload failed; baseline unchanged");
return;
}
+
+ let bytes: u64 = plan
+ .files_to_upload
+ .iter()
+ .filter_map(|file| std::fs::metadata(&file.local_path).ok())
+ .map(|metadata| metadata.len())
+ .sum();
+ metrics::counter!(CHECKPOINT_UPLOADED_BYTES_TOTAL, "kind" => kind).increment(bytes);
metrics::gauge!(CHECKPOINT_LAST_UPLOAD_TIMESTAMP_SECONDS)
.set(Utc::now().timestamp() as f64);
+ metrics::gauge!(CHECKPOINT_LAST_FULL_UPLOAD_TIMESTAMP_SECONDS)
+ .set(plan.info.metadata.full_upload_at.timestamp() as f64);
+
+ let uploaded = plan.info.metadata.clone();
+ if let Err(e) = UploadBaseline::save(
+ &self.local_dir().join(UPLOADED_FILENAME),
+ &self.config.s3_bucket,
+ uploaded.clone(),
+ ) {
+ warn!(error = %e, "saving the upload baseline failed; the next process builds on an older upload of this DB");
+ }
*self
.baseline
.lock()
- .expect("the baseline lock is never held across a panic") =
- Some(plan.info.metadata.clone());
+ .expect("the baseline lock is never held across a panic") = Some(uploaded);
info!(
+ kind,
uploaded_files = plan.files_to_upload.len(),
+ bytes,
"checkpoint uploaded to S3"
);
}
@@ -336,10 +607,21 @@ impl CheckpointSweeper {
#[async_trait]
impl Sweeper for CheckpointSweeper {
async fn run_once(&self) {
- self.checkpoint_once().await;
+ self.checkpoint_once(Trigger::Periodic).await;
}
}
+/// Takes periodic checkpoints until the sweeper's stop token fires, then a final one once
+/// `handle`'s shutdown phase begins. Register `handle` in a later shutdown phase than every
+/// consumer, so the final checkpoint runs after their final commits.
+pub async fn run_checkpoints(sweeper: Arc<CheckpointSweeper>, interval: Duration, handle: Handle) {
+ let _scope = handle.process_scope();
+ let stop = sweeper.stop.clone();
+ run_sweep_loop(sweeper.clone(), interval, CHECKPOINT_LOOP_NAME, stop).await;
+ handle.shutdown_recv().await;
+ sweeper.final_checkpoint().await;
+}
+
/// Total byte size and file count of a directory tree. Unreadable entries are skipped.
fn dir_size_and_count(dir: &Path) -> (u64, u64) {
let mut size = 0u64;
@@ -369,6 +651,7 @@ fn dir_size_and_count(dir: &Path) -> (u64, u64) {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::store::durability::PodOrdinal;
#[test]
fn should_upload_fires_on_the_first_and_every_nth_tick() {
@@ -399,6 +682,78 @@ mod tests {
assert_eq!(upload_cadence(0, 900_000), 900_000); // zero checkpoint interval handled
}
+ #[test]
+ fn the_final_trigger_captures_the_drained_ownership_and_uploads_only_an_incremental_plan() {
+ let final_trigger = Trigger::Final {
+ drained: DrainedOwnership::for_test([3, 7]),
+ deadline: Instant::now(),
+ };
+ let baseline = CheckpointMetadata::new(
+ PodOrdinal::STANDALONE,
+ Utc::now(),
+ DbIdentity::for_test("db"),
+ );
+ let incremental = UploadKind::Incremental(&baseline);
+ let full = UploadKind::Full(FullReason::ChainExpired);
+ assert_eq!(final_trigger.owned(Vec::new), BTreeSet::from([3, 7]));
+ assert!(final_trigger.uploads(1, 3, &incremental));
+ assert!(!final_trigger.uploads(0, 3, &full));
+
+ assert_eq!(
+ Trigger::Periodic.owned(|| vec![1, 2]),
+ BTreeSet::from([1, 2])
+ );
+ assert!(!Trigger::Periodic.uploads(1, 3, &incremental));
+ assert!(Trigger::Periodic.uploads(0, 3, &full));
+ }
+
+ #[test]
+ fn an_upload_builds_on_its_baseline_only_for_the_same_db_and_bucket_and_a_young_chain() {
+ let now = Utc::now();
+ let day = Duration::from_secs(86_400);
+ let db = DbIdentity::for_test("db-a");
+ let chain_started = |age: chrono::Duration, db: &str| {
+ let mut baseline = CheckpointMetadata::new(
+ PodOrdinal::STANDALONE,
+ now - chrono::Duration::minutes(15),
+ DbIdentity::for_test(db),
+ );
+ baseline.full_upload_at = now - age;
+ baseline
+ };
+ let young = chain_started(chrono::Duration::hours(23), "db-a");
+ let at_limit = chain_started(chrono::Duration::days(1), "db-a");
+ let expired = chain_started(chrono::Duration::hours(25), "db-a");
+ let other_db = chain_started(chrono::Duration::hours(1), "db-b");
+
+ assert_eq!(
+ upload_kind(None, &db, now, day),
+ UploadKind::Full(FullReason::NoBaseline)
+ );
+ assert_eq!(
+ upload_kind(Some(&other_db), &db, now, day),
+ UploadKind::Full(FullReason::OtherDb)
+ );
+ assert_eq!(
+ upload_kind(Some(&expired), &db, now, day),
+ UploadKind::Full(FullReason::ChainExpired)
+ );
+ assert_eq!(
+ upload_kind(Some(&at_limit), &db, now, day),
+ UploadKind::Incremental(&at_limit)
+ );
+ assert_eq!(
+ upload_kind(Some(&young), &db, now, day),
+ UploadKind::Incremental(&young)
+ );
+
+ let dir = tempfile::TempDir::new().unwrap();
+ let uploaded = dir.path().join(UPLOADED_FILENAME);
+ UploadBaseline::save(&uploaded, "bucket-a", young.clone()).unwrap();
+ assert_eq!(UploadBaseline::load(&uploaded, "bucket-a"), Some(young));
+ assert_eq!(UploadBaseline::load(&uploaded, "bucket-b"), None);
+ }
+
#[test]
fn dir_size_and_count_sums_nested_files() {
let dir = tempfile::TempDir::new().unwrap();
diff --git a/rust/cohort-stream-processor/src/store/durability/config.rs b/rust/cohort-stream-processor/src/store/durability/config.rs
index 9563166d8241..8e20cec49f97 100644
--- a/rust/cohort-stream-processor/src/store/durability/config.rs
+++ b/rust/cohort-stream-processor/src/store/durability/config.rs
@@ -74,6 +74,16 @@ pub struct DurabilityConfig {
/// local staleness must be tighter because if a pod was down for longer than this, another pod
/// likely consumed the partition and local data is behind.
pub local_checkpoint_max_staleness: Duration,
+
+ /// Age past which the next upload is full: it bounds how far back a restore's chain of
+ /// incremental uploads reaches.
+ pub full_upload_interval: Duration,
+
+ /// Average read rate one upload may take from the store's disk.
+ pub upload_max_bytes_per_sec: u64,
+
+ /// Budget for the final checkpoint on a graceful stop, from the drain to the end of its upload.
+ pub final_upload_timeout: Duration,
}
impl Default for DurabilityConfig {
@@ -99,6 +109,9 @@ impl Default for DurabilityConfig {
local_checkpoint_max_staleness: Duration::from_secs(
DEFAULT_LOCAL_CHECKPOINT_MAX_STALENESS_SECS,
),
+ full_upload_interval: Duration::from_secs(86_400),
+ upload_max_bytes_per_sec: 64 * 1024 * 1024,
+ final_upload_timeout: Duration::from_secs(45),
}
}
}
diff --git a/rust/cohort-stream-processor/src/store/durability/export.rs b/rust/cohort-stream-processor/src/store/durability/export.rs
index 6a790b777dd4..4df188ed7846 100644
--- a/rust/cohort-stream-processor/src/store/durability/export.rs
+++ b/rust/cohort-stream-processor/src/store/durability/export.rs
@@ -17,22 +17,18 @@ impl CheckpointExporter {
Self { uploader }
}
- pub async fn export_checkpoint_with_plan(&self, plan: &CheckpointPlan) -> Result<()> {
- self.export_checkpoint_with_plan_cancellable(plan, None, None)
- .await
- }
-
/// Export a checkpoint with cancellation support. A cancellation returns an error early but is
- /// recorded as a cancellation (not a failure) in metrics/logs. `cancel_cause` ("rebalance" /
- /// "shutdown") labels that metric.
+ /// recorded as a cancellation (not a failure) in metrics/logs. `trigger` labels the upload
+ /// counter.
pub async fn export_checkpoint_with_plan_cancellable(
&self,
plan: &CheckpointPlan,
cancel_token: Option<&CancellationToken>,
- cancel_cause: Option<&str>,
+ trigger: &'static str,
) -> Result<()> {
if !self.is_available().await {
- metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "unavailable").increment(1);
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "unavailable", "trigger" => trigger)
+ .increment(1);
warn!(
remote_metadata_path = plan.info.get_metadata_key(),
"Export failed: uploader not available"
@@ -55,7 +51,8 @@ impl CheckpointExporter {
metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "success")
.record(upload_duration.as_secs_f64());
- metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "success").increment(1);
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "success", "trigger" => trigger)
+ .increment(1);
info!(
remote_path = plan.info.get_metadata_key(),
@@ -73,20 +70,20 @@ impl CheckpointExporter {
Err(e) => {
let upload_duration = upload_start.elapsed();
if e.downcast_ref::<UploadCancelledError>().is_some() {
- // Metrics labels must be 'static, so map the cause to a fixed string.
- let cause: &'static str = match cancel_cause {
- Some("rebalance") => "rebalance",
- Some("shutdown") => "shutdown",
- _ => "unknown",
- };
- metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "cancelled", "cause" => cause)
+ metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "cancelled")
.record(upload_duration.as_secs_f64());
- metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "cancelled", "cause" => cause)
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "cancelled", "trigger" => trigger)
.increment(1);
+ warn!(
+ remote_path = plan.info.get_metadata_key(),
+ elapsed_seconds = upload_duration.as_secs_f64(),
+ "Export cancelled before its metadata.json; the previous upload stays the newest restorable one",
+ );
} else {
metrics::histogram!(CHECKPOINT_UPLOAD_DURATION_SECONDS, "result" => "error")
.record(upload_duration.as_secs_f64());
- metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "error").increment(1);
+ metrics::counter!(CHECKPOINT_UPLOADS_TOTAL, "result" => "error", "trigger" => trigger)
+ .increment(1);
error!(
remote_path = plan.info.get_metadata_key(),
elapsed_seconds = upload_duration.as_secs_f64(),
@@ -112,6 +109,7 @@ mod tests {
use crate::store::durability::{
CheckpointInfo, CheckpointMetadata, PodOrdinal, UploadCancelledError,
};
+ use crate::store::DbIdentity;
#[derive(Debug)]
struct MockUploader {
@@ -168,7 +166,11 @@ 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(PodOrdinal::STANDALONE, timestamp);
+ let metadata = CheckpointMetadata::new(
+ PodOrdinal::STANDALONE,
+ timestamp,
+ DbIdentity::for_test("db"),
+ );
let info = CheckpointInfo::new(metadata, "checkpoints".to_string());
CheckpointPlan {
info,
@@ -183,7 +185,7 @@ mod tests {
let plan = create_test_plan();
let result = exporter
- .export_checkpoint_with_plan_cancellable(&plan, None, None)
+ .export_checkpoint_with_plan_cancellable(&plan, None, "periodic")
.await;
assert!(result.is_ok());
@@ -196,7 +198,7 @@ mod tests {
let plan = create_test_plan();
let result = exporter
- .export_checkpoint_with_plan_cancellable(&plan, None, Some("rebalance"))
+ .export_checkpoint_with_plan_cancellable(&plan, None, "final")
.await;
assert!(result.is_err());
@@ -214,7 +216,7 @@ mod tests {
let plan = create_test_plan();
let result = exporter
- .export_checkpoint_with_plan_cancellable(&plan, None, None)
+ .export_checkpoint_with_plan_cancellable(&plan, None, "periodic")
.await;
assert!(result.is_err());
diff --git a/rust/cohort-stream-processor/src/store/durability/metadata.rs b/rust/cohort-stream-processor/src/store/durability/metadata.rs
index 863fa96f5f6b..7f0f6bd6d74d 100644
--- a/rust/cohort-stream-processor/src/store/durability/metadata.rs
+++ b/rust/cohort-stream-processor/src/store/durability/metadata.rs
@@ -8,12 +8,12 @@ use tracing::debug;
use super::format_version;
use super::lineage::{CheckpointLineage, PodOrdinal};
-use crate::store::STORE_SCHEMA_VERSION;
+use crate::store::{DbIdentity, STORE_SCHEMA_VERSION};
/// Filename of the checkpoint metadata JSON file, in a remote attempt directory and in a local one.
pub const METADATA_FILENAME: &str = "metadata.json";
-/// 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.
+/// Checkpoint ID format: the S3 attempt directory name, derived from `attempt_timestamp`. A final
+/// checkpoint can land in the same second as a periodic one, so the id carries milliseconds.
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.
@@ -45,18 +45,31 @@ pub struct CheckpointMetadata {
/// The [`STORE_SCHEMA_VERSION`] the checkpointed DB was written under. A restore checks it
/// before downloading anything.
pub store_schema: u32,
+ /// The checkpointed DB's id. An SST file name is unique only within one DB, so an incremental
+ /// upload reuses this checkpoint's files only for a DB with the same id.
+ pub db_identity: DbIdentity,
+ /// The attempt time of the last full upload in this checkpoint's chain of incrementals.
+ pub full_upload_at: DateTime<Utc>,
/// Every remote file needed to reconstitute the store, across this and earlier attempts.
pub files: Vec<CheckpointFile>,
}
impl CheckpointMetadata {
- pub fn new(ordinal: PodOrdinal, attempt_timestamp: DateTime<Utc>) -> Self {
+ /// Metadata for a checkpoint that starts a new chain: `full_upload_at` is its own attempt time
+ /// until an incremental plan copies it from the baseline.
+ pub fn new(
+ ordinal: PodOrdinal,
+ attempt_timestamp: DateTime<Utc>,
+ db_identity: DbIdentity,
+ ) -> Self {
Self {
version: METADATA_VERSION,
id: Self::generate_id(attempt_timestamp),
ordinal,
attempt_timestamp,
store_schema: STORE_SCHEMA_VERSION,
+ db_identity,
+ full_upload_at: attempt_timestamp,
files: Vec::new(),
}
}
@@ -173,7 +186,7 @@ mod tests {
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)
+ CheckpointMetadata::new(ordinal, attempt, DbIdentity::for_test("db-a"))
}
#[test]
diff --git a/rust/cohort-stream-processor/src/store/durability/planner.rs b/rust/cohort-stream-processor/src/store/durability/planner.rs
index 9fe31c9286f0..106a5c8a1ed1 100644
--- a/rust/cohort-stream-processor/src/store/durability/planner.rs
+++ b/rust/cohort-stream-processor/src/store/durability/planner.rs
@@ -17,9 +17,12 @@ pub struct CheckpointPlan {
/// 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.
+/// With no previous attempt, every file uploads and the plan starts a new chain. Otherwise dedup is
+/// keyed on filename: SST files (immutable) are reused from the previous attempt; mutable files are
+/// re-uploaded only on checksum change, and the plan stays in the previous attempt's chain. The
+/// caller must pass a previous attempt of the same DB, because SST names are unique only within one
+/// DB. 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,
@@ -51,6 +54,7 @@ pub fn plan_checkpoint(
});
};
+ info.metadata.full_upload_at = prev_meta.full_upload_at;
let mut prev_file_map: HashMap<String, CheckpointFile> = HashMap::new();
for prev_cp_file in &prev_meta.files {
let filename = prev_cp_file
@@ -236,6 +240,7 @@ mod tests {
use tokio_util::sync::CancellationToken;
use crate::store::durability::{CheckpointLineage, PodOrdinal};
+ use crate::store::DbIdentity;
fn attempt_dir(base: &Path, checkpoint_id: &str) -> PathBuf {
CheckpointLineage::new(PodOrdinal::STANDALONE)
@@ -244,7 +249,11 @@ mod tests {
}
fn metadata_at(attempt_timestamp: DateTime<Utc>) -> CheckpointMetadata {
- CheckpointMetadata::new(PodOrdinal::STANDALONE, attempt_timestamp)
+ CheckpointMetadata::new(
+ PodOrdinal::STANDALONE,
+ attempt_timestamp,
+ DbIdentity::for_test("db"),
+ )
}
fn remote_attempt_dir(namespace: &str, checkpoint_id: &str) -> String {
@@ -318,6 +327,7 @@ mod tests {
plan.info.get_metadata_key(),
format!("{expected_remote_path}/metadata.json"),
);
+ assert_eq!(plan.info.metadata.full_upload_at, attempt_timestamp);
}
#[test]
@@ -328,6 +338,8 @@ mod tests {
let prev_checkpoint_id = CheckpointMetadata::generate_id(prev_attempt_timestamp);
let mut prev_metadata = metadata_at(prev_attempt_timestamp);
+ let chain_started = prev_attempt_timestamp - Duration::hours(5);
+ prev_metadata.full_upload_at = chain_started;
let prev_local_attempt_dir = attempt_dir(temp_dir.path(), &prev_checkpoint_id);
@@ -376,6 +388,10 @@ mod tests {
.unwrap();
assert_eq!(plan.files_to_upload.len(), 1);
+ assert_eq!(
+ plan.info.metadata.full_upload_at, chain_started,
+ "an incremental plan stays in its baseline's chain",
+ );
let got_sst3 = plan
.files_to_upload
.iter()
diff --git a/rust/cohort-stream-processor/src/store/durability/recovery.rs b/rust/cohort-stream-processor/src/store/durability/recovery.rs
index 707dd5340edd..2742c4f00a96 100644
--- a/rust/cohort-stream-processor/src/store/durability/recovery.rs
+++ b/rust/cohort-stream-processor/src/store/durability/recovery.rs
@@ -26,13 +26,15 @@ use metrics::{counter, gauge, histogram};
use rdkafka::error::KafkaError;
use tracing::{error, info, warn};
+use super::checkpoint::{UploadBaseline, UPLOADED_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::{ReplayWindow, RestorePlan};
use super::stage::{
- link_checkpoint, staging_path, PendingRestore, RestoredFrom, ResumeError, ValidatedStage,
+ link_checkpoint, parent_dir, staging_path, sync_dir, PendingRestore, RestoredFrom, ResumeError,
+ ValidatedStage,
};
use super::{DirCleanupGuard, S3Downloader};
use crate::config::Config;
@@ -338,6 +340,8 @@ async fn prepare_store(
let mut restore = Restore {
live: &live,
stage,
+ uploaded: local_dir.join(UPLOADED_FILENAME),
+ s3_bucket: &durability.s3_bucket,
lineage,
events_topic: InputTopic::new(&config.cohort_stream_events_topic),
window,
@@ -410,6 +414,9 @@ struct LocalAttempt {
struct Restore<'a, W> {
live: &'a Path,
stage: PathBuf,
+ /// The lineage's `uploaded.json`, which a publish rewrites.
+ uploaded: PathBuf,
+ s3_bucket: &'a str,
lineage: CheckpointLineage,
events_topic: InputTopic,
window: &'a W,
@@ -605,6 +612,8 @@ impl<W: ReplayWindow> Restore<'_, W> {
Admission::Replays(plan) => plan,
Admission::Rejected(reason) => return Ok(Verdict::Unusable(reason)),
};
+ self.reset_upload_baseline(staged.source())
+ .map_err(RestoreBlocked::Local)?;
let pending = staged
.publish(manifest, plan, self.live)
.map_err(RestoreBlocked::Local)?;
@@ -617,6 +626,24 @@ impl<W: ReplayWindow> Restore<'_, W> {
);
Ok(Verdict::Published(pending))
}
+
+ /// A restored DB reuses the SST numbers written after its checkpoint, so an `uploaded.json` from
+ /// a later upload would name files it rewrites. An uploaded checkpoint becomes the baseline;
+ /// after a local one the next upload is full. The directory is synced before the publish, because
+ /// a crash could otherwise keep the published store beside the old baseline.
+ fn reset_upload_baseline(&self, source: &RestoredFrom) -> io::Result<()> {
+ match source {
+ RestoredFrom::S3 { candidate } => {
+ std::fs::create_dir_all(parent_dir(&self.uploaded))?;
+ UploadBaseline::save(&self.uploaded, self.s3_bucket, candidate.clone())
+ }
+ RestoredFrom::Local { .. } => match std::fs::remove_file(&self.uploaded) {
+ Err(err) if err.kind() != io::ErrorKind::NotFound => Err(err),
+ _ => Ok(()),
+ },
+ }?;
+ sync_dir(parent_dir(&self.uploaded))
+ }
}
/// True when `path` is an opened RocksDB store: the directory holds `CURRENT`, RocksDB's manifest
@@ -844,7 +871,11 @@ mod tests {
})
.unwrap();
std::fs::create_dir_all(parent).unwrap();
- let metadata = CheckpointMetadata::new(PodOrdinal::STANDALONE, Utc::now());
+ let metadata = CheckpointMetadata::new(
+ PodOrdinal::STANDALONE,
+ Utc::now(),
+ store.db_identity().unwrap(),
+ );
let dir = parent.join(&metadata.id);
store.create_checkpoint(&dir).unwrap();
OffsetManifest::capture(
@@ -891,6 +922,7 @@ mod tests {
CheckpointMetadata::new(
PodOrdinal::STANDALONE,
metadata.attempt_timestamp + chrono::Duration::minutes(15),
+ metadata.db_identity.clone(),
),
"checkpoints".to_string(),
);
@@ -911,6 +943,8 @@ mod tests {
Restore {
live: Path::new(&self.config.store_path),
stage: staging_path(Path::new(&self.config.store_path)),
+ uploaded: self.lineage_dir().join(UPLOADED_FILENAME),
+ s3_bucket: &self.config.checkpoint_s3_bucket,
lineage: CheckpointLineage::new(PodOrdinal::STANDALONE),
events_topic: InputTopic::new(EVENTS),
window,
@@ -1013,6 +1047,16 @@ mod tests {
assert_eq!(pending.source().label(), "s3");
assert_eq!(pending.source().checkpoint_id(), checkpoint_id);
assert!(search.failed.is_empty(), "{:?}", search.failed);
+ assert_eq!(
+ UploadBaseline::load(
+ &boot.lineage_dir().join(UPLOADED_FILENAME),
+ &boot.config.checkpoint_s3_bucket,
+ )
+ .unwrap()
+ .id,
+ checkpoint_id,
+ "the restored upload becomes the next upload's baseline",
+ );
}
#[tokio::test(start_paused = true)]
@@ -1056,13 +1100,19 @@ mod tests {
#[tokio::test]
async fn a_local_checkpoint_stays_pending_and_each_boot_checks_its_window_again() {
let boot = Boot::new();
- boot.local_checkpoint();
+ let baseline = boot.local_checkpoint();
+ let uploaded = boot.lineage_dir().join(UPLOADED_FILENAME);
+ UploadBaseline::save(&uploaded, &boot.config.checkpoint_s3_bucket, baseline).unwrap();
let Ok(BootStore::Restored(published)) = boot.prepare(&window()).await else {
panic!("a fresh local checkpoint restores");
};
assert_eq!(published.source().label(), "local");
assert!(boot.live().join(MARKER_FILENAME).is_file());
+ assert!(
+ !uploaded.exists(),
+ "a local restore leaves no upload baseline, so the next upload is full",
+ );
let Ok(BootStore::Restored(resumed)) = boot.prepare(&window()).await else {
panic!("a store with a marker resumes its restore instead of reopening");
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 0173ee5062f9..7bce98eb9317 100644
--- a/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
+++ b/rust/cohort-stream-processor/src/store/durability/s3_uploader.rs
@@ -6,9 +6,11 @@ use object_store::buffered::BufWriter;
use object_store::path::Path as ObjectPath;
use object_store::{ObjectStore, ObjectStoreExt, PutPayload};
use std::path::Path;
-use std::sync::Arc;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};
@@ -21,6 +23,38 @@ use crate::observability::metrics::CHECKPOINT_FILES_UPLOADED_TOTAL;
const UPLOAD_CHUNK_SIZE: usize = 8 * 1024 * 1024; // 8MB
+/// Holds one upload's files, together, to a byte rate. The upload reads the disk the live path and
+/// the boot rebuild read, so an unpaced full upload competes with them for its whole run.
+struct UploadPace {
+ bytes_per_sec: u64,
+ /// When the bytes admitted so far are paid for. Time spent below the rate is not banked, so a
+ /// slow stretch never turns into a burst at full disk speed.
+ next: Mutex<Instant>,
+}
+
+impl UploadPace {
+ fn new(bytes_per_sec: u64) -> Self {
+ Self {
+ bytes_per_sec: bytes_per_sec.max(1),
+ next: Mutex::new(Instant::now()),
+ }
+ }
+
+ /// Counts `bytes`, then waits until the rate allows them.
+ async fn admit(&self, bytes: u64) {
+ let due = {
+ let mut next = self
+ .next
+ .lock()
+ .expect("the pace lock is never held across a panic");
+ *next = (*next).max(Instant::now())
+ + Duration::from_secs_f64(bytes as f64 / self.bytes_per_sec as f64);
+ *next
+ };
+ tokio::time::sleep_until(due).await;
+ }
+}
+
enum ChunkResult {
Data(usize),
EndOfStream,
@@ -86,18 +120,17 @@ impl S3Uploader {
&self,
local_path: &Path,
s3_key: &str,
- cancel_token: Option<&CancellationToken>,
+ cancel_token: &CancellationToken,
+ pace: &UploadPace,
) -> Result<()> {
- if let Some(token) = cancel_token {
- if token.is_cancelled() {
- metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "cancelled")
- .increment(1);
- warn!("Upload cancelled before starting: {s3_key}");
- return Err(UploadCancelledError {
- reason: format!("before starting: {s3_key}"),
- }
- .into());
+ if cancel_token.is_cancelled() {
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "cancelled")
+ .increment(1);
+ warn!("Upload cancelled before starting: {s3_key}");
+ return Err(UploadCancelledError {
+ reason: format!("before starting: {s3_key}"),
}
+ .into());
}
let path = ObjectPath::from(s3_key);
@@ -118,7 +151,8 @@ impl S3Uploader {
let mut buf = vec![0u8; UPLOAD_CHUNK_SIZE];
loop {
- let chunk_result = read_chunk_cancellable(&mut file, &mut buf, cancel_token).await;
+ let chunk_result =
+ read_chunk_cancellable(&mut file, &mut buf, Some(cancel_token)).await;
match chunk_result {
ChunkResult::Data(n) => {
@@ -129,18 +163,16 @@ impl S3Uploader {
return Err(anyhow::Error::new(e))
.with_context(|| format!("Failed to write chunk to S3: {s3_key}"));
}
- }
- ChunkResult::EndOfStream => break,
- ChunkResult::Cancelled => {
- drop(upload.abort().await);
- metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "cancelled")
- .increment(1);
- warn!("Upload of {s3_key} cancelled mid-stream");
- return Err(UploadCancelledError {
- reason: format!("mid-stream: {s3_key}"),
+ if cancel_token
+ .run_until_cancelled(pace.admit(n as u64))
+ .await
+ .is_none()
+ {
+ return Err(cancel_mid_stream(upload, s3_key).await);
}
- .into());
}
+ ChunkResult::EndOfStream => break,
+ ChunkResult::Cancelled => return Err(cancel_mid_stream(upload, s3_key).await),
ChunkResult::Error(e) => {
drop(upload.abort().await);
metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "error")
@@ -177,6 +209,16 @@ impl S3Uploader {
}
}
+async fn cancel_mid_stream(mut upload: BufWriter, s3_key: &str) -> anyhow::Error {
+ drop(upload.abort().await);
+ metrics::counter!(CHECKPOINT_FILES_UPLOADED_TOTAL, "status" => "cancelled").increment(1);
+ warn!("Upload of {s3_key} cancelled mid-stream");
+ UploadCancelledError {
+ reason: format!("mid-stream: {s3_key}"),
+ }
+ .into()
+}
+
#[async_trait]
impl CheckpointUploader for S3Uploader {
async fn upload_checkpoint_with_plan_cancellable(
@@ -205,6 +247,7 @@ impl CheckpointUploader for S3Uploader {
.map(|parent| parent.child_token())
.unwrap_or_default();
+ let pace = UploadPace::new(self.config.upload_max_bytes_per_sec);
// At most N files open simultaneously: N * ~18MB (8MB read buf + ~10MB BufWriter).
let upload_tasks: Vec<_> = plan
.files_to_upload
@@ -215,8 +258,9 @@ impl CheckpointUploader for S3Uploader {
let mut stream = stream::iter(upload_tasks)
.map(|(src, dest)| {
let token = upload_token.clone();
+ let pace = &pace;
async move {
- self.upload_file_cancellable(&src, &dest, Some(&token))
+ self.upload_file_cancellable(&src, &dest, &token, pace)
.await?;
Ok::<String, anyhow::Error>(dest)
}
@@ -356,4 +400,18 @@ mod tests {
_ => panic!("Expected Data result"),
}
}
+
+ #[tokio::test(start_paused = true)]
+ async fn the_pace_holds_concurrent_files_to_one_shared_byte_rate() {
+ let pace = UploadPace::new(4 * 1024 * 1024);
+ let started = Instant::now();
+
+ tokio::join!(
+ pace.admit(8 * 1024 * 1024),
+ pace.admit(8 * 1024 * 1024),
+ pace.admit(4 * 1024 * 1024),
+ );
+
+ assert_eq!(started.elapsed(), Duration::from_secs(5));
+ }
}
diff --git a/rust/cohort-stream-processor/src/store/durability/stage.rs b/rust/cohort-stream-processor/src/store/durability/stage.rs
index 62ea69bdf3eb..83619263a110 100644
--- a/rust/cohort-stream-processor/src/store/durability/stage.rs
+++ b/rust/cohort-stream-processor/src/store/durability/stage.rs
@@ -41,9 +41,10 @@ pub fn staging_path(live: &Path) -> PathBuf {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RestoredFrom {
- /// A local checkpoint.
+ /// A local checkpoint. Its `metadata.json` describes a plan that may never have been uploaded,
+ /// so it is no upload baseline.
Local { checkpoint_id: String },
- /// An uploaded checkpoint.
+ /// An uploaded checkpoint, which the next upload can build on.
S3 { candidate: CheckpointMetadata },
}
@@ -311,7 +312,7 @@ pub(super) fn parent_dir(path: &Path) -> &Path {
}
}
-fn sync_dir(dir: &Path) -> io::Result<()> {
+pub(super) fn sync_dir(dir: &Path) -> io::Result<()> {
File::open(dir)?.sync_all()
}
diff --git a/rust/cohort-stream-processor/src/store/mod.rs b/rust/cohort-stream-processor/src/store/mod.rs
index 5f04c0821695..e08b9155b11d 100644
--- a/rust/cohort-stream-processor/src/store/mod.rs
+++ b/rust/cohort-stream-processor/src/store/mod.rs
@@ -26,8 +26,8 @@ pub use keyspace::{
PersonRecords, SliceCoverageKey, SliceCoverages,
};
pub use rocks::{
- BatchBuilder, CfStats, CohortStore, EventSnapshotRaw, Stage2DirtyTrackingGuard, StoreConfig,
- StoreError, StoreStats, STORE_SCHEMA_VERSION,
+ BatchBuilder, CfStats, CohortStore, DbIdentity, EventSnapshotRaw, Stage2DirtyTrackingGuard,
+ StoreConfig, StoreError, StoreStats, STORE_SCHEMA_VERSION,
};
pub use staged::StagedBatch;
diff --git a/rust/cohort-stream-processor/src/store/rocks.rs b/rust/cohort-stream-processor/src/store/rocks.rs
index 30412a25e313..01d19c4d4a3e 100644
--- a/rust/cohort-stream-processor/src/store/rocks.rs
+++ b/rust/cohort-stream-processor/src/store/rocks.rs
@@ -21,6 +21,7 @@ use rocksdb::{
Cache, ColumnFamily, DBWithThreadMode, Direction, FlushOptions, IteratorMode, Options,
ReadOptions, SingleThreaded, WriteBatch, WriteOptions,
};
+use serde::{Deserialize, Serialize};
use thiserror::Error;
use tracing::{info, warn};
@@ -64,6 +65,7 @@ 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_DB_IDENTITY: &str = "db_identity";
const OP_FLUSH: &str = "flush";
const OP_FLUSH_WAL: &str = "flush_wal";
const OP_SCAN: &str = "scan";
@@ -204,6 +206,18 @@ pub enum StoreError {
OffloadCancelled,
}
+/// The RocksDB DB id. A reopen and a checkpoint keep it; a created store gets a new one.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct DbIdentity(String);
+
+#[cfg(test)]
+impl DbIdentity {
+ pub(crate) fn for_test(id: &str) -> Self {
+ Self(id.to_owned())
+ }
+}
+
/// One scanned key/value pair as raw bytes — the merge-CF GC decodes each per CF.
pub type RawKv = (Vec<u8>, Vec<u8>);
@@ -437,6 +451,17 @@ impl CohortStore {
Ok(())
}
+ pub fn db_identity(&self) -> Result<DbIdentity, StoreError> {
+ let id = self
+ .db
+ .get_db_identity()
+ .map_err(|source| StoreError::Backend {
+ op: OP_DB_IDENTITY,
+ source,
+ })?;
+ Ok(DbIdentity(String::from_utf8_lossy(&id).into_owned()))
+ }
+
/// Compare the `cf_meta` schema stamp against [`STORE_SCHEMA_VERSION`]. A fresh store (one that
/// did not exist before this open) is stamped and passes; an existing store must match. On
/// mismatch, either fail typed or signal a wipe-and-retry per `wipe_on_schema_mismatch`.
@@ -2517,6 +2542,18 @@ mod tests {
restored.get_behavioral(&key).unwrap().as_deref(),
Some(b"snapshot".as_slice()),
);
+ assert_eq!(
+ restored.db_identity().unwrap(),
+ store.db_identity().unwrap(),
+ "a restored checkpoint is the same DB, so an incremental upload may reuse its files",
+ );
+
+ let created = CohortStore::open(&StoreConfig {
+ path: dir.path().join("other"),
+ ..StoreConfig::default()
+ })
+ .unwrap();
+ assert_ne!(created.db_identity().unwrap(), store.db_identity().unwrap());
}
// RocksDB's Checkpoint::create_checkpoint creates the destination dir itself and requires
diff --git a/rust/cohort-stream-processor/src/sweep/scheduler.rs b/rust/cohort-stream-processor/src/sweep/scheduler.rs
index 2a9d0c9ee963..9923f225b6d6 100644
--- a/rust/cohort-stream-processor/src/sweep/scheduler.rs
+++ b/rust/cohort-stream-processor/src/sweep/scheduler.rs
@@ -23,6 +23,13 @@ pub trait Sweeper: Send + Sync {
async fn run_once(&self);
}
+#[async_trait]
+impl<S: Sweeper + ?Sized> Sweeper for std::sync::Arc<S> {
+ async fn run_once(&self) {
+ (**self).run_once().await;
+ }
+}
+
/// The cutoff a worker passes to [`EvictionQueue::due_keys`](super::EvictionQueue::due_keys): a key
/// is due once its deadline is strictly before `now_ms − safety_margin_ms`.
///
diff --git a/rust/cohort-stream-processor/tests/events_consumer.rs b/rust/cohort-stream-processor/tests/events_consumer.rs
index 6a3cd9d965aa..27c5b38cae0a 100644
--- a/rust/cohort-stream-processor/tests/events_consumer.rs
+++ b/rust/cohort-stream-processor/tests/events_consumer.rs
@@ -1506,16 +1506,37 @@ async fn s3_restore_replays_past_the_checkpoint_after_the_broker_moved_on() {
tokio::time::sleep(Duration::from_millis(200)).await;
}
- // upload_every_n = 1, so the tick uploads.
- let sweeper = CheckpointSweeper::new(
- store.clone(),
- dispatcher,
- groups.clone(),
- lineage,
- config.durability_config(),
- 1,
+ // upload_every_n = 1, so every tick uploads.
+ let sweeper = |dispatcher| {
+ CheckpointSweeper::new(
+ store.clone(),
+ dispatcher,
+ groups.clone(),
+ lineage,
+ config.durability_config(),
+ 1,
+ tokio_util::sync::CancellationToken::new(),
+ )
+ };
+ let uploaded = lineage
+ .local_dir(std::path::Path::new(&config.checkpoint_local_dir))
+ .join("uploaded.json");
+ let baseline = || -> serde_json::Value {
+ serde_json::from_slice(
+ &std::fs::read(&uploaded).expect("an upload records its baseline"),
+ )
+ .unwrap()
+ };
+ sweeper(dispatcher.clone()).run_once().await;
+ let first = baseline();
+ // A second sweeper over the same store stands in for a restarted process.
+ sweeper(dispatcher).run_once().await;
+ let second = baseline();
+ assert_ne!(second["metadata"]["id"], first["metadata"]["id"]);
+ assert_eq!(
+ second["metadata"]["full_upload_at"], first["metadata"]["full_upload_at"],
+ "a restarted process continues the upload chain of its store",
);
- sweeper.run_once().await;
let total = before_checkpoint + produce_new_persons(&topic, NEW_PERSONS).await;
let start = Instant::now();
diff --git a/rust/cohort-stream-processor/tests/merge_durability.rs b/rust/cohort-stream-processor/tests/merge_durability.rs
index 966f694818b8..1ee02585663d 100644
--- a/rust/cohort-stream-processor/tests/merge_durability.rs
+++ b/rust/cohort-stream-processor/tests/merge_durability.rs
@@ -939,6 +939,7 @@ async fn checkpoint_to_s3(instance: &Instance, config: &Config, groups: &Arc<Inp
config.checkpoint_lineage().expect("ordinal pod name"),
config.durability_config(),
1,
+ tokio_util::sync::CancellationToken::new(),
);
sweeper.run_once().await;
}