Skip to main content

reddb_server/runtime/
serverless_snapshot_publication.rs

1//! Lease-generation-fenced publication of serverless snapshots.
2//!
3//! Payloads are uploaded under immutable keys. Only the small `HEAD.json`
4//! pointer is mutable, and every owner claims and advances it with backend CAS.
5//! A stale process may finish an expensive payload upload after its lease has
6//! expired, but it cannot make that payload current after a successor claims
7//! the head under a newer lease generation.
8
9use std::path::Path;
10use std::sync::{Arc, Mutex};
11
12use crate::replication::lease::WriterLease;
13use crate::storage::backend::{
14    AtomicRemoteBackend, BackendError, BackendObjectVersion, ConditionalPut,
15};
16
17#[derive(Debug)]
18pub enum SnapshotPublicationError {
19    Backend(BackendError),
20    InvalidState(String),
21    Fenced(String),
22}
23
24impl std::fmt::Display for SnapshotPublicationError {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        match self {
27            Self::Backend(err) => write!(f, "snapshot publication backend error: {err}"),
28            Self::InvalidState(message) => write!(f, "snapshot publication state error: {message}"),
29            Self::Fenced(message) => write!(f, "snapshot publication fenced: {message}"),
30        }
31    }
32}
33
34impl std::error::Error for SnapshotPublicationError {}
35
36impl From<BackendError> for SnapshotPublicationError {
37    fn from(value: BackendError) -> Self {
38        Self::Backend(value)
39    }
40}
41
42/// An uploaded generation a writer is about to make current.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct GenerationPointer {
45    pub manifest_key: String,
46    /// Object key of the generation's main data file (`snapshot_key`).
47    pub data_key: String,
48    pub wal_lsn: u64,
49}
50
51impl GenerationPointer {
52    fn as_ref_for_new_stream(&self, epoch: u64) -> reddb_file::ServerlessGenerationRef {
53        reddb_file::ServerlessGenerationRef {
54            manifest_key: self.manifest_key.clone(),
55            wal_lsn: self.wal_lsn,
56            wal_epochs: vec![reddb_file::ServerlessWalEpoch {
57                epoch,
58                start_lsn: 1,
59            }],
60        }
61    }
62}
63
64/// Drop claims whose whole range is already inside the generation; the claim
65/// that owns `wal_lsn + 1` and every later claim stay.
66fn prune_wal_epochs(generation: &mut reddb_file::ServerlessGenerationRef) {
67    let first_needed = generation.wal_lsn.saturating_add(1);
68    while generation.wal_epochs.len() > 1 && generation.wal_epochs[1].start_lsn <= first_needed {
69        generation.wal_epochs.remove(0);
70    }
71}
72
73#[derive(Clone)]
74struct VersionedHead {
75    head: reddb_file::ServerlessSnapshotHead,
76    version: BackendObjectVersion,
77}
78
79enum PublicationState {
80    Unobserved,
81    Observed(Option<VersionedHead>),
82    Claimed(VersionedHead),
83    Fenced,
84}
85
86pub struct SnapshotPublicationStore {
87    backend: Arc<dyn AtomicRemoteBackend>,
88    database_key: String,
89    head_key: String,
90    state: Mutex<PublicationState>,
91}
92
93impl SnapshotPublicationStore {
94    pub fn new(backend: Arc<dyn AtomicRemoteBackend>, database_key: impl Into<String>) -> Self {
95        let database_key = database_key.into();
96        let head_key = reddb_file::serverless_snapshot_head_key(&database_key);
97        Self {
98            backend,
99            database_key,
100            head_key,
101            state: Mutex::new(PublicationState::Unobserved),
102        }
103    }
104
105    /// Observe the exact head version used to hydrate this boot. The later
106    /// claim must CAS this version; if publication advances while the runtime
107    /// is opening, the claim fails and boot retries from the newer snapshot.
108    pub fn observe_for_boot(&self) -> Result<Option<String>, SnapshotPublicationError> {
109        let mut state = self
110            .state
111            .lock()
112            .expect("poisoned snapshot publication state");
113        match &*state {
114            PublicationState::Unobserved => {}
115            PublicationState::Observed(head) => {
116                return Ok(head.as_ref().map(|head| head.head.snapshot_key.clone()));
117            }
118            PublicationState::Claimed(head) => {
119                return Ok(Some(head.head.snapshot_key.clone()));
120            }
121            PublicationState::Fenced => {
122                return Err(SnapshotPublicationError::Fenced(
123                    "publication head was already superseded".to_string(),
124                ));
125            }
126        }
127
128        let observed = self.read_versioned_head()?;
129        let snapshot_key = observed.as_ref().map(|head| head.head.snapshot_key.clone());
130        *state = PublicationState::Observed(observed);
131        Ok(snapshot_key)
132    }
133
134    /// Claim the observed head for `lease`. On the first serverless boot there
135    /// is no head yet, so the already-open local database is uploaded once as
136    /// an initial immutable snapshot and installed with `IfAbsent`.
137    pub fn claim(
138        &self,
139        lease: &WriterLease,
140        local_snapshot: &Path,
141    ) -> Result<(), SnapshotPublicationError> {
142        let mut state = self
143            .state
144            .lock()
145            .expect("poisoned snapshot publication state");
146        let observed = match &*state {
147            PublicationState::Observed(observed) => observed.clone(),
148            PublicationState::Unobserved => {
149                return Err(SnapshotPublicationError::InvalidState(
150                    "head must be observed before lease acquisition".to_string(),
151                ));
152            }
153            PublicationState::Claimed(_) => {
154                return Err(SnapshotPublicationError::InvalidState(
155                    "head is already claimed".to_string(),
156                ));
157            }
158            PublicationState::Fenced => {
159                return Err(SnapshotPublicationError::Fenced(
160                    "publication head was already superseded".to_string(),
161                ));
162            }
163        };
164
165        let (next, condition) = match observed {
166            Some(current) => {
167                if current.head.database_key != self.database_key {
168                    return Err(SnapshotPublicationError::InvalidState(format!(
169                        "head database '{}' does not match '{}'",
170                        current.head.database_key, self.database_key
171                    )));
172                }
173                let mut next = current.head;
174                // Release deletes the lease object, so generations may repeat.
175                // Reserve a sequence on every claim to avoid both payload-key
176                // reuse and identical HEAD bytes (ABA) across clean restarts.
177                next.publication_sequence =
178                    next.publication_sequence.checked_add(1).ok_or_else(|| {
179                        SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
180                    })?;
181                next.holder_id = lease.holder_id.clone();
182                next.term = lease.term;
183                next.lease_generation = lease.generation;
184                (next, ConditionalPut::IfVersion(current.version))
185            }
186            None => {
187                let publication_sequence = 1;
188                let snapshot_key = reddb_file::serverless_snapshot_key(
189                    &self.database_key,
190                    lease.generation,
191                    publication_sequence,
192                );
193                self.backend.upload_conditional(
194                    local_snapshot,
195                    &snapshot_key,
196                    ConditionalPut::IfAbsent,
197                )?;
198                (
199                    reddb_file::ServerlessSnapshotHead {
200                        database_key: self.database_key.clone(),
201                        holder_id: lease.holder_id.clone(),
202                        term: lease.term,
203                        lease_generation: lease.generation,
204                        publication_sequence,
205                        snapshot_key,
206                        generation: None,
207                    },
208                    ConditionalPut::IfAbsent,
209                )
210            }
211        };
212
213        match self.publish_head(&next, condition) {
214            Ok(version) => {
215                *state = PublicationState::Claimed(VersionedHead {
216                    head: next,
217                    version,
218                });
219                Ok(())
220            }
221            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
222                *state = PublicationState::Fenced;
223                Err(SnapshotPublicationError::Fenced(message))
224            }
225            Err(err) => Err(err),
226        }
227    }
228
229    pub fn publish(
230        &self,
231        lease: &WriterLease,
232        local_snapshot: &Path,
233    ) -> Result<(), SnapshotPublicationError> {
234        let mut state = self
235            .state
236            .lock()
237            .expect("poisoned snapshot publication state");
238        let current = match &*state {
239            PublicationState::Claimed(current) => current.clone(),
240            PublicationState::Fenced => {
241                return Err(SnapshotPublicationError::Fenced(
242                    "publication head was superseded".to_string(),
243                ));
244            }
245            _ => {
246                return Err(SnapshotPublicationError::InvalidState(
247                    "publication requires a claimed head".to_string(),
248                ));
249            }
250        };
251        if current.head.fencing_token() != lease.fencing_token()
252            || current.head.holder_id != lease.holder_id
253        {
254            *state = PublicationState::Fenced;
255            return Err(SnapshotPublicationError::Fenced(format!(
256                "lease {} generation {} does not own head generation {}",
257                lease.holder_id, lease.generation, current.head.lease_generation
258            )));
259        }
260
261        let publication_sequence = current
262            .head
263            .publication_sequence
264            .checked_add(1)
265            .ok_or_else(|| {
266                SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
267            })?;
268        let snapshot_key = reddb_file::serverless_snapshot_key(
269            &self.database_key,
270            lease.generation,
271            publication_sequence,
272        );
273        self.backend
274            .upload_conditional(local_snapshot, &snapshot_key, ConditionalPut::IfAbsent)?;
275
276        let mut next = current.head;
277        next.publication_sequence = publication_sequence;
278        next.snapshot_key = snapshot_key;
279        match self.publish_head(&next, ConditionalPut::IfVersion(current.version)) {
280            Ok(version) => {
281                *state = PublicationState::Claimed(VersionedHead {
282                    head: next,
283                    version,
284                });
285                Ok(())
286            }
287            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
288                *state = PublicationState::Fenced;
289                Err(SnapshotPublicationError::Fenced(message))
290            }
291            Err(err) => Err(err),
292        }
293    }
294
295    /// Head observed at boot (or claimed since). Generation restore reads the
296    /// generation pointer and stream ownership from it.
297    pub fn observed_head(&self) -> Option<reddb_file::ServerlessSnapshotHead> {
298        let state = self
299            .state
300            .lock()
301            .expect("poisoned snapshot publication state");
302        match &*state {
303            PublicationState::Observed(Some(head)) | PublicationState::Claimed(head) => {
304                Some(head.head.clone())
305            }
306            _ => None,
307        }
308    }
309
310    /// The publication sequence the boot claim will install. Generation mode
311    /// uses it as the writer's WAL stream epoch: it is unique per claim and
312    /// strictly greater than every earlier claim and publication on this head.
313    pub fn next_claim_epoch(&self) -> Result<u64, SnapshotPublicationError> {
314        let state = self
315            .state
316            .lock()
317            .expect("poisoned snapshot publication state");
318        match &*state {
319            PublicationState::Observed(Some(head)) => head
320                .head
321                .publication_sequence
322                .checked_add(1)
323                .ok_or_else(|| SnapshotPublicationError::InvalidState("sequence exhausted".into())),
324            PublicationState::Observed(None) => Ok(1),
325            PublicationState::Fenced => Err(SnapshotPublicationError::Fenced(
326                "publication head was already superseded".to_string(),
327            )),
328            _ => Err(SnapshotPublicationError::InvalidState(
329                "head must be observed and unclaimed".to_string(),
330            )),
331        }
332    }
333
334    /// The publication sequence the next `publish_generation` will install.
335    pub fn next_publication_sequence(&self) -> Result<u64, SnapshotPublicationError> {
336        let state = self
337            .state
338            .lock()
339            .expect("poisoned snapshot publication state");
340        match &*state {
341            PublicationState::Claimed(head) => head
342                .head
343                .publication_sequence
344                .checked_add(1)
345                .ok_or_else(|| SnapshotPublicationError::InvalidState("sequence exhausted".into())),
346            PublicationState::Fenced => Err(SnapshotPublicationError::Fenced(
347                "publication head was superseded".to_string(),
348            )),
349            _ => Err(SnapshotPublicationError::InvalidState(
350                "publication requires a claimed head".to_string(),
351            )),
352        }
353    }
354
355    /// Claim the observed head for a generation-mode writer. The claim bumps
356    /// the publication sequence (the writer's stream epoch) and records that
357    /// this epoch owns the archive stream from `stream_start_lsn` on. A first
358    /// boot, or a migration from a single-file head, installs `initial`.
359    pub fn claim_generation_stream(
360        &self,
361        lease: &WriterLease,
362        stream_start_lsn: u64,
363        initial: Option<&GenerationPointer>,
364    ) -> Result<u64, SnapshotPublicationError> {
365        let mut state = self
366            .state
367            .lock()
368            .expect("poisoned snapshot publication state");
369        let observed = match &*state {
370            PublicationState::Observed(observed) => observed.clone(),
371            PublicationState::Fenced => {
372                return Err(SnapshotPublicationError::Fenced(
373                    "publication head was already superseded".to_string(),
374                ));
375            }
376            _ => {
377                return Err(SnapshotPublicationError::InvalidState(
378                    "head must be observed and unclaimed".to_string(),
379                ));
380            }
381        };
382        let (next, condition) = match observed {
383            Some(current) => {
384                if current.head.database_key != self.database_key {
385                    return Err(SnapshotPublicationError::InvalidState(format!(
386                        "head database '{}' does not match '{}'",
387                        current.head.database_key, self.database_key
388                    )));
389                }
390                let mut next = current.head;
391                next.publication_sequence =
392                    next.publication_sequence.checked_add(1).ok_or_else(|| {
393                        SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
394                    })?;
395                next.holder_id = lease.holder_id.clone();
396                next.term = lease.term;
397                next.lease_generation = lease.generation;
398                let epoch = next.publication_sequence;
399                match (initial, next.generation.take()) {
400                    (Some(pointer), _) => {
401                        next.snapshot_key = pointer.data_key.clone();
402                        next.generation = Some(pointer.as_ref_for_new_stream(epoch));
403                    }
404                    (None, Some(mut generation)) => {
405                        generation.wal_epochs.push(reddb_file::ServerlessWalEpoch {
406                            epoch,
407                            start_lsn: stream_start_lsn,
408                        });
409                        next.generation = Some(generation);
410                    }
411                    (None, None) => {
412                        return Err(SnapshotPublicationError::InvalidState(
413                            "a single-file snapshot head needs an initial generation".into(),
414                        ));
415                    }
416                }
417                (next, ConditionalPut::IfVersion(current.version))
418            }
419            None => {
420                let pointer = initial.ok_or_else(|| {
421                    SnapshotPublicationError::InvalidState(
422                        "first generation-mode boot needs an initial generation".into(),
423                    )
424                })?;
425                (
426                    reddb_file::ServerlessSnapshotHead {
427                        database_key: self.database_key.clone(),
428                        holder_id: lease.holder_id.clone(),
429                        term: lease.term,
430                        lease_generation: lease.generation,
431                        publication_sequence: 1,
432                        snapshot_key: pointer.data_key.clone(),
433                        generation: Some(pointer.as_ref_for_new_stream(1)),
434                    },
435                    ConditionalPut::IfAbsent,
436                )
437            }
438        };
439        let epoch = next.publication_sequence;
440        match self.publish_head(&next, condition) {
441            Ok(version) => {
442                *state = PublicationState::Claimed(VersionedHead {
443                    head: next,
444                    version,
445                });
446                Ok(epoch)
447            }
448            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
449                *state = PublicationState::Fenced;
450                Err(SnapshotPublicationError::Fenced(message))
451            }
452            Err(err) => Err(err),
453        }
454    }
455
456    /// Make an uploaded generation current. Returns the head it replaced so
457    /// the caller can garbage-collect objects older than the previous
458    /// generation. Fails with `Fenced` once a successor claimed the head.
459    pub fn publish_generation(
460        &self,
461        lease: &WriterLease,
462        pointer: &GenerationPointer,
463    ) -> Result<reddb_file::ServerlessSnapshotHead, SnapshotPublicationError> {
464        let mut state = self
465            .state
466            .lock()
467            .expect("poisoned snapshot publication state");
468        let current = match &*state {
469            PublicationState::Claimed(current) => current.clone(),
470            PublicationState::Fenced => {
471                return Err(SnapshotPublicationError::Fenced(
472                    "publication head was superseded".to_string(),
473                ));
474            }
475            _ => {
476                return Err(SnapshotPublicationError::InvalidState(
477                    "publication requires a claimed head".to_string(),
478                ));
479            }
480        };
481        if current.head.fencing_token() != lease.fencing_token()
482            || current.head.holder_id != lease.holder_id
483        {
484            *state = PublicationState::Fenced;
485            return Err(SnapshotPublicationError::Fenced(format!(
486                "lease {} generation {} does not own head generation {}",
487                lease.holder_id, lease.generation, current.head.lease_generation
488            )));
489        }
490        let mut next = current.head.clone();
491        next.publication_sequence = next.publication_sequence.checked_add(1).ok_or_else(|| {
492            SnapshotPublicationError::InvalidState("snapshot sequence exhausted".into())
493        })?;
494        next.snapshot_key = pointer.data_key.clone();
495        let generation = next.generation.as_mut().ok_or_else(|| {
496            SnapshotPublicationError::InvalidState("claimed head has no generation".into())
497        })?;
498        if pointer.wal_lsn < generation.wal_lsn {
499            return Err(SnapshotPublicationError::InvalidState(format!(
500                "generation at stream LSN {} would move the head back from {}",
501                pointer.wal_lsn, generation.wal_lsn
502            )));
503        }
504        generation.manifest_key = pointer.manifest_key.clone();
505        generation.wal_lsn = pointer.wal_lsn;
506        prune_wal_epochs(generation);
507        match self.publish_head(&next, ConditionalPut::IfVersion(current.version)) {
508            Ok(version) => {
509                *state = PublicationState::Claimed(VersionedHead {
510                    head: next,
511                    version,
512                });
513                Ok(current.head)
514            }
515            Err(SnapshotPublicationError::Backend(BackendError::PreconditionFailed(message))) => {
516                *state = PublicationState::Fenced;
517                Err(SnapshotPublicationError::Fenced(message))
518            }
519            Err(err) => Err(err),
520        }
521    }
522
523    pub fn database_key(&self) -> &str {
524        &self.database_key
525    }
526
527    fn read_versioned_head(&self) -> Result<Option<VersionedHead>, SnapshotPublicationError> {
528        let before = match self.backend.object_version(&self.head_key)? {
529            Some(version) => version,
530            None => return Ok(None),
531        };
532        let temp = reddb_file::ServerlessWriterLeaseTempFile::new("snapshot-head-read");
533        if !self.backend.download(&self.head_key, temp.path())? {
534            return Ok(None);
535        }
536        if self.backend.object_version(&self.head_key)?.as_ref() != Some(&before) {
537            return Err(SnapshotPublicationError::Backend(
538                BackendError::PreconditionFailed(
539                    "serverless snapshot head changed while being read".to_string(),
540                ),
541            ));
542        }
543        let bytes = temp
544            .read_bytes()
545            .map_err(|err| BackendError::Transport(err.to_string()))?;
546        let head = reddb_file::decode_serverless_snapshot_head_json(&bytes)
547            .map_err(|err| BackendError::Internal(err.to_string()))?;
548        Ok(Some(VersionedHead {
549            head,
550            version: before,
551        }))
552    }
553
554    fn publish_head(
555        &self,
556        head: &reddb_file::ServerlessSnapshotHead,
557        condition: ConditionalPut,
558    ) -> Result<BackendObjectVersion, SnapshotPublicationError> {
559        let bytes = reddb_file::encode_serverless_snapshot_head_json(head)
560            .map_err(|err| BackendError::Internal(err.to_string()))?;
561        let temp = reddb_file::ServerlessWriterLeaseTempFile::new("snapshot-head-write");
562        temp.write_bytes(&bytes)
563            .map_err(|err| BackendError::Transport(err.to_string()))?;
564        Ok(self
565            .backend
566            .upload_conditional(temp.path(), &self.head_key, condition)?)
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573    use crate::storage::backend::LocalBackend;
574
575    fn lease(holder: &str, generation: u64) -> WriterLease {
576        WriterLease {
577            database_key: "main".to_string(),
578            holder_id: holder.to_string(),
579            term: 1,
580            generation,
581            acquired_at_ms: 1,
582            expires_at_ms: u64::MAX,
583        }
584    }
585
586    fn read_current_snapshot(database_key: &str) -> Vec<u8> {
587        let head_path = reddb_file::serverless_snapshot_head_key(database_key);
588        let head_bytes = std::fs::read(head_path).expect("read publication head");
589        let head = reddb_file::decode_serverless_snapshot_head_json(&head_bytes)
590            .expect("decode publication head");
591        std::fs::read(head.snapshot_key).expect("read current immutable snapshot")
592    }
593
594    #[test]
595    fn successor_claim_fences_delayed_old_writer_publication() {
596        let root = tempfile::tempdir().expect("publication directory");
597        let database_key = root.path().join("remote").join("main.rdb");
598        let database_key = database_key.to_string_lossy().to_string();
599        let old_local = root.path().join("old.rdb");
600        let new_local = root.path().join("new.rdb");
601        std::fs::write(&old_local, b"old-snapshot").expect("write old local snapshot");
602        std::fs::write(&new_local, b"new-snapshot").expect("write new local snapshot");
603
604        let old = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
605        assert_eq!(old.observe_for_boot().expect("observe empty head"), None);
606        old.claim(&lease("old", 1), &old_local)
607            .expect("old writer claims initial head");
608
609        let successor = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
610        assert!(successor
611            .observe_for_boot()
612            .expect("observe old head")
613            .is_some());
614        successor
615            .claim(&lease("new", 2), &old_local)
616            .expect("successor claims head under new generation");
617
618        assert!(matches!(
619            old.publish(&lease("old", 1), &old_local),
620            Err(SnapshotPublicationError::Fenced(_))
621        ));
622        successor
623            .publish(&lease("new", 2), &new_local)
624            .expect("successor publishes current snapshot");
625        assert_eq!(read_current_snapshot(&database_key), b"new-snapshot");
626    }
627
628    #[test]
629    fn reused_lease_identity_cannot_restore_an_old_heads_cas_version() {
630        let root = tempfile::tempdir().expect("publication directory");
631        let database_key = root.path().join("main.rdb").to_string_lossy().to_string();
632        let local = root.path().join("local.rdb");
633        std::fs::write(&local, b"committed").expect("local snapshot");
634        let old = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
635        old.observe_for_boot().expect("observe first boot");
636        old.claim(&lease("same-holder", 1), &local)
637            .expect("first claim");
638        // A clean release removes the lease key. Even with the same holder,
639        // term and generation, the next boot must change the HEAD CAS version.
640        let successor = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
641        successor.observe_for_boot().expect("observe next boot");
642        successor
643            .claim(&lease("same-holder", 1), &local)
644            .expect("reused identity claims");
645        std::fs::write(&local, b"stale").expect("old writer resumes");
646        assert!(matches!(
647            old.publish(&lease("same-holder", 1), &local),
648            Err(SnapshotPublicationError::Fenced(_))
649        ));
650        assert_eq!(read_current_snapshot(&database_key), b"committed");
651    }
652
653    fn pointer(tag: &str, wal_lsn: u64) -> GenerationPointer {
654        GenerationPointer {
655            manifest_key: format!("gen/{tag}/MANIFEST.json"),
656            data_key: format!("gen/{tag}/files/data.rdb"),
657            wal_lsn,
658        }
659    }
660
661    #[test]
662    fn generation_claims_record_stream_ownership_and_fence_stale_writers() {
663        let root = tempfile::tempdir().expect("publication directory");
664        let database_key = root.path().join("main.rdb").to_string_lossy().to_string();
665        let first = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
666        first.observe_for_boot().expect("observe empty head");
667        assert_eq!(first.next_claim_epoch().unwrap(), 1);
668        let epoch_a = first
669            .claim_generation_stream(&lease("a", 1), 1, Some(&pointer("a1", 0)))
670            .expect("first boot claims with its initial generation");
671        assert_eq!(epoch_a, 1);
672        first
673            .publish_generation(&lease("a", 1), &pointer("a2", 40))
674            .expect("writer publishes a later generation");
675
676        let successor = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
677        successor.observe_for_boot().expect("observe a's head");
678        let epoch_b = successor
679            .claim_generation_stream(&lease("b", 2), 58, None)
680            .expect("successor claims the stream after restoring through 57");
681        assert!(epoch_b > epoch_a);
682        let head = successor.observed_head().expect("claimed head");
683        let generation = head.generation.expect("generation head");
684        assert_eq!(generation.wal_lsn, 40);
685        assert_eq!(generation.owner_of(57), Some(epoch_a));
686        assert_eq!(generation.owner_of(58), Some(epoch_b));
687
688        // The stale writer can no longer move the head.
689        assert!(matches!(
690            first.publish_generation(&lease("a", 1), &pointer("a3", 60)),
691            Err(SnapshotPublicationError::Fenced(_))
692        ));
693        // Once a generation covers the old epoch's range, it is pruned.
694        successor
695            .publish_generation(&lease("b", 2), &pointer("b1", 70))
696            .expect("successor publishes");
697        let generation = successor.observed_head().unwrap().generation.unwrap();
698        assert_eq!(generation.wal_epochs.len(), 1);
699        assert_eq!(generation.wal_epochs[0].epoch, epoch_b);
700        assert!(matches!(
701            successor.publish_generation(&lease("b", 2), &pointer("b0", 69)),
702            Err(SnapshotPublicationError::InvalidState(_))
703        ));
704    }
705
706    #[test]
707    fn boot_claim_fails_when_head_advanced_during_hydration() {
708        let root = tempfile::tempdir().expect("publication directory");
709        let database_key = root.path().join("remote").join("main.rdb");
710        let database_key = database_key.to_string_lossy().to_string();
711        let first = root.path().join("first.rdb");
712        let second = root.path().join("second.rdb");
713        std::fs::write(&first, b"first").expect("write first snapshot");
714        std::fs::write(&second, b"second").expect("write second snapshot");
715
716        let writer = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key.clone());
717        writer.observe_for_boot().expect("observe empty head");
718        writer
719            .claim(&lease("writer", 1), &first)
720            .expect("claim first head");
721
722        let booting = SnapshotPublicationStore::new(Arc::new(LocalBackend), database_key);
723        booting.observe_for_boot().expect("observe first head");
724        writer
725            .publish(&lease("writer", 1), &second)
726            .expect("advance head while successor hydrates");
727
728        assert!(matches!(
729            booting.claim(&lease("successor", 2), &first),
730            Err(SnapshotPublicationError::Fenced(_))
731        ));
732    }
733}