hydracache 0.57.1

User-facing HydraCache runtime crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;

use serde::{Deserialize, Serialize};

use crate::cluster::{ClusterEpoch, ClusterNodeId, PartitionId};
use crate::grid::durability::DurabilitySnapshotManifest;
use crate::grid::hardening::WriteWatermark;

/// Cluster checkpoint manifest format version registered in `docs/COMPAT.md`.
pub const CLUSTER_CHECKPOINT_MANIFEST_FORMAT_VERSION: u32 = 1;

/// Per-node durable manifests collected for a cluster-wide checkpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeCheckpointManifest {
    /// Node that produced these durable snapshot manifests.
    pub node_id: ClusterNodeId,
    /// Durable snapshot manifests reported by the node.
    pub snapshots: Vec<DurabilitySnapshotManifest>,
}

impl NodeCheckpointManifest {
    /// Create a normalized per-node checkpoint manifest.
    pub fn new(
        node_id: impl Into<ClusterNodeId>,
        mut snapshots: Vec<DurabilitySnapshotManifest>,
    ) -> Self {
        snapshots.sort_by(snapshot_sort);
        Self {
            node_id: node_id.into(),
            snapshots,
        }
    }
}

/// Cluster-wide consistent cut over durable per-node snapshot manifests.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClusterCheckpointManifest {
    /// Manifest format version.
    pub format_version: u32,
    /// Operator/controller supplied checkpoint id.
    pub checkpoint_id: String,
    /// Authority epoch for the cut.
    pub epoch: ClusterEpoch,
    /// Required barrier watermark for each partition in the cut.
    pub partition_watermarks: BTreeMap<PartitionId, WriteWatermark>,
    /// Per-node durable manifests that prove the cut is covered.
    pub node_manifests: BTreeMap<ClusterNodeId, Vec<DurabilitySnapshotManifest>>,
    /// Controller timestamp in milliseconds after process start.
    pub created_after_ms: u64,
    /// Checksum over stable manifest fields.
    pub checksum: u64,
}

impl ClusterCheckpointManifest {
    /// Build and verify a checksum-protected cluster checkpoint manifest.
    pub fn new(
        checkpoint_id: impl Into<String>,
        epoch: ClusterEpoch,
        watermarks: impl IntoIterator<Item = WriteWatermark>,
        node_manifests: impl IntoIterator<Item = NodeCheckpointManifest>,
        created_after: Duration,
    ) -> Result<Self, ClusterCheckpointError> {
        let checkpoint_id = checkpoint_id.into();
        let partition_watermarks = normalize_watermarks(epoch, watermarks)?;
        let node_manifests = normalize_node_manifests(node_manifests)?;
        let created_after_ms = duration_millis(created_after);
        let checksum = checkpoint_checksum(
            &checkpoint_id,
            epoch,
            &partition_watermarks,
            &node_manifests,
            created_after_ms,
        );
        let manifest = Self {
            format_version: CLUSTER_CHECKPOINT_MANIFEST_FORMAT_VERSION,
            checkpoint_id,
            epoch,
            partition_watermarks,
            node_manifests,
            created_after_ms,
            checksum,
        };
        manifest.verify()?;
        Ok(manifest)
    }

    /// Verify format, checksum, per-node manifests, and partition coverage.
    pub fn verify(&self) -> Result<(), ClusterCheckpointError> {
        if self.format_version != CLUSTER_CHECKPOINT_MANIFEST_FORMAT_VERSION {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::UnsupportedFormat,
                format!(
                    "unsupported cluster checkpoint format {}; expected {}",
                    self.format_version, CLUSTER_CHECKPOINT_MANIFEST_FORMAT_VERSION
                ),
            ));
        }
        if self.partition_watermarks.is_empty() {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::EmptyBarrier,
                "cluster checkpoint barrier has no partitions",
            ));
        }
        for (partition, watermark) in &self.partition_watermarks {
            if *partition != watermark.partition {
                return Err(ClusterCheckpointError::new(
                    ClusterCheckpointErrorKind::Manifest,
                    format!(
                        "checkpoint partition key {} does not match watermark partition {}",
                        partition.value(),
                        watermark.partition.value()
                    ),
                ));
            }
            if watermark.epoch != self.epoch {
                return Err(ClusterCheckpointError::new(
                    ClusterCheckpointErrorKind::StaleWatermark,
                    format!(
                        "checkpoint partition {} watermark epoch {} does not match checkpoint epoch {}",
                        partition.value(),
                        watermark.epoch.value(),
                        self.epoch.value()
                    ),
                ));
            }
        }
        if self.node_manifests.is_empty() {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::PartialCut,
                "cluster checkpoint has no node manifests",
            ));
        }
        for snapshots in self.node_manifests.values() {
            for snapshot in snapshots {
                snapshot.verify().map_err(|error| {
                    ClusterCheckpointError::new(
                        ClusterCheckpointErrorKind::Manifest,
                        error.to_string(),
                    )
                })?;
            }
        }
        validate_partition_coverage(&self.partition_watermarks, &self.node_manifests)?;
        let expected = checkpoint_checksum(
            &self.checkpoint_id,
            self.epoch,
            &self.partition_watermarks,
            &self.node_manifests,
            self.created_after_ms,
        );
        if expected != self.checksum {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::Checksum,
                format!(
                    "cluster checkpoint checksum mismatch for '{}'",
                    self.checkpoint_id
                ),
            ));
        }
        Ok(())
    }

    /// Return the barrier watermark for `partition`.
    pub fn watermark_for_partition(&self, partition: PartitionId) -> Option<WriteWatermark> {
        self.partition_watermarks.get(&partition).copied()
    }

    /// Return whether this checkpoint covers the supplied write watermark.
    pub fn covers(&self, watermark: WriteWatermark) -> bool {
        self.watermark_for_partition(watermark.partition)
            .map(|barrier| watermark_is_at_or_before_barrier(watermark, barrier))
            .unwrap_or(false)
    }
}

/// In-memory coordinator for cluster-wide checkpoint collection.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CheckpointCoordinator {
    latest_valid: Option<ClusterCheckpointManifest>,
    rejected_total: u64,
}

impl CheckpointCoordinator {
    /// Create an empty checkpoint coordinator.
    pub fn new() -> Self {
        Self::default()
    }

    /// Collect per-node manifests and store the checkpoint only if the cut is complete.
    pub fn coordinate(
        &mut self,
        checkpoint_id: impl Into<String>,
        epoch: ClusterEpoch,
        watermarks: impl IntoIterator<Item = WriteWatermark>,
        node_manifests: impl IntoIterator<Item = NodeCheckpointManifest>,
        created_after: Duration,
    ) -> Result<ClusterCheckpointManifest, ClusterCheckpointError> {
        match ClusterCheckpointManifest::new(
            checkpoint_id,
            epoch,
            watermarks,
            node_manifests,
            created_after,
        ) {
            Ok(manifest) => {
                self.latest_valid = Some(manifest.clone());
                Ok(manifest)
            }
            Err(error) => {
                self.rejected_total = self.rejected_total.saturating_add(1);
                Err(error)
            }
        }
    }

    /// Return the latest complete, verified checkpoint, if one exists.
    pub fn latest_valid(&self) -> Option<&ClusterCheckpointManifest> {
        self.latest_valid.as_ref()
    }

    /// Return rejected partial/stale/invalid checkpoint attempts.
    pub fn rejected_total(&self) -> u64 {
        self.rejected_total
    }
}

/// Stable checkpoint error kind used by recovery and tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClusterCheckpointErrorKind {
    /// The barrier did not name any partitions.
    EmptyBarrier,
    /// The manifest format is newer or otherwise unsupported.
    UnsupportedFormat,
    /// The manifest checksum does not match stable fields.
    Checksum,
    /// A node crashed or failed to provide coverage for a required partition.
    PartialCut,
    /// A reported snapshot does not cover the required partition watermark.
    StaleWatermark,
    /// A nested durable manifest is malformed or failed verification.
    Manifest,
    /// Restore/rescale was fenced by the current authority epoch.
    AuthorityFence,
}

/// Error returned by checkpoint collection, verification, and restore fencing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClusterCheckpointError {
    kind: ClusterCheckpointErrorKind,
    message: String,
}

impl ClusterCheckpointError {
    /// Create a checkpoint error.
    pub fn new(kind: ClusterCheckpointErrorKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }

    /// Return the stable error kind.
    pub fn kind(&self) -> ClusterCheckpointErrorKind {
        self.kind
    }
}

impl fmt::Display for ClusterCheckpointError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for ClusterCheckpointError {}

fn normalize_watermarks(
    epoch: ClusterEpoch,
    watermarks: impl IntoIterator<Item = WriteWatermark>,
) -> Result<BTreeMap<PartitionId, WriteWatermark>, ClusterCheckpointError> {
    let mut normalized: BTreeMap<PartitionId, WriteWatermark> = BTreeMap::new();
    for watermark in watermarks {
        if watermark.epoch != epoch {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::StaleWatermark,
                format!(
                    "checkpoint watermark for partition {} has epoch {}, expected {}",
                    watermark.partition.value(),
                    watermark.epoch.value(),
                    epoch.value()
                ),
            ));
        }
        match normalized.get(&watermark.partition) {
            Some(existing) if existing.version != watermark.version => {
                return Err(ClusterCheckpointError::new(
                    ClusterCheckpointErrorKind::StaleWatermark,
                    format!(
                        "conflicting checkpoint watermarks for partition {}",
                        watermark.partition.value()
                    ),
                ));
            }
            Some(_) => {}
            None => {
                normalized.insert(watermark.partition, watermark);
            }
        }
    }
    if normalized.is_empty() {
        return Err(ClusterCheckpointError::new(
            ClusterCheckpointErrorKind::EmptyBarrier,
            "cluster checkpoint barrier has no partitions",
        ));
    }
    Ok(normalized)
}

fn normalize_node_manifests(
    node_manifests: impl IntoIterator<Item = NodeCheckpointManifest>,
) -> Result<BTreeMap<ClusterNodeId, Vec<DurabilitySnapshotManifest>>, ClusterCheckpointError> {
    let mut normalized = BTreeMap::new();
    for mut node_manifest in node_manifests {
        if normalized.contains_key(&node_manifest.node_id) {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::Manifest,
                format!(
                    "duplicate checkpoint manifest for node {}",
                    node_manifest.node_id
                ),
            ));
        }
        node_manifest.snapshots.sort_by(snapshot_sort);
        normalized.insert(node_manifest.node_id, node_manifest.snapshots);
    }
    if normalized.is_empty() {
        return Err(ClusterCheckpointError::new(
            ClusterCheckpointErrorKind::PartialCut,
            "cluster checkpoint has no node manifests",
        ));
    }
    Ok(normalized)
}

fn validate_partition_coverage(
    required: &BTreeMap<PartitionId, WriteWatermark>,
    node_manifests: &BTreeMap<ClusterNodeId, Vec<DurabilitySnapshotManifest>>,
) -> Result<(), ClusterCheckpointError> {
    for (partition, barrier) in required {
        let candidates = node_manifests
            .values()
            .flat_map(|snapshots| snapshots.iter())
            .filter(|snapshot| snapshot.watermark.partition == *partition)
            .collect::<Vec<_>>();
        if candidates.is_empty() {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::PartialCut,
                format!(
                    "cluster checkpoint missing snapshot coverage for partition {}",
                    partition.value()
                ),
            ));
        }
        if candidates
            .iter()
            .all(|snapshot| !snapshot_covers_required(snapshot.watermark, *barrier))
        {
            return Err(ClusterCheckpointError::new(
                ClusterCheckpointErrorKind::StaleWatermark,
                format!(
                    "cluster checkpoint has no snapshot at or beyond partition {} watermark {}",
                    partition.value(),
                    barrier.version
                ),
            ));
        }
    }
    Ok(())
}

fn snapshot_covers_required(snapshot: WriteWatermark, required: WriteWatermark) -> bool {
    snapshot.partition == required.partition
        && snapshot.epoch == required.epoch
        && snapshot.version >= required.version
}

fn watermark_is_at_or_before_barrier(watermark: WriteWatermark, barrier: WriteWatermark) -> bool {
    watermark.partition == barrier.partition
        && (watermark.epoch < barrier.epoch
            || (watermark.epoch == barrier.epoch && watermark.version <= barrier.version))
}

fn checkpoint_checksum(
    checkpoint_id: &str,
    epoch: ClusterEpoch,
    watermarks: &BTreeMap<PartitionId, WriteWatermark>,
    node_manifests: &BTreeMap<ClusterNodeId, Vec<DurabilitySnapshotManifest>>,
    created_after_ms: u64,
) -> u64 {
    let mut checksum = ArtifactChecksum::new();
    checksum.u32(CLUSTER_CHECKPOINT_MANIFEST_FORMAT_VERSION);
    checksum.bytes(checkpoint_id.as_bytes());
    checksum.u64(epoch.value());
    checksum.u64(created_after_ms);
    checksum.usize(watermarks.len());
    for (partition, watermark) in watermarks {
        checksum.u32(partition.value());
        checksum.u32(watermark.partition.value());
        checksum.u64(watermark.version);
        checksum.u64(watermark.epoch.value());
    }
    checksum.usize(node_manifests.len());
    for (node, snapshots) in node_manifests {
        checksum.bytes(node.as_str().as_bytes());
        checksum.usize(snapshots.len());
        for snapshot in snapshots {
            checksum.u32(snapshot.format_version);
            checksum.bytes(snapshot.namespace.as_bytes());
            checksum.u32(snapshot.watermark.partition.value());
            checksum.u64(snapshot.watermark.version);
            checksum.u64(snapshot.watermark.epoch.value());
            checksum.u64(snapshot.created_after_ms);
            checksum.u64(snapshot.interval_ms);
            checksum.u64(snapshot.checksum);
        }
    }
    checksum.finish()
}

fn snapshot_sort(
    left: &DurabilitySnapshotManifest,
    right: &DurabilitySnapshotManifest,
) -> std::cmp::Ordering {
    (
        left.watermark.partition.value(),
        left.watermark.epoch.value(),
        left.watermark.version,
        left.namespace.as_str(),
        left.created_after_ms,
    )
        .cmp(&(
            right.watermark.partition.value(),
            right.watermark.epoch.value(),
            right.watermark.version,
            right.namespace.as_str(),
            right.created_after_ms,
        ))
}

fn duration_millis(duration: Duration) -> u64 {
    duration.as_millis().min(u128::from(u64::MAX)) as u64
}

#[derive(Debug, Clone, Copy)]
struct ArtifactChecksum(u64);

impl ArtifactChecksum {
    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const PRIME: u64 = 0x0000_0100_0000_01b3;

    fn new() -> Self {
        Self(Self::OFFSET)
    }

    fn u8(&mut self, value: u8) {
        self.0 ^= u64::from(value);
        self.0 = self.0.wrapping_mul(Self::PRIME);
    }

    fn u32(&mut self, value: u32) {
        self.raw_bytes(&value.to_le_bytes());
    }

    fn u64(&mut self, value: u64) {
        self.raw_bytes(&value.to_le_bytes());
    }

    fn usize(&mut self, value: usize) {
        self.u64(value as u64);
    }

    fn bytes(&mut self, bytes: &[u8]) {
        self.usize(bytes.len());
        self.raw_bytes(bytes);
    }

    fn raw_bytes(&mut self, bytes: &[u8]) {
        for byte in bytes {
            self.u8(*byte);
        }
    }

    fn finish(self) -> u64 {
        self.0
    }
}