reddb-io-server 1.46.0

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Lease-generation-fenced publication of serverless snapshots.
//!
//! Payloads are uploaded under immutable keys. Only the small `HEAD.json`
//! pointer is mutable, and every owner claims and advances it with backend CAS.
//! A stale process may finish an expensive payload upload after its lease has
//! expired, but it cannot make that payload current after a successor claims
//! the head under a newer lease generation.

use std::path::Path;
use std::sync::{Arc, Mutex};

use crate::replication::lease::WriterLease;
use crate::storage::backend::{
    AtomicRemoteBackend, BackendError, BackendObjectVersion, ConditionalPut,
};

#[derive(Debug)]
pub enum SnapshotPublicationError {
    Backend(BackendError),
    InvalidState(String),
    Fenced(String),
}

impl std::fmt::Display for SnapshotPublicationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Backend(err) => write!(f, "snapshot publication backend error: {err}"),
            Self::InvalidState(message) => write!(f, "snapshot publication state error: {message}"),
            Self::Fenced(message) => write!(f, "snapshot publication fenced: {message}"),
        }
    }
}

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

impl From<BackendError> for SnapshotPublicationError {
    fn from(value: BackendError) -> Self {
        Self::Backend(value)
    }
}

/// An uploaded generation a writer is about to make current.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GenerationPointer {
    pub manifest_key: String,
    /// Object key of the generation's main data file (`snapshot_key`).
    pub data_key: String,
    pub wal_lsn: u64,
}

impl GenerationPointer {
    fn as_ref_for_new_stream(&self, epoch: u64) -> reddb_file::ServerlessGenerationRef {
        reddb_file::ServerlessGenerationRef {
            manifest_key: self.manifest_key.clone(),
            wal_lsn: self.wal_lsn,
            wal_epochs: vec![reddb_file::ServerlessWalEpoch {
                epoch,
                start_lsn: 1,
            }],
        }
    }
}

/// Drop claims whose whole range is already inside the generation; the claim
/// that owns `wal_lsn + 1` and every later claim stay.
fn prune_wal_epochs(generation: &mut reddb_file::ServerlessGenerationRef) {
    let first_needed = generation.wal_lsn.saturating_add(1);
    while generation.wal_epochs.len() > 1 && generation.wal_epochs[1].start_lsn <= first_needed {
        generation.wal_epochs.remove(0);
    }
}

#[derive(Clone)]
struct VersionedHead {
    head: reddb_file::ServerlessSnapshotHead,
    version: BackendObjectVersion,
}

enum PublicationState {
    Unobserved,
    Observed(Option<VersionedHead>),
    Claimed(VersionedHead),
    Fenced,
}

pub struct SnapshotPublicationStore {
    backend: Arc<dyn AtomicRemoteBackend>,
    database_key: String,
    head_key: String,
    state: Mutex<PublicationState>,
}

impl SnapshotPublicationStore {
    pub fn new(backend: Arc<dyn AtomicRemoteBackend>, database_key: impl Into<String>) -> Self {
        let database_key = database_key.into();
        let head_key = reddb_file::serverless_snapshot_head_key(&database_key);
        Self {
            backend,
            database_key,
            head_key,
            state: Mutex::new(PublicationState::Unobserved),
        }
    }

    /// Observe the exact head version used to hydrate this boot. The later
    /// claim must CAS this version; if publication advances while the runtime
    /// is opening, the claim fails and boot retries from the newer snapshot.
    pub fn observe_for_boot(&self) -> Result<Option<String>, SnapshotPublicationError> {
        let mut state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        match &*state {
            PublicationState::Unobserved => {}
            PublicationState::Observed(head) => {
                return Ok(head.as_ref().map(|head| head.head.snapshot_key.clone()));
            }
            PublicationState::Claimed(head) => {
                return Ok(Some(head.head.snapshot_key.clone()));
            }
            PublicationState::Fenced => {
                return Err(SnapshotPublicationError::Fenced(
                    "publication head was already superseded".to_string(),
                ));
            }
        }

        let observed = self.read_versioned_head()?;
        let snapshot_key = observed.as_ref().map(|head| head.head.snapshot_key.clone());
        *state = PublicationState::Observed(observed);
        Ok(snapshot_key)
    }

    /// Claim the observed head for `lease`. On the first serverless boot there
    /// is no head yet, so the already-open local database is uploaded once as
    /// an initial immutable snapshot and installed with `IfAbsent`.
    pub fn claim(
        &self,
        lease: &WriterLease,
        local_snapshot: &Path,
    ) -> Result<(), SnapshotPublicationError> {
        let mut state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        let observed = match &*state {
            PublicationState::Observed(observed) => observed.clone(),
            PublicationState::Unobserved => {
                return Err(SnapshotPublicationError::InvalidState(
                    "head must be observed before lease acquisition".to_string(),
                ));
            }
            PublicationState::Claimed(_) => {
                return Err(SnapshotPublicationError::InvalidState(
                    "head is already claimed".to_string(),
                ));
            }
            PublicationState::Fenced => {
                return Err(SnapshotPublicationError::Fenced(
                    "publication head was already superseded".to_string(),
                ));
            }
        };

        let (next, condition) = match observed {
            Some(current) => {
                if current.head.database_key != self.database_key {
                    return Err(SnapshotPublicationError::InvalidState(format!(
                        "head database '{}' does not match '{}'",
                        current.head.database_key, self.database_key
                    )));
                }
                let mut next = current.head;
                // Release deletes the lease object, so generations may repeat.
                // Reserve a sequence on every claim to avoid both payload-key
                // reuse and identical HEAD bytes (ABA) across clean restarts.
                next.publication_sequence =
                    next.publication_sequence.checked_add(1).ok_or_else(|| {
                        SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
                    })?;
                next.holder_id = lease.holder_id.clone();
                next.term = lease.term;
                next.lease_generation = lease.generation;
                (next, ConditionalPut::IfVersion(current.version))
            }
            None => {
                let publication_sequence = 1;
                let snapshot_key = reddb_file::serverless_snapshot_key(
                    &self.database_key,
                    lease.generation,
                    publication_sequence,
                );
                self.backend.upload_conditional(
                    local_snapshot,
                    &snapshot_key,
                    ConditionalPut::IfAbsent,
                )?;
                (
                    reddb_file::ServerlessSnapshotHead {
                        database_key: self.database_key.clone(),
                        holder_id: lease.holder_id.clone(),
                        term: lease.term,
                        lease_generation: lease.generation,
                        publication_sequence,
                        snapshot_key,
                        generation: None,
                    },
                    ConditionalPut::IfAbsent,
                )
            }
        };

        match self.publish_head(&next, condition) {
            Ok(version) => {
                *state = PublicationState::Claimed(VersionedHead {
                    head: next,
                    version,
                });
                Ok(())
            }
            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
                *state = PublicationState::Fenced;
                Err(SnapshotPublicationError::Fenced(message))
            }
            Err(err) => Err(err),
        }
    }

    pub fn publish(
        &self,
        lease: &WriterLease,
        local_snapshot: &Path,
    ) -> Result<(), SnapshotPublicationError> {
        let mut state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        let current = match &*state {
            PublicationState::Claimed(current) => current.clone(),
            PublicationState::Fenced => {
                return Err(SnapshotPublicationError::Fenced(
                    "publication head was superseded".to_string(),
                ));
            }
            _ => {
                return Err(SnapshotPublicationError::InvalidState(
                    "publication requires a claimed head".to_string(),
                ));
            }
        };
        if current.head.fencing_token() != lease.fencing_token()
            || current.head.holder_id != lease.holder_id
        {
            *state = PublicationState::Fenced;
            return Err(SnapshotPublicationError::Fenced(format!(
                "lease {} generation {} does not own head generation {}",
                lease.holder_id, lease.generation, current.head.lease_generation
            )));
        }

        let publication_sequence = current
            .head
            .publication_sequence
            .checked_add(1)
            .ok_or_else(|| {
                SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
            })?;
        let snapshot_key = reddb_file::serverless_snapshot_key(
            &self.database_key,
            lease.generation,
            publication_sequence,
        );
        self.backend
            .upload_conditional(local_snapshot, &snapshot_key, ConditionalPut::IfAbsent)?;

        let mut next = current.head;
        next.publication_sequence = publication_sequence;
        next.snapshot_key = snapshot_key;
        match self.publish_head(&next, ConditionalPut::IfVersion(current.version)) {
            Ok(version) => {
                *state = PublicationState::Claimed(VersionedHead {
                    head: next,
                    version,
                });
                Ok(())
            }
            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
                *state = PublicationState::Fenced;
                Err(SnapshotPublicationError::Fenced(message))
            }
            Err(err) => Err(err),
        }
    }

    /// Head observed at boot (or claimed since). Generation restore reads the
    /// generation pointer and stream ownership from it.
    pub fn observed_head(&self) -> Option<reddb_file::ServerlessSnapshotHead> {
        let state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        match &*state {
            PublicationState::Observed(Some(head)) | PublicationState::Claimed(head) => {
                Some(head.head.clone())
            }
            _ => None,
        }
    }

    /// The publication sequence the boot claim will install. Generation mode
    /// uses it as the writer's WAL stream epoch: it is unique per claim and
    /// strictly greater than every earlier claim and publication on this head.
    pub fn next_claim_epoch(&self) -> Result<u64, SnapshotPublicationError> {
        let state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        match &*state {
            PublicationState::Observed(Some(head)) => head
                .head
                .publication_sequence
                .checked_add(1)
                .ok_or_else(|| SnapshotPublicationError::InvalidState("sequence exhausted".into())),
            PublicationState::Observed(None) => Ok(1),
            PublicationState::Fenced => Err(SnapshotPublicationError::Fenced(
                "publication head was already superseded".to_string(),
            )),
            _ => Err(SnapshotPublicationError::InvalidState(
                "head must be observed and unclaimed".to_string(),
            )),
        }
    }

    /// The publication sequence the next `publish_generation` will install.
    pub fn next_publication_sequence(&self) -> Result<u64, SnapshotPublicationError> {
        let state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        match &*state {
            PublicationState::Claimed(head) => head
                .head
                .publication_sequence
                .checked_add(1)
                .ok_or_else(|| SnapshotPublicationError::InvalidState("sequence exhausted".into())),
            PublicationState::Fenced => Err(SnapshotPublicationError::Fenced(
                "publication head was superseded".to_string(),
            )),
            _ => Err(SnapshotPublicationError::InvalidState(
                "publication requires a claimed head".to_string(),
            )),
        }
    }

    /// Claim the observed head for a generation-mode writer. The claim bumps
    /// the publication sequence (the writer's stream epoch) and records that
    /// this epoch owns the archive stream from `stream_start_lsn` on. A first
    /// boot, or a migration from a single-file head, installs `initial`.
    pub fn claim_generation_stream(
        &self,
        lease: &WriterLease,
        stream_start_lsn: u64,
        initial: Option<&GenerationPointer>,
    ) -> Result<u64, SnapshotPublicationError> {
        let mut state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        let observed = match &*state {
            PublicationState::Observed(observed) => observed.clone(),
            PublicationState::Fenced => {
                return Err(SnapshotPublicationError::Fenced(
                    "publication head was already superseded".to_string(),
                ));
            }
            _ => {
                return Err(SnapshotPublicationError::InvalidState(
                    "head must be observed and unclaimed".to_string(),
                ));
            }
        };
        let (next, condition) = match observed {
            Some(current) => {
                if current.head.database_key != self.database_key {
                    return Err(SnapshotPublicationError::InvalidState(format!(
                        "head database '{}' does not match '{}'",
                        current.head.database_key, self.database_key
                    )));
                }
                let mut next = current.head;
                next.publication_sequence =
                    next.publication_sequence.checked_add(1).ok_or_else(|| {
                        SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
                    })?;
                next.holder_id = lease.holder_id.clone();
                next.term = lease.term;
                next.lease_generation = lease.generation;
                let epoch = next.publication_sequence;
                match (initial, next.generation.take()) {
                    (Some(pointer), _) => {
                        next.snapshot_key = pointer.data_key.clone();
                        next.generation = Some(pointer.as_ref_for_new_stream(epoch));
                    }
                    (None, Some(mut generation)) => {
                        generation.wal_epochs.push(reddb_file::ServerlessWalEpoch {
                            epoch,
                            start_lsn: stream_start_lsn,
                        });
                        next.generation = Some(generation);
                    }
                    (None, None) => {
                        return Err(SnapshotPublicationError::InvalidState(
                            "a single-file snapshot head needs an initial generation".into(),
                        ));
                    }
                }
                (next, ConditionalPut::IfVersion(current.version))
            }
            None => {
                let pointer = initial.ok_or_else(|| {
                    SnapshotPublicationError::InvalidState(
                        "first generation-mode boot needs an initial generation".into(),
                    )
                })?;
                (
                    reddb_file::ServerlessSnapshotHead {
                        database_key: self.database_key.clone(),
                        holder_id: lease.holder_id.clone(),
                        term: lease.term,
                        lease_generation: lease.generation,
                        publication_sequence: 1,
                        snapshot_key: pointer.data_key.clone(),
                        generation: Some(pointer.as_ref_for_new_stream(1)),
                    },
                    ConditionalPut::IfAbsent,
                )
            }
        };
        let epoch = next.publication_sequence;
        match self.publish_head(&next, condition) {
            Ok(version) => {
                *state = PublicationState::Claimed(VersionedHead {
                    head: next,
                    version,
                });
                Ok(epoch)
            }
            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
                *state = PublicationState::Fenced;
                Err(SnapshotPublicationError::Fenced(message))
            }
            Err(err) => Err(err),
        }
    }

    /// Make an uploaded generation current. Returns the head it replaced so
    /// the caller can garbage-collect objects older than the previous
    /// generation. Fails with `Fenced` once a successor claimed the head.
    pub fn publish_generation(
        &self,
        lease: &WriterLease,
        pointer: &GenerationPointer,
    ) -> Result<reddb_file::ServerlessSnapshotHead, SnapshotPublicationError> {
        let mut state = self
            .state
            .lock()
            .expect("poisoned snapshot publication state");
        let current = match &*state {
            PublicationState::Claimed(current) => current.clone(),
            PublicationState::Fenced => {
                return Err(SnapshotPublicationError::Fenced(
                    "publication head was superseded".to_string(),
                ));
            }
            _ => {
                return Err(SnapshotPublicationError::InvalidState(
                    "publication requires a claimed head".to_string(),
                ));
            }
        };
        if current.head.fencing_token() != lease.fencing_token()
            || current.head.holder_id != lease.holder_id
        {
            *state = PublicationState::Fenced;
            return Err(SnapshotPublicationError::Fenced(format!(
                "lease {} generation {} does not own head generation {}",
                lease.holder_id, lease.generation, current.head.lease_generation
            )));
        }
        let mut next = current.head.clone();
        next.publication_sequence = next.publication_sequence.checked_add(1).ok_or_else(|| {
            SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
        })?;
        next.snapshot_key = pointer.data_key.clone();
        let generation = next.generation.as_mut().ok_or_else(|| {
            SnapshotPublicationError::InvalidState("claimed head has no generation".into())
        })?;
        if pointer.wal_lsn < generation.wal_lsn {
            return Err(SnapshotPublicationError::InvalidState(format!(
                "generation at stream LSN {} would move the head back from {}",
                pointer.wal_lsn, generation.wal_lsn
            )));
        }
        generation.manifest_key = pointer.manifest_key.clone();
        generation.wal_lsn = pointer.wal_lsn;
        prune_wal_epochs(generation);
        match self.publish_head(&next, ConditionalPut::IfVersion(current.version)) {
            Ok(version) => {
                *state = PublicationState::Claimed(VersionedHead {
                    head: next,
                    version,
                });
                Ok(current.head)
            }
            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
                *state = PublicationState::Fenced;
                Err(SnapshotPublicationError::Fenced(message))
            }
            Err(err) => Err(err),
        }
    }

    pub fn database_key(&self) -> &str {
        &self.database_key
    }

    fn read_versioned_head(&self) -> Result<Option<VersionedHead>, SnapshotPublicationError> {
        let before = match self.backend.object_version(&self.head_key)? {
            Some(version) => version,
            None => return Ok(None),
        };
        let temp = reddb_file::ServerlessWriterLeaseTempFile::new("snapshot-head-read");
        if !self.backend.download(&self.head_key, temp.path())? {
            return Ok(None);
        }
        if self.backend.object_version(&self.head_key)?.as_ref() != Some(&before) {
            return Err(SnapshotPublicationError::Backend(
                BackendError::PreconditionFailed(
                    "serverless snapshot head changed while being read".to_string(),
                ),
            ));
        }
        let bytes = temp
            .read_bytes()
            .map_err(|err| BackendError::Transport(err.to_string()))?;
        let head = reddb_file::decode_serverless_snapshot_head_json(&bytes)
            .map_err(|err| BackendError::Internal(err.to_string()))?;
        Ok(Some(VersionedHead {
            head,
            version: before,
        }))
    }

    fn publish_head(
        &self,
        head: &reddb_file::ServerlessSnapshotHead,
        condition: ConditionalPut,
    ) -> Result<BackendObjectVersion, SnapshotPublicationError> {
        let bytes = reddb_file::encode_serverless_snapshot_head_json(head)
            .map_err(|err| BackendError::Internal(err.to_string()))?;
        let temp = reddb_file::ServerlessWriterLeaseTempFile::new("snapshot-head-write");
        temp.write_bytes(&bytes)
            .map_err(|err| BackendError::Transport(err.to_string()))?;
        Ok(self
            .backend
            .upload_conditional(temp.path(), &self.head_key, condition)?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::backend::LocalBackend;

    fn lease(holder: &str, generation: u64) -> WriterLease {
        WriterLease {
            database_key: "main".to_string(),
            holder_id: holder.to_string(),
            term: 1,
            generation,
            acquired_at_ms: 1,
            expires_at_ms: u64::MAX,
        }
    }

    fn read_current_snapshot(database_key: &str) -> Vec<u8> {
        let head_path = reddb_file::serverless_snapshot_head_key(database_key);
        let head_bytes = std::fs::read(head_path).expect("read publication head");
        let head = reddb_file::decode_serverless_snapshot_head_json(&head_bytes)
            .expect("decode publication head");
        std::fs::read(head.snapshot_key).expect("read current immutable snapshot")
    }

    #[test]
    fn successor_claim_fences_delayed_old_writer_publication() {
        let root = tempfile::tempdir().expect("publication directory");
        let database_key = root.path().join("remote").join("main.rdb");
        let database_key = database_key.to_string_lossy().to_string();
        let old_local = root.path().join("old.rdb");
        let new_local = root.path().join("new.rdb");
        std::fs::write(&old_local, b"old-snapshot").expect("write old local snapshot");
        std::fs::write(&new_local, b"new-snapshot").expect("write new local snapshot");

        let old = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        assert_eq!(old.observe_for_boot().expect("observe empty head"), None);
        old.claim(&lease("old", 1), &old_local)
            .expect("old writer claims initial head");

        let successor = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        assert!(successor
            .observe_for_boot()
            .expect("observe old head")
            .is_some());
        successor
            .claim(&lease("new", 2), &old_local)
            .expect("successor claims head under new generation");

        assert!(matches!(
            old.publish(&lease("old", 1), &old_local),
            Err(SnapshotPublicationError::Fenced(_))
        ));
        successor
            .publish(&lease("new", 2), &new_local)
            .expect("successor publishes current snapshot");
        assert_eq!(read_current_snapshot(&database_key), b"new-snapshot");
    }

    #[test]
    fn reused_lease_identity_cannot_restore_an_old_heads_cas_version() {
        let root = tempfile::tempdir().expect("publication directory");
        let database_key = root.path().join("main.rdb").to_string_lossy().to_string();
        let local = root.path().join("local.rdb");
        std::fs::write(&local, b"committed").expect("local snapshot");
        let old = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        old.observe_for_boot().expect("observe first boot");
        old.claim(&lease("same-holder", 1), &local)
            .expect("first claim");
        // A clean release removes the lease key. Even with the same holder,
        // term and generation, the next boot must change the HEAD CAS version.
        let successor = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        successor.observe_for_boot().expect("observe next boot");
        successor
            .claim(&lease("same-holder", 1), &local)
            .expect("reused identity claims");
        std::fs::write(&local, b"stale").expect("old writer resumes");
        assert!(matches!(
            old.publish(&lease("same-holder", 1), &local),
            Err(SnapshotPublicationError::Fenced(_))
        ));
        assert_eq!(read_current_snapshot(&database_key), b"committed");
    }

    fn pointer(tag: &str, wal_lsn: u64) -> GenerationPointer {
        GenerationPointer {
            manifest_key: format!("gen/{tag}/MANIFEST.json"),
            data_key: format!("gen/{tag}/files/data.rdb"),
            wal_lsn,
        }
    }

    #[test]
    fn generation_claims_record_stream_ownership_and_fence_stale_writers() {
        let root = tempfile::tempdir().expect("publication directory");
        let database_key = root.path().join("main.rdb").to_string_lossy().to_string();
        let first = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        first.observe_for_boot().expect("observe empty head");
        assert_eq!(first.next_claim_epoch().unwrap(), 1);
        let epoch_a = first
            .claim_generation_stream(&lease("a", 1), 1, Some(&pointer("a1", 0)))
            .expect("first boot claims with its initial generation");
        assert_eq!(epoch_a, 1);
        first
            .publish_generation(&lease("a", 1), &pointer("a2", 40))
            .expect("writer publishes a later generation");

        let successor = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        successor.observe_for_boot().expect("observe a's head");
        let epoch_b = successor
            .claim_generation_stream(&lease("b", 2), 58, None)
            .expect("successor claims the stream after restoring through 57");
        assert!(epoch_b > epoch_a);
        let head = successor.observed_head().expect("claimed head");
        let generation = head.generation.expect("generation head");
        assert_eq!(generation.wal_lsn, 40);
        assert_eq!(generation.owner_of(57), Some(epoch_a));
        assert_eq!(generation.owner_of(58), Some(epoch_b));

        // The stale writer can no longer move the head.
        assert!(matches!(
            first.publish_generation(&lease("a", 1), &pointer("a3", 60)),
            Err(SnapshotPublicationError::Fenced(_))
        ));
        // Once a generation covers the old epoch's range, it is pruned.
        successor
            .publish_generation(&lease("b", 2), &pointer("b1", 70))
            .expect("successor publishes");
        let generation = successor.observed_head().unwrap().generation.unwrap();
        assert_eq!(generation.wal_epochs.len(), 1);
        assert_eq!(generation.wal_epochs[0].epoch, epoch_b);
        assert!(matches!(
            successor.publish_generation(&lease("b", 2), &pointer("b0", 69)),
            Err(SnapshotPublicationError::InvalidState(_))
        ));
    }

    #[test]
    fn boot_claim_fails_when_head_advanced_during_hydration() {
        let root = tempfile::tempdir().expect("publication directory");
        let database_key = root.path().join("remote").join("main.rdb");
        let database_key = database_key.to_string_lossy().to_string();
        let first = root.path().join("first.rdb");
        let second = root.path().join("second.rdb");
        std::fs::write(&first, b"first").expect("write first snapshot");
        std::fs::write(&second, b"second").expect("write second snapshot");

        let writer = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
        writer.observe_for_boot().expect("observe empty head");
        writer
            .claim(&lease("writer", 1), &first)
            .expect("claim first head");

        let booting = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key);
        booting.observe_for_boot().expect("observe first head");
        writer
            .publish(&lease("writer", 1), &second)
            .expect("advance head while successor hydrates");

        assert!(matches!(
            booting.claim(&lease("successor", 2), &first),
            Err(SnapshotPublicationError::Fenced(_))
        ));
    }
}