Skip to main content

wal_backup/replication/
shipper.rs

1//! WAL frame shipper — continuously reads new WAL frames and uploads them to
2//! object storage as segments.
3//!
4//! # Sync loop
5//!
6//! The `run()` method loops forever:
7//! 1. Open the WAL file, find new frames since last sync
8//! 2. Read frame data into a segment, upload to bucket
9//! 3. Update the manifest with the new shipped frame count
10//! 4. Check for manifest conflicts (remote ahead) — fatal if found
11//!
12//! # Backoff
13//!
14//! On error, exponential backoff from 0.1s to 30s max.
15//! `ManifestConflict` is fatal — the shipper breaks the loop and the
16//! tokio task exits. The process must restart after re-restore.
17//!
18//! # Conflict resolution
19//!
20//! Last-write-wins (no consensus). Two concurrent writers can both update
21//! the manifest; the later write overwrites the earlier. This is safe when
22//! only one node writes at a time (the typical embedded use case).
23
24use bytes::Bytes;
25use std::path::Path;
26use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
27use std::sync::Arc;
28use std::time::{Duration, Instant};
29use tempfile::NamedTempFile;
30use tokio::sync::Mutex;
31use tokio::sync::Notify;
32use tokio::time::sleep;
33use tracing::{error, info, warn};
34
35use crate::config::{Config, SyncMode};
36use crate::error::{Error, Result};
37use crate::metrics::Metrics;
38use crate::replication::manifest::{ConflictLevel, L1File, Manifest, MANIFEST_KEY};
39use crate::storage::BucketStore;
40use crate::wal::{WalFile, WalFrame};
41
42struct SegmentResult {
43    start_frame: u32,
44    frames_read: u32,
45    data: Bytes,
46    sync_duration_ms: u64,
47}
48
49struct WalOpenResult {
50    salt_1: u32,
51    salt_2: u32,
52    wal_truncated: bool,
53    segment: Option<SegmentResult>,
54}
55
56pub struct FrameShipper {
57    config: Config,
58    bucket: Arc<dyn BucketStore>,
59    manifest: Arc<Mutex<Manifest>>,
60    last_sync: Arc<Mutex<Instant>>,
61    snapshot_trigger: Arc<Notify>,
62    sync_notify: Arc<Notify>,
63    wal_notify: Arc<Notify>,
64    shipped_frames: Arc<AtomicU32>,
65    snapshot_version: Arc<AtomicU64>,
66    force_snapshot: Arc<AtomicBool>,
67    metrics: Arc<dyn Metrics>,
68}
69
70impl FrameShipper {
71    #[allow(clippy::too_many_arguments)]
72    pub fn new(
73        config: Config,
74        bucket: Arc<dyn BucketStore>,
75        manifest: Arc<Mutex<Manifest>>,
76        snapshot_trigger: Arc<Notify>,
77        sync_notify: Arc<Notify>,
78        wal_notify: Arc<Notify>,
79        snapshot_version: Arc<AtomicU64>,
80        force_snapshot: Arc<AtomicBool>,
81        shipped_frames: Arc<AtomicU32>,
82        metrics: Arc<dyn Metrics>,
83    ) -> Self {
84        FrameShipper {
85            config,
86            bucket,
87            manifest,
88            last_sync: Arc::new(Mutex::new(Instant::now())),
89            snapshot_trigger,
90            sync_notify,
91            wal_notify,
92            shipped_frames,
93            snapshot_version,
94            force_snapshot,
95            metrics,
96        }
97    }
98
99    pub fn last_sync(&self) -> Arc<Mutex<Instant>> {
100        self.last_sync.clone()
101    }
102
103    pub fn sync_notify(&self) -> Arc<Notify> {
104        self.sync_notify.clone()
105    }
106
107    pub async fn run(&self) {
108        let mut backoff = Duration::from_millis(100);
109        let mut last_gc = Instant::now();
110        let mut last_compaction = Instant::now();
111        let gc_interval = self.config.gc_interval();
112        let compaction_interval = self.config.compaction_interval();
113
114        loop {
115            // Verify writer identity on every loop iteration.
116            // This catches the case where another process deleted writer.json
117            // and re-created it with a different identity.
118            if let Err(e) = crate::connection::verify_writer_id(
119                &self.bucket,
120                self.bucket.prefix(),
121                self.bucket.writer_id(),
122            )
123            .await
124            {
125                if e.is_wrong_writer() {
126                    error!("WRITER IDENTITY LOST: {e} — stopping shipper to prevent corruption");
127                    return;
128                }
129                // Transient error (bucket unavailable) — log and continue
130                warn!("Writer verification failed (will retry): {e}");
131            }
132
133            // Run GC if configured and interval has elapsed
134            if let Some(interval) = gc_interval {
135                if last_gc.elapsed() >= interval {
136                    last_gc = Instant::now();
137                    match self.gc().await {
138                        Ok(deleted) => {
139                            if deleted > 0 {
140                                info!("GC run completed, deleted {} orphaned segments", deleted);
141                            }
142                        }
143                        Err(e) => {
144                            warn!("GC failed: {}", e);
145                        }
146                    }
147                }
148            }
149
150            // Run compaction if configured and interval has elapsed
151            if let Some(interval) = compaction_interval {
152                if last_compaction.elapsed() >= interval {
153                    last_compaction = Instant::now();
154                    match self.compact().await {
155                        Ok(compacted) => {
156                            if compacted > 0 {
157                                info!(
158                                    "Compaction run completed, compacted {} L0 segments",
159                                    compacted
160                                );
161                            }
162                        }
163                        Err(e) => {
164                            warn!("Compaction failed: {}", e);
165                        }
166                    }
167                }
168            }
169
170            let result = self.sync_once().await;
171            match result {
172                Ok(true) => {
173                    backoff = Duration::from_millis(100);
174                    *self.last_sync.lock().await = Instant::now();
175                    self.sync_notify.notify_waiters();
176                }
177                Ok(false) => {
178                    *self.last_sync.lock().await = Instant::now();
179                    self.sync_notify.notify_waiters();
180                    match self.config.sync_mode() {
181                        SyncMode::Immediate => {
182                            // Use wal_notify.notified() for event-driven wakeups
183                            // combined with a poll interval as fallback
184                            let poll_interval = self.config.poll_interval();
185                            tokio::select! {
186                                _ = self.wal_notify.notified() => {
187                                    // WAL changed — sync immediately
188                                }
189                                _ = sleep(poll_interval) => {
190                                    // Poll interval elapsed — check for new frames
191                                }
192                            }
193                        }
194                        SyncMode::Lazy => {
195                            sleep(self.config.poll_interval()).await;
196                        }
197                    }
198                }
199                Err(e) => {
200                    error!("WAL sync error, backing off {:?}: {}", backoff, e);
201                    if matches!(e, Error::ManifestConflict { .. }) {
202                        error!(
203                            "Manifest conflict is fatal — remote manifest is ahead. \
204                            Re-restore from bucket and restart to resolve."
205                        );
206                        self.metrics.shipper_error(&e.to_string());
207                        break;
208                    }
209                    self.metrics.shipper_error(&e.to_string());
210                    sleep(backoff).await;
211                    backoff = (backoff * 2).min(Duration::from_secs(30));
212                }
213            }
214        }
215    }
216
217    pub async fn sync_once(&self) -> Result<bool> {
218        let start_frame = self.manifest.lock().await.shipped_frames;
219        let max_frames = self.config.max_frames_per_segment();
220
221        let wal_path_clone = self.config.wal_path().clone();
222        let sync_result = match tokio::task::spawn_blocking(move || {
223            Self::open_and_read_frames(&wal_path_clone, start_frame, max_frames)
224        })
225        .await
226        {
227            Ok(result) => result,
228            Err(e) => {
229                warn!("WAL open+read task failed: {}", e);
230                return Ok(false);
231            }
232        };
233
234        let wal_info = match sync_result {
235            Ok(info) => info,
236            Err(e) => {
237                if matches!(e, Error::WalParse { .. } | Error::WalChecksum { .. }) {
238                    error!("WAL file is corrupt: {}", e);
239                    return Err(e);
240                }
241                warn!("Failed to open WAL file: {}", e);
242                return Ok(false);
243            }
244        };
245
246        let mut manifest = self.manifest.lock().await;
247
248        if wal_info.wal_truncated {
249            self.force_snapshot.store(true, Ordering::Relaxed);
250            self.snapshot_trigger.notify_one();
251            self.shipped_frames
252                .store(manifest.shipped_frames, Ordering::Release);
253            let pre_version = self.snapshot_version.load(Ordering::Acquire);
254            drop(manifest);
255            info!("WAL truncated (checkpoint mid-flight), waiting for snapshot to complete");
256            let deadline = Instant::now() + self.config.salt_change_timeout();
257            loop {
258                if self.snapshot_version.load(Ordering::Acquire) != pre_version {
259                    info!("Snapshot completed (version changed), resuming with updated manifest");
260                    break;
261                }
262                if Instant::now() > deadline {
263                    warn!(
264                        "Timed out waiting for snapshot after WAL truncation ({:?}), retrying",
265                        self.config.salt_change_timeout()
266                    );
267                    break;
268                }
269                tokio::time::sleep(Duration::from_millis(100)).await;
270            }
271            return Ok(false);
272        }
273
274        let fresh_manifest = manifest.current_salt_1 == 0 && manifest.current_salt_2 == 0;
275        if manifest.is_different_salt(wal_info.salt_1, wal_info.salt_2) {
276            if fresh_manifest {
277                manifest.current_salt_1 = wal_info.salt_1;
278                manifest.current_salt_2 = wal_info.salt_2;
279            } else {
280                self.force_snapshot.store(true, Ordering::Relaxed);
281                self.snapshot_trigger.notify_one();
282                self.shipped_frames
283                    .store(manifest.shipped_frames, Ordering::Release);
284                let pre_version = self.snapshot_version.load(Ordering::Acquire);
285                drop(manifest);
286                info!(
287                    "WAL salt changed, waiting for snapshot to complete before resuming shipping"
288                );
289                let deadline = Instant::now() + self.config.salt_change_timeout();
290                loop {
291                    if self.snapshot_version.load(Ordering::Acquire) != pre_version {
292                        info!(
293                            "Snapshot completed (version changed), resuming with updated manifest"
294                        );
295                        break;
296                    }
297                    if Instant::now() > deadline {
298                        warn!(
299                            "Timed out waiting for snapshot after salt change ({:?}), retrying",
300                            self.config.salt_change_timeout()
301                        );
302                        break;
303                    }
304                    tokio::time::sleep(Duration::from_millis(100)).await;
305                }
306                return Ok(false);
307            }
308        }
309
310        let segment = match wal_info.segment {
311            Some(seg) => seg,
312            None => return Ok(false),
313        };
314
315        let end_frame = segment.start_frame + segment.frames_read;
316
317        let upload_key = format!(
318            "wal/{}/{start:08}-{end:08}.segment",
319            manifest.salt_string(),
320            start = segment.start_frame,
321            end = end_frame,
322        );
323
324        let segment_len = segment.data.len() as u64;
325
326        // Check for manifest conflicts and refresh our etag from the remote read
327        if let Ok(Some((remote_data, remote_etag))) = self.bucket.get_with_etag(MANIFEST_KEY).await
328        {
329            if let Ok(remote) = Manifest::deserialize(&remote_data) {
330                let level = manifest.conflict_level(&remote);
331                match level {
332                    ConflictLevel::None => {
333                        // Update our local etag from the remote read so our
334                        // conditional write below uses the latest known etag
335                        manifest.etag = Some(remote_etag);
336                        // Also merge any snapshot-related fields that the
337                        // snapshot manager may have updated since our last write.
338                        // Without this, the shipper would overwrite the remote
339                        // manifest with stale snapshot_checksum = None.
340                        manifest.snapshot = remote.snapshot.clone();
341                        manifest.snapshot_checksum = remote.snapshot_checksum.clone();
342                        manifest.db_size = remote.db_size;
343                    }
344                    ConflictLevel::RemoteAhead => {
345                        return Err(Error::ManifestConflict {
346                            local_gen: manifest.generation,
347                            remote_gen: remote.generation,
348                        });
349                    }
350                    ConflictLevel::LocalAhead => {
351                        warn!(
352                            "Manifest: local gen {} ahead of remote gen {} (normal if this node \
353                             is the primary). Proceeding.",
354                            manifest.generation, remote.generation
355                        );
356                        // Still merge remote snapshot fields and update etag
357                        manifest.etag = Some(remote_etag);
358                        manifest.snapshot = remote.snapshot.clone();
359                        manifest.snapshot_checksum = remote.snapshot_checksum.clone();
360                        manifest.db_size = remote.db_size;
361                    }
362                }
363            }
364        }
365
366        // Check for WAL size backpressure before uploading
367        if self.config.max_wal_size_bytes() > 0 {
368            let wal_size = match tokio::fs::metadata(self.config.wal_path()).await {
369                Ok(meta) => meta.len(),
370                Err(_) => 0,
371            };
372            if wal_size > self.config.max_wal_size_bytes() {
373                warn!(
374                    "WAL size {} exceeds max {} — forcing snapshot and pausing shipping",
375                    wal_size,
376                    self.config.max_wal_size_bytes()
377                );
378                self.force_snapshot.store(true, Ordering::Relaxed);
379                self.snapshot_trigger.notify_one();
380                // Return false to let snapshot complete before continuing
381                return Ok(false);
382            }
383        }
384
385        // Compute checksum before upload (data is moved by put)
386        let segment_checksum = crate::util::compute_sha256(&segment.data);
387
388        self.bucket.put(&upload_key, segment.data).await?;
389
390        // Store segment checksum for restore verification
391        manifest
392            .segment_checksums
393            .insert(upload_key.clone(), segment_checksum);
394
395        self.metrics.segment_uploaded(&upload_key, segment_len);
396        self.metrics.frames_shipped(segment.frames_read);
397
398        let prev_shipped_frames = manifest.shipped_frames;
399        manifest.update_shipped_frames(end_frame);
400
401        if let Err(e) = async {
402            let manifest_bytes = manifest.serialize()?;
403            let etag = manifest.etag.clone();
404            drop(manifest);
405            if let Some(ref etag) = etag {
406                self.bucket
407                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
408                    .await
409            } else {
410                // No etag known (fresh manifest) — use regular put
411                self.bucket
412                    .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
413                    .await
414            }
415        }
416        .await
417        {
418            error!(
419                "Failed to write manifest after segment upload (precondition failed or error), rolling back segment {}: {}",
420                upload_key, e
421            );
422            if let Err(delete_err) = self.bucket.delete(&upload_key).await {
423                error!(
424                    "Failed to delete rolled-back segment {}: {}",
425                    upload_key, delete_err
426                );
427            }
428            // Re-acquire manifest and restore shipped_frames
429            let mut manifest = self.manifest.lock().await;
430            manifest.shipped_frames = prev_shipped_frames;
431
432            // If this was a precondition failure, re-read the remote manifest
433            // to sync our local state before retrying
434            if matches!(e, crate::error::Error::PreconditionFailed { .. }) {
435                warn!(
436                    "Manifest precondition failed — another writer updated it. Re-reading remote manifest to sync state."
437                );
438                if let Ok(Some((remote_data, _))) = self.bucket.get_with_etag(MANIFEST_KEY).await {
439                    if let Ok(remote) = Manifest::deserialize(&remote_data) {
440                        // Preserve local progress — only advance, never retreat.
441                        manifest.shipped_frames =
442                            std::cmp::max(manifest.shipped_frames, remote.shipped_frames);
443                        manifest.generation = remote.generation;
444                        manifest.etag = remote.etag;
445                        tracing::info!(
446                            "Synced local manifest from remote: gen={}, frames={}",
447                            manifest.generation,
448                            manifest.shipped_frames
449                        );
450                    }
451                }
452                // Return Ok(false) so the loop continues without backing off
453                return Ok(false);
454            }
455            return Err(e);
456        }
457
458        info!(
459            "Shipped frames {}..{} to {}",
460            segment.start_frame, end_frame, upload_key
461        );
462
463        self.shipped_frames.store(end_frame, Ordering::Release);
464
465        self.metrics.sync_completed(segment.sync_duration_ms);
466
467        Ok(true)
468    }
469
470    /// Garbage collect orphaned WAL segments.
471    ///
472    /// An orphaned segment is one that:
473    /// - Matches the current salt prefix (`wal/{salt_1}-{salt_2}/`)
474    /// - Has a start frame less than the current `shipped_frames` count
475    ///   (i.e., it's been superseded by newer segments)
476    ///
477    /// Segments with start frame >= shipped_frames are ACTIVE and never deleted,
478    /// even if they are still being written to.
479    ///
480    /// **Limitation:** Only segments under the *current* salt prefix are considered.
481    /// After a WAL salt change, segments from the previous salt are not cleaned up.
482    /// These orphaned segments are harmless (they're just stale data) but consume
483    /// storage. A future enhancement could add a separate pass for old salt prefixes.
484    ///
485    /// Returns the number of orphaned segments deleted.
486    pub async fn gc(&self) -> Result<u32> {
487        let shipped_frames;
488        let l1_max;
489        let prefix;
490        {
491            let manifest = self.manifest.lock().await;
492            shipped_frames = manifest.shipped_frames;
493            l1_max = manifest.l1_max_frame_value();
494            prefix = format!("wal/{}/", manifest.salt_string());
495        }
496
497        if shipped_frames == 0 {
498            // No frames shipped yet, nothing to gc
499            return Ok(0);
500        }
501
502        // List all objects with the current salt prefix
503        let listed = self.bucket.list(&prefix).await?;
504
505        let mut deleted = 0u32;
506        // Collect segment keys to remove from bucket AND from segment_checksums
507        let mut keys_to_prune: Vec<String> = Vec::new();
508        for key in listed {
509            // Delete L0 segments (.segment) that are either:
510            // 1. Orphaned: start_frame < shipped_frames (superseded by newer segments)
511            // 2. Compacted: end_frame <= l1_max (fully covered by an L1 file)
512            if key.ends_with(".segment") {
513                if let Some(seg_start) = Self::extract_start_frame(&key) {
514                    if seg_start < shipped_frames {
515                        self.bucket.delete(&key).await?;
516                        self.metrics.orphan_deleted(&key);
517                        deleted += 1;
518                        keys_to_prune.push(key.clone());
519                        info!("GC deleted orphaned segment: {}", key);
520                        continue;
521                    }
522                }
523                if let Some(seg_end) = Self::extract_end_frame(&key) {
524                    if seg_end <= l1_max {
525                        // L0 fully covered by compaction — safe to delete
526                        self.bucket.delete(&key).await?;
527                        self.metrics.orphan_deleted(&key);
528                        deleted += 1;
529                        keys_to_prune.push(key);
530                    }
531                }
532            }
533        }
534
535        // Prune checksums for deleted segments from the manifest
536        // We hold the lock for this brief update to keep segment_checksums in sync
537        if !keys_to_prune.is_empty() {
538            let manifest_etag;
539            {
540                let mut manifest = self.manifest.lock().await;
541                for key in &keys_to_prune {
542                    manifest.segment_checksums.remove(key);
543                }
544                manifest_etag = manifest.etag.clone();
545                let manifest_bytes = manifest.serialize()?;
546                // Release lock before persist to avoid holding it across I/O
547                drop(manifest);
548                if let Some(ref etag) = manifest_etag {
549                    self.bucket
550                        .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
551                        .await?;
552                } else {
553                    self.bucket
554                        .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
555                        .await?;
556                }
557            }
558        }
559
560        if deleted > 0 {
561            info!(
562                "GC completed: deleted {} orphaned/compacted segments (shipped_frames={}, l1_max={})",
563                deleted, shipped_frames, l1_max
564            );
565        }
566
567        Ok(deleted)
568    }
569
570    /// Check if the error is from a truncated WAL file (exists but too small
571    /// to contain a valid header, e.g. after wal_checkpoint(TRUNCATE)).
572    fn is_truncated_wal(e: &Error) -> bool {
573        match e {
574            // Direct IO error: file too short
575            Error::Io(e) => e.kind() == std::io::ErrorKind::UnexpectedEof,
576            // WAL parse error with "fill whole buffer" message
577            Error::WalParse { detail, .. } => detail.contains("fill whole buffer"),
578            _ => false,
579        }
580    }
581
582    fn extract_start_frame(key: &str) -> Option<u32> {
583        // Pattern: wal/salt/start-end.segment
584        // Extract start from the start-end part
585        let segments: Vec<&str> = key.rsplitn(2, '/').collect();
586        if segments.len() < 2 {
587            return None;
588        }
589        let filename = segments[0]; // e.g., "00000100-00000199.segment"
590        filename
591            .split('-')
592            .next()
593            .and_then(|s| s.strip_suffix(".segment").unwrap_or(s).parse::<u32>().ok())
594    }
595
596    /// Extract end frame from a segment key like "wal/salt/00000100-00000199.segment"
597    fn extract_end_frame(key: &str) -> Option<u32> {
598        let segments: Vec<&str> = key.rsplitn(2, '/').collect();
599        if segments.len() < 2 {
600            return None;
601        }
602        let filename = segments[0];
603        filename
604            .split('-')
605            .nth(1)
606            .and_then(|s| s.strip_suffix(".segment").unwrap_or(s).parse::<u32>().ok())
607    }
608
609    /// Compact L0 segments into L1 files.
610    ///
611    /// Compaction merges multiple small L0 `.segment` files into fewer,
612    /// larger L1 `.l1` files. This reduces the number of GET requests
613    /// needed during restore and lowers storage costs.
614    ///
615    /// # Algorithm
616    ///
617    /// 1. List all L0 segments under the current salt prefix
618    /// 2. Filter out segments already covered by existing L1 files
619    /// 3. If fewer than `compaction_min_segments` eligible L0s, skip
620    /// 4. Merge eligible L0s into a single L1 file
621    /// 5. Upload the L1, update the manifest
622    /// 6. GC will delete the L0s in the next cycle
623    ///
624    /// Returns the number of L0 segments compacted.
625    pub async fn compact(&self) -> Result<u32> {
626        let manifest = self.manifest.lock().await;
627        let salt_string = manifest.salt_string();
628        let prefix = format!("wal/{}/", salt_string);
629        let l1_max = manifest.l1_max_frame_value();
630        let min_segments = self.config.compaction_min_segments();
631        drop(manifest);
632
633        // List all L0 segments
634        let listed = self.bucket.list(&prefix).await?;
635
636        let mut l0_segments: Vec<String> = listed
637            .into_iter()
638            .filter(|k| k.ends_with(".segment"))
639            .collect();
640        l0_segments.sort();
641
642        if l0_segments.is_empty() {
643            return Ok(0);
644        }
645
646        // Filter out segments already covered by L1 files
647        let eligible: Vec<String> = l0_segments
648            .into_iter()
649            .filter(|k| {
650                // A segment is covered if its end_frame <= l1_max
651                match Self::extract_end_frame(k) {
652                    Some(end) => end > l1_max,
653                    None => true, // Can't parse, skip filtering
654                }
655            })
656            .collect();
657
658        if (eligible.len() as u32) < min_segments {
659            return Ok(0);
660        }
661
662        // Determine the frame range for the L1 file
663        let start_frame = Self::extract_start_frame(&eligible[0]).ok_or_else(|| {
664            Error::Compaction("could not parse start frame from segment key".into())
665        })?;
666        let end_frame = Self::extract_end_frame(
667            eligible
668                .last()
669                .ok_or_else(|| Error::Compaction("no eligible segments".into()))?,
670        )
671        .ok_or_else(|| Error::Compaction("could not parse end frame from segment key".into()))?;
672
673        // Download and merge all eligible L0 segments into a NamedTempFile.
674        // NamedTempFile uses a random suffix so the path is unpredictable and
675        // the file is automatically cleaned up if we return early on error.
676        let tmp_dir = std::path::Path::new("/tmp");
677        let mut tmp_file = NamedTempFile::new_in(tmp_dir)
678            .map_err(|e| Error::Compaction(format!("create temp file: {e}")))?;
679
680        for key in &eligible {
681            let segment_data = self
682                .bucket
683                .get(key)
684                .await?
685                .ok_or_else(|| Error::Compaction(format!("segment not found: {key}")))?;
686            use std::io::Write;
687            tmp_file
688                .write_all(&segment_data)
689                .map_err(|e| Error::Compaction(format!("write temp file: {e}")))?;
690        }
691        use std::io::Seek;
692        tmp_file
693            .seek(std::io::SeekFrom::Start(0))
694            .map_err(|e| Error::Compaction(format!("seek temp file: {e}")))?;
695
696        // Get the temp file path BEFORE upload (NamedTempFile keeps the file
697        // alive even after we drop the handle, but we need the path string).
698        let tmp_path = tmp_file.path().to_path_buf();
699        let l1_size = std::fs::metadata(&tmp_path).map(|m| m.len()).unwrap_or(0);
700
701        // Upload the L1 file from the temp file (streaming, no full-blob in memory)
702        let l1_key = format!("wal/{}/{:08}-{:08}.l1", salt_string, start_frame, end_frame);
703        self.bucket.put_file(&l1_key, &tmp_path).await?;
704
705        // Compute L1 checksum for restore verification
706        let l1_checksum = crate::util::compute_sha256_file(&tmp_path)
707            .map_err(|e| Error::Compaction(format!("L1 checksum: {e}")))?;
708
709        // NamedTempFile auto-deletes the temp file when it goes out of scope.
710        // Explicit close is not required — drop is sufficient.
711        drop(tmp_file);
712
713        let l1 = L1File {
714            key: l1_key.clone(),
715            start_frame,
716            end_frame,
717            source_count: eligible.len() as u32,
718            checksum: Some(l1_checksum),
719        };
720
721        // Update manifest with the new L1 file
722        let mut manifest = self.manifest.lock().await;
723        manifest.add_l1_file(l1);
724        manifest.generation = manifest.generation.wrapping_add(1);
725
726        // Write manifest (with etag if available)
727        if let Err(e) = async {
728            let manifest_bytes = manifest.serialize()?;
729            let etag = manifest.etag.clone();
730            drop(manifest);
731            if let Some(ref etag) = etag {
732                self.bucket
733                    .put_if_match(MANIFEST_KEY, Bytes::from(manifest_bytes), etag)
734                    .await
735            } else {
736                self.bucket
737                    .put(MANIFEST_KEY, Bytes::from(manifest_bytes))
738                    .await
739            }
740        }
741        .await
742        {
743            // Rollback: delete the L1 file we just uploaded
744            warn!(
745                "Failed to write manifest after compaction, rolling back L1 {}: {}",
746                l1_key, e
747            );
748            if let Err(delete_err) = self.bucket.delete(&l1_key).await {
749                warn!("Failed to delete rolled-back L1 {}: {}", l1_key, delete_err);
750            }
751            // Re-acquire manifest and remove the L1 entry
752            let mut manifest = self.manifest.lock().await;
753            manifest.l1_files.retain(|l| l.key != l1_key);
754            manifest.l1_max_frame = manifest.l1_files.iter().map(|l| l.end_frame).max();
755            return Err(e);
756        }
757
758        self.metrics
759            .segment_compacted(eligible.len() as u32, &l1_key);
760        info!(
761            "Compacted {} L0 segments into L1 {} ({}..{}, {} bytes)",
762            eligible.len(),
763            l1_key,
764            start_frame,
765            end_frame,
766            l1_size
767        );
768
769        Ok(eligible.len() as u32)
770    }
771
772    fn open_and_read_frames(
773        path: &Path,
774        start_frame: u32,
775        max_frames: u32,
776    ) -> Result<WalOpenResult> {
777        let wal = match WalFile::open(path) {
778            Ok(w) => w,
779            Err(e) if e.is_io_not_found() => {
780                return Ok(WalOpenResult {
781                    salt_1: 0,
782                    salt_2: 0,
783                    wal_truncated: false,
784                    segment: None,
785                });
786            }
787            // WAL file exists but is empty or too small to contain a valid header.
788            // This happens after wal_checkpoint(TRUNCATE) truncates the WAL to 0 bytes
789            // before SQLite writes a new header. Treat as "no WAL available" — the
790            // shipper will retry on the next cycle when the header appears.
791            Err(e) if e.is_io_not_found() || Self::is_truncated_wal(&e) => {
792                return Ok(WalOpenResult {
793                    salt_1: 0,
794                    salt_2: 0,
795                    wal_truncated: false,
796                    segment: None,
797                });
798            }
799            Err(e) => return Err(e),
800        };
801
802        let salt_1 = wal.header().salt_1;
803        let salt_2 = wal.header().salt_2;
804
805        let wal_truncated = start_frame > 0 && wal.total_frames() < start_frame;
806
807        let new_frames = wal.total_frames().saturating_sub(start_frame);
808        if new_frames == 0 {
809            return Ok(WalOpenResult {
810                salt_1,
811                salt_2,
812                wal_truncated,
813                segment: None,
814            });
815        }
816
817        let total_to_ship = std::cmp::min(new_frames, max_frames);
818        let page_size = wal.page_size();
819        let big_endian = wal.header().magic == 0x377f0683;
820        let initial_prev_cksum_1 = wal.header().checksum_1;
821        let initial_prev_cksum_2 = wal.header().checksum_2;
822
823        let sync_start = Instant::now();
824        let mut file = std::fs::File::open(path)?;
825        let mut data = Vec::with_capacity(
826            (total_to_ship as usize) * (WalFrame::frame_size(page_size) as usize),
827        );
828        let mut frames_read = 0u32;
829        let mut prev_cksum_1 = initial_prev_cksum_1;
830        let mut prev_cksum_2 = initial_prev_cksum_2;
831
832        if start_frame > 0 {
833            if let Some(frame) = WalFrame::read(
834                &mut file,
835                start_frame - 1,
836                page_size,
837                prev_cksum_1,
838                prev_cksum_2,
839                big_endian,
840                start_frame == 1,
841            )? {
842                prev_cksum_1 = frame.checksum_1;
843                prev_cksum_2 = frame.checksum_2;
844            }
845        }
846
847        for i in 0..total_to_ship {
848            let frame_idx = start_frame + i;
849            match WalFrame::read(
850                &mut file,
851                frame_idx,
852                page_size,
853                prev_cksum_1,
854                prev_cksum_2,
855                big_endian,
856                true,
857            )? {
858                Some(frame) => {
859                    prev_cksum_1 = frame.checksum_1;
860                    prev_cksum_2 = frame.checksum_2;
861                    data.extend_from_slice(&frame.page_number.to_be_bytes());
862                    data.extend_from_slice(&frame.db_size_after.to_be_bytes());
863                    data.extend_from_slice(&frame.salt_1.to_be_bytes());
864                    data.extend_from_slice(&frame.salt_2.to_be_bytes());
865                    data.extend_from_slice(&frame.checksum_1.to_be_bytes());
866                    data.extend_from_slice(&frame.checksum_2.to_be_bytes());
867                    data.extend_from_slice(&frame.data);
868                    frames_read += 1;
869                }
870                None => break,
871            }
872        }
873
874        if frames_read == 0 {
875            return Ok(WalOpenResult {
876                salt_1,
877                salt_2,
878                wal_truncated,
879                segment: None,
880            });
881        }
882
883        Ok(WalOpenResult {
884            salt_1,
885            salt_2,
886            wal_truncated: false,
887            segment: Some(SegmentResult {
888                start_frame,
889                frames_read,
890                data: Bytes::from(data),
891                sync_duration_ms: sync_start.elapsed().as_millis() as u64,
892            }),
893        })
894    }
895}