Skip to main content

wal_backup/replication/
snapshot.rs

1//! Snapshot management for WAL replication.
2//!
3//! # Snapshot approach
4//!
5//! We take a snapshot by checkpointing the WAL (`PRAGMA wal_checkpoint(TRUNCATE)`) then
6//! reading the database file directly, rather than using `VACUUM INTO`. This avoids:
7//!
8//! - `VACUUM INTO` failing with "output file already exists" on repeated calls
9//! - File locking issues when opening a second connection while the main connection
10//!   holds the WAL lock
11//!
12//! Trade-off: the snapshot includes free space from fragmented database pages (slightly
13//! larger uploads). A future improvement could re-add `VACUUM INTO` with unique temp
14//! paths if size is critical.
15//!
16//! # Concurrency note
17//!
18//! The snapshot opens a second SQLite connection to perform the checkpoint. If the main
19//! connection is mid-transaction, `wal_checkpoint(TRUNCATE)` will block until the
20//! transaction completes. This is acceptable because snapshots are infrequent and the
21//! main connection's transactions are typically short-lived. If blocking becomes an
22//! issue, consider using `wal_checkpoint(PASSIVE)` which is non-blocking but may not
23//! checkpoint all frames.
24
25use bytes::Bytes;
26use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
27use std::sync::Arc;
28use tokio::sync::Mutex;
29use tokio::sync::Notify;
30use tokio::time::{sleep, Instant};
31use tracing::{info, warn};
32
33use crate::config::Config;
34use crate::error::Result;
35use crate::metrics::Metrics;
36use crate::replication::manifest::{Manifest, MANIFEST_KEY};
37use crate::storage::BucketStore;
38use crate::wal::WalFile;
39
40pub struct SnapshotManager {
41    config: Config,
42    bucket: Arc<dyn BucketStore>,
43    manifest: Arc<Mutex<Manifest>>,
44    last_snapshot_time: Arc<Mutex<Instant>>,
45    trigger: Arc<Notify>,
46    snapshot_version: Arc<AtomicU64>,
47    force_next: Arc<AtomicBool>,
48    metrics: Arc<dyn Metrics>,
49    shutdown: Arc<Notify>,
50    /// Reference to the main SQLite connection. Used for checkpointing
51    /// the WAL before taking a snapshot. The main connection holds the
52    /// WAL read lock, so checkpointing through it ensures all pages are
53    /// moved from WAL to the main DB file.
54    conn: Arc<Mutex<rusqlite::Connection>>,
55}
56
57impl SnapshotManager {
58    #[allow(clippy::too_many_arguments)]
59    pub fn new(
60        config: Config,
61        bucket: Arc<dyn BucketStore>,
62        manifest: Arc<Mutex<Manifest>>,
63        trigger: Arc<Notify>,
64        snapshot_version: Arc<AtomicU64>,
65        force_next: Arc<AtomicBool>,
66        metrics: Arc<dyn Metrics>,
67        conn: Arc<Mutex<rusqlite::Connection>>,
68    ) -> Self {
69        SnapshotManager {
70            config,
71            bucket,
72            manifest,
73            last_snapshot_time: Arc::new(Mutex::new(Instant::now())),
74            trigger,
75            snapshot_version,
76            force_next,
77            metrics,
78            shutdown: Arc::new(Notify::new()),
79            conn,
80        }
81    }
82
83    pub fn trigger(&self) -> Arc<Notify> {
84        self.trigger.clone()
85    }
86
87    pub fn force_next(&self) -> Arc<AtomicBool> {
88        self.force_next.clone()
89    }
90
91    pub fn shutdown_notify(&self) -> Arc<Notify> {
92        self.shutdown.clone()
93    }
94
95    pub fn bucket(&self) -> Arc<dyn BucketStore> {
96        self.bucket.clone()
97    }
98
99    pub async fn run(&self) {
100        loop {
101            // Verify writer identity — catch if another process stole this prefix
102            if let Err(e) = crate::connection::verify_writer_id(
103                &self.bucket,
104                self.bucket.prefix(),
105                self.bucket.writer_id(),
106            )
107            .await
108            {
109                if e.is_wrong_writer() {
110                    tracing::error!("WRITER IDENTITY LOST: {e} — stopping snapshot manager");
111                    return;
112                }
113                warn!("Writer verification failed (will retry): {e}");
114            }
115
116            if let Err(e) = self.maybe_take_snapshot().await {
117                warn!("Snapshot check failed: {e}");
118            }
119            tokio::select! {
120                _ = sleep(self.config.snapshot_check_interval()) => {},
121                _ = self.trigger.notified() => {},
122                _ = self.shutdown.notified() => {
123                    info!("SnapshotManager shutting down");
124                    return;
125                },
126            }
127        }
128    }
129
130    pub async fn maybe_take_snapshot(&self) -> Result<()> {
131        let forced = self.force_next.swap(false, Ordering::Relaxed);
132
133        if !forced {
134            let wal_exists = match tokio::fs::try_exists(self.config.wal_path()).await {
135                Ok(exists) => exists,
136                Err(e) => {
137                    warn!("Failed to check WAL existence for snapshot: {e}");
138                    false
139                }
140            };
141            if !wal_exists {
142                return Ok(());
143            }
144
145            let wal_len = match tokio::fs::metadata(self.config.wal_path()).await {
146                Ok(m) => m.len(),
147                Err(e) => {
148                    warn!("Failed to read WAL metadata for snapshot check: {e}");
149                    return Ok(());
150                }
151            };
152
153            let elapsed = self.last_snapshot_time.lock().await.elapsed();
154
155            let should_snapshot = wal_len >= self.config.snapshot_threshold_bytes()
156                || elapsed >= self.config.snapshot_interval();
157
158            if !should_snapshot {
159                return Ok(());
160            }
161
162            info!(
163                "Taking snapshot: WAL size {wal_size}MB, elapsed {elapsed_sec}s",
164                wal_size = wal_len / 1024 / 1024,
165                elapsed_sec = elapsed.as_secs(),
166            );
167        } else {
168            info!("Taking forced snapshot (salt-change trigger)");
169        }
170
171        self.take_snapshot().await?;
172
173        Ok(())
174    }
175
176    pub async fn take_snapshot(&self) -> Result<()> {
177        let snapshot_path = format!(
178            "snapshots/{}.db",
179            chrono::Utc::now().format("%Y%m%d-%H%M%S%.6f")
180        );
181
182        let db_path = self.config.db_path().clone();
183        let temp_db_path = db_path
184            .parent()
185            .unwrap_or_else(|| std::path::Path::new("."))
186            .join(".snapshot-temp.db");
187        let temp_db_path_for_cleanup = temp_db_path.clone();
188
189        let result = self
190            .take_snapshot_inner(&snapshot_path, &db_path, &temp_db_path)
191            .await;
192        if result.is_err() {
193            tokio::fs::remove_file(&temp_db_path_for_cleanup).await.ok();
194        }
195        result
196    }
197
198    async fn take_snapshot_inner(
199        &self,
200        snapshot_path: &str,
201        db_path: &std::path::Path,
202        temp_db_path: &std::path::Path,
203    ) -> Result<()> {
204        let db_path_owned = db_path.to_path_buf();
205        let temp_db_path_owned = temp_db_path.to_path_buf();
206        let snapshot_path_owned = snapshot_path.to_string();
207
208        // Checkpoint through the main connection. This is critical because
209        // the main connection holds the WAL read lock. A separate connection
210        // can only do a partial checkpoint (moving unlocked pages), which
211        // results in a snapshot that doesn't contain all data.
212        //
213        // We lock the connection in async context (no deadlock risk), then
214        // pass the guard to spawn_blocking for the file copy.
215        let main_size_after = {
216            let guard = self.conn.lock().await;
217            guard
218                .execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")
219                .map_err(|e| crate::error::Error::Snapshot(format!("checkpoint: {e}")))?;
220            let db_path_clone = db_path_owned.clone();
221            let main_size_after = tokio::task::spawn_blocking(move || {
222                std::fs::metadata(&db_path_clone)
223                    .map(|m| m.len())
224                    .unwrap_or(0)
225            })
226            .await
227            .unwrap_or(0);
228            drop(guard);
229            main_size_after
230        };
231        tracing::debug!(
232            "snapshot: main db size after checkpoint={}",
233            main_size_after
234        );
235
236        // Now copy the fully-checkpointed main db to temp file for upload.
237        tokio::fs::copy(&db_path_owned, &temp_db_path_owned).await?;
238
239        let (page_size, db_size) = {
240            let temp_path = temp_db_path_owned.clone();
241            tokio::task::spawn_blocking(move || {
242                let conn = rusqlite::Connection::open(&temp_path)?;
243                conn.execute_batch("PRAGMA journal_mode = WAL")?;
244                conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
245                drop(conn);
246                let mut header = [0u8; 20];
247                let mut file = std::fs::File::open(&temp_path)?;
248                std::io::Read::read_exact(&mut file, &mut header)?;
249                let ps = crate::restore::read_page_size_from_db(&header)?;
250                let size = std::fs::metadata(&temp_path)?.len();
251                Ok::<_, crate::error::Error>((ps, size))
252            })
253            .await??
254        };
255
256        // Compute checksum from the temp file. We read the file into memory
257        // to avoid TOCTOU races with concurrent writes to the same path.
258        let checksum = {
259            let temp_path = temp_db_path_owned.clone();
260            tokio::task::spawn_blocking(move || {
261                let bytes = std::fs::read(&temp_path)?;
262                Ok::<_, std::io::Error>(crate::util::compute_sha256(&bytes))
263            })
264            .await?
265            .map_err(|e| crate::error::Error::Snapshot(format!("checksum failed: {e}")))?
266        };
267
268        self.bucket
269            .put_file(&snapshot_path_owned, &temp_db_path_owned)
270            .await?;
271
272        tokio::fs::remove_file(&temp_db_path_owned).await.ok();
273
274        let wal_len = tokio::fs::metadata(self.config.wal_path())
275            .await
276            .map(|m| m.len())
277            .unwrap_or(0);
278        self.metrics.snapshot_taken(db_size, wal_len);
279
280        let wal = {
281            let wal_path = self.config.wal_path().clone();
282            tokio::task::spawn_blocking(move || WalFile::open(&wal_path).ok())
283                .await
284                .unwrap_or(None)
285        };
286        let wal = wal.unwrap_or_else(|| {
287            warn!("WAL file not found or unreadable during snapshot, using synthetic header");
288            let header = crate::wal::WalHeader::synthetic(page_size, 0, 0);
289            crate::wal::WalFile::with_synthetic_header(header, page_size)
290        });
291
292        let mut manifest = self.manifest.lock().await;
293
294        let old_salt_prefix = if manifest.current_salt_1 != 0 || manifest.current_salt_2 != 0 {
295            if manifest.current_salt_1 != wal.header().salt_1
296                || manifest.current_salt_2 != wal.header().salt_2
297            {
298                Some(manifest.segment_prefix())
299            } else {
300                None
301            }
302        } else {
303            None
304        };
305
306        manifest.update_snapshot(
307            snapshot_path.to_string(),
308            checksum.clone(),
309            wal.header().salt_1,
310            wal.header().salt_2,
311            page_size,
312            db_size,
313        );
314
315        let manifest_bytes = manifest.serialize()?;
316        let etag = manifest.etag.clone();
317        if let Err(e) = async {
318            if let Some(ref etag) = etag {
319                self.bucket
320                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
321                    .await
322            } else {
323                self.bucket
324                    .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
325                    .await
326            }
327        }
328        .await
329        {
330            if matches!(e, crate::error::Error::PreconditionFailed { .. }) {
331                warn!("Manifest precondition failed during snapshot — another writer updated it. Re-reading and retrying.");
332                // Re-read remote manifest and update with our snapshot
333                if let Ok(Some((remote_data, remote_etag))) =
334                    self.bucket.get_with_etag(MANIFEST_KEY).await
335                {
336                    if let Ok(mut remote) = Manifest::deserialize(&remote_data) {
337                        // Merge: take snapshot metadata from us, but preserve
338                        // replication state (shipped_frames, l1_files, etc.)
339                        // from remote in case the shipper advanced concurrently.
340                        remote.snapshot = Some(snapshot_path.to_string());
341                        remote.snapshot_checksum = Some(checksum.clone());
342                        remote.current_salt_1 = wal.header().salt_1;
343                        remote.current_salt_2 = wal.header().salt_2;
344                        remote.page_size = page_size;
345                        remote.db_size = db_size;
346                        // Preserve remote replication state — do NOT reset
347                        // shipped_frames or clear l1_files. The shipper may
348                        // have shipped frames or compacted segments while we
349                        // were creating the snapshot.
350                        remote.etag = Some(remote_etag);
351                        let updated_bytes = remote.serialize()?;
352                        if let Err(e2) = self
353                            .bucket
354                            .put_if_match(
355                                MANIFEST_KEY,
356                                Bytes::from(updated_bytes),
357                                remote.etag.as_deref().unwrap_or(""),
358                            )
359                            .await
360                        {
361                            warn!("Retry manifest write also failed: {e2}. Snapshot {snapshot_path} is uploaded but manifest not updated.");
362                            return Err(e2);
363                        }
364                        info!("Successfully updated manifest on retry after precondition failure.");
365                    } else {
366                        return Err(e);
367                    }
368                } else {
369                    return Err(e);
370                }
371            } else {
372                return Err(e);
373            }
374        }
375
376        drop(manifest);
377
378        if let Some(old_prefix) = old_salt_prefix {
379            match self.bucket.list(&old_prefix).await {
380                Ok(keys) => {
381                    for key in keys {
382                        if key.ends_with(".segment") || key.ends_with(".l1") {
383                            if let Err(e) = self.bucket.delete(&key).await {
384                                warn!("Failed to delete old segment {}: {e}", key);
385                            } else {
386                                self.metrics.segment_deleted(&key);
387                                info!("Deleted old salt segment: {key}");
388                            }
389                        }
390                    }
391                }
392                Err(e) => {
393                    warn!("Failed to list old salt segments for cleanup: {e}");
394                }
395            }
396        }
397
398        *self.last_snapshot_time.lock().await = Instant::now();
399
400        self.snapshot_version.fetch_add(1, Ordering::Release);
401
402        info!("Snapshot complete: {} ({} bytes)", snapshot_path, db_size);
403
404        Ok(())
405    }
406}