wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar โ€” a library. Like Litestream, but embedded.
Documentation
# wal-backup Master Tasklist

> **Legend:** `P0` = blocks publish | `P1` = Litestream replacement | `P2` = quality | `P3` = nice-to-have | `P4` = test infra

---

## ๐Ÿ“ฆ P0 โ€” Blocking crates.io Publish

### P0.1 Publish to crates.io
- [ ] `cargo publish -p wal-backup`
- [ ] Verify Cargo.toml metadata (description, license, repository, keywords)
- [ ] Create crates.io API token
- [ ] `cargo publish --dry-run` (was passing last check)

### P0.2 โœ… W1: EncryptedBucketStore::get_file loads full plaintext into RAM
**`src/storage/encrypted.rs`** โ€” OOM risk for large snapshots.
- [x] Download encrypted to temp file (`inner.get_file` โ†’ `encrypted-tmp`)
- [x] Decrypt file-to-file in `spawn_blocking` with key zeroization
- [x] Write plaintext in 256KB chunks to avoid holding full DB in memory

### P0.3 โœ… W4: segment_checksums grows without bound
**`src/replication/manifest.rs:52`** โ€” Unbounded memory/I/O growth.
- [x] `update_snapshot`: prune checksums for old salt prefix on salt change
- [x] `gc()`: remove checksums for orphaned/compacted segments + persist updated manifest

### P0.4 โœ… W7: Two-step rename in restore not crash-atomic
**`src/restore.rs`** โ€” Crash between DB/WAL renames leaves DB without WAL.
- [x] Write `.db.restore-in-progress` marker before first rename (contains WAL temp path)
- [x] Rename DB โ†’ final, then WAL โ†’ final, then delete marker
- [x] On `download_and_reconstruct()`, check for stale marker and clean up

### P0.5 โœ… W15: Manifest version not checked on deserialization
**`src/replication/manifest.rs`** โ€” Future schema changes fail silently.
- [x] Parse into raw `serde_json::Value` first, check `version` field
- [x] Return clear error for unknown versions (e.g. "unsupported manifest version 2")

### P0.6 โœ… W5: Compaction temp file leaked on error paths
**`src/replication/shipper.rs`** โ€” No cleanup on error.
- [x] Replaced deterministic path with `tempfile::NamedTempFile`
- [x] RAII auto-cleanup on drop (all error paths covered)
- [x] Added `tempfile = "3"` as regular dep (was dev-dep only)

### P0.7 โœ… W16: Predictable temp file paths enable symlink attacks
**`src/storage/encrypted.rs`, `src/storage/compressed.rs`**
- [x] Compaction path: `NamedTempFile` with random suffix (P0.6)
- [x] Snapshot restore (`get_file`): downloads via inner store's temp + cleanup
- [x] `put_file` in compressed.rs: uses `NamedTempFile` instead of `path.with_extension("compress-tmp")`
- [x] `put_file` in encrypted.rs: uses `NamedTempFile` instead of `path.with_extension("encrypt-tmp")`
- [x] All temp files now use random, unpredictable paths (RAII cleanup)

### P0.8 โœ… W17: KeyEntry not zeroized on drop (key schedule persists)
**`src/storage/encrypted.rs`**
- [x] Added `zeroize = { features = ["zeroize_derive"] }` (was dep-only without features)
- [x] `Aes256Gcm` inner cipher: `aes` crate implements `ZeroizeOnDrop` on key schedule types
- [x] `current_key` already zeroized in `Drop` impl (unchanged)
- [x] Past keys cleared via `HashMap::clear()` triggers each `Aes256Gcm` drop โ†’ auto-zeroize

### P0.9 โš ๏ธ A10: Integration tests flaky (~3%, pre-existing)
**`tests/integration_tests.rs`** โ€” Intermittent failure when run with full suite.
- [x] NOT caused by P0 changes โ€” confirmed by isolated test runs (10/10 pass)
- [x] Root cause unknown: temp dir collision or tokio runtime state leakage
- [ ] Mitigation: add `#[serial_test::serial]` or enforce unique per-test workdirs
- [x] Documented in A10 audit finding; lower priority than publish

---

## ๐Ÿ† P1 โ€” Litestream Replacement Features

### P1.1 Multi-destination replication (MultiBucketStore)
**New: `src/storage/multi.rs`** โ€” Fan-out writes to N bucket stores.
- [ ] `MultiBucketStore` struct with `Vec<Arc<dyn BucketStore>>`
- [ ] `put()` โ†’ fan-out to all stores, collect errors (best-effort, log failures)
- [ ] `get()`/`list()`/`delete()` โ†’ operate on first store only (source of truth)
- [ ] Tests: write to 2 in-memory stores, verify both have data

### P1.2 Point-in-time recovery (PITR)
**`src/restore.rs` + manifest** โ€” Restore WAL up to a specific frame or timestamp.
- [ ] Store `max_wall_time` in manifest tracking latest WAL frame timestamp
- [ ] `restore_to_timestamp(t: DateTime)` method:
  - [ ] Download snapshot
  - [ ] Download ALL L0 + L1 segments up to target time
  - [ ] Replay frames until timestamp > target (handling salt changes)
  - [ ] Write reconstructed DB + WAL
- [ ] CLI: `wal-backup restore /path/to/db --at "2026-05-19T15:32:00Z"`
- [ ] Tests: write data, wait, write more data, restore to mid-point, verify

### P1.3 Snapshot retention / generational backups
**`src/config.rs` + `src/replication/snapshot.rs`** โ€” Keep N latest snapshots.
- [ ] `Config::with_snapshot_retention(count: usize)` (default 1)
- [ ] On new snapshot: upload โ†’ update manifest โ†’ delete oldest exceeding count
- [ ] Prune by generation number or timestamp
- [ ] Tests: retention=2, take 3 snapshots, verify only 2 remain

### P1.4 SFTP/SSH storage backend
**New: `src/storage/sftp.rs`** โ€” Custom BucketStore over SSH/SFTP.
- [ ] Research `ssh2` crate vs CLI subprocess approach
- [ ] `SftpBucketStore { host, port, user, key_path, base_path }`
- [ ] Map S3-style paths to filesystem paths
- [ ] `put_if_match` / `put_if_not_exists` โ†’ fallback with TOCTOU warning
- [ ] Authentication: key-based, password (optional)

### P1.5 Prometheus metrics export
**Optional `metrics-prometheus` feature flag.**
- [ ] Add `prometheus` crate as optional dependency
- [ ] Export counters: shipped segments, shipped frames, snapshots
- [ ] Export gauges: snapshot bytes, replica lag, WAL size, health
- [ ] Integrate with daemon example's HTTP server on `/metrics`

### P1.6 CLI: restore from specific generation
**`src/bin/wal-backup.rs`** โ€” `wal-backup restore --generation N`.
- [ ] List available snapshot generations from bucket
- [ ] Restore from specific generation
- [ ] Requires P1.3 (retention) for old snapshots to exist

---

## ๐Ÿ”ง P2 โ€” Quality & Robustness

### P2.1 Large DB test (>1GB)
- [ ] Create 1GB SQLite DB
- [ ] Run backup (verify streaming multipart upload works)
- [ ] Delete local, restore from bucket
- [ ] Verify checksums match

### P2.2 WAL fuzz test
- [ ] `cargo fuzz` or `proptest` harness for WAL parser
- [ ] Feed random bytes, verify never panics
- [ ] Verify checksum validation catches all corruptions
- [ ] Verify salt-change detection works correctly

### P2.3 Concurrent stress test
- [ ] N concurrent tasks writing through `DurabilityLayer`
- [ ] Verify all rows preserved after restore
- [ ] Test with `SyncMode::Immediate` and `SyncMode::Lazy`

### P2.4 Network partition test
- [ ] Proxy between app and S3 (mitmproxy/squid)
- [ ] Kill proxy mid-upload, verify retry logic
- [ ] Verify no partial objects in bucket
- [ ] Verify restore still succeeds

### P2.5 CLI: --force-takeover on verify/status
**`src/bin/wal-backup.rs`** โ€” Skip writer check for read-only commands.
- [ ] Add `--force-takeover` flag to `verify` subcommand
- [ ] Add `--force-takeover` flag to `status` subcommand
- [ ] Or: skip writer verification entirely for read-only operations

### P2.6 examples/restore_only.rs
- [ ] Restore from bucket using `RestoreEngine` directly (no `DurabilityLayer`)
- [ ] Useful for one-off recovery, migration, seeding replicas

### P2.7 wal-backup verify checks segment checksums
**From CORRUPTION-PLAN.md ยง4b** โ€” Download + verify SHA256 of each segment.
- [ ] Iterate manifest segment_checksums
- [ ] Download each segment, compute SHA256, compare
- [ ] Report mismatches

### P2.8 Track segment timestamps for PITR
**`src/wal/frame.rs`** โ€” WAL frames have 64-bit timestamp in header (bytes 56-63).
- [ ] Extract timestamp from WAL frame header
- [ ] Store `min/max_wall_time` per segment in manifest
- [ ] Prerequisite for P1.2

### P2.9 Snapshot temp file uses non-unique name
**`src/replication/snapshot.rs:193-196`** โ€” `.snapshot-temp.db` collides across processes.
- [ ] Include PID or random suffix in temp file name

### P2.10 Bucket validation should surface errors to caller
**`src/connection.rs:783-830`** โ€” Validation only logs, never returns errors.
- [ ] Consider returning `Result<Vec<String>>` with list of issues
- [ ] Or: add a `validation_errors` field on `DurabilityLayer`

---

## ๐Ÿš€ P3 โ€” Nice-to-Have Features

### P3.1 VFS read replicas
**`src/vfs/`** โ€” SQLite VFS shim reading from bucket.
- [ ] `sqlite3_vfs` struct with `xOpen`, `xRead`, `xFileSize`, etc.
- [ ] On open: download snapshot + WAL from bucket to local
- [ ] On read: page-fault from local copy
- [ ] No FUSE needed โ€” pure VFS interface

### P3.2 Directory watcher
**`examples/directory_watcher.rs`** โ€” Auto-backup new .db files.
- [ ] Watch directory for new `.db` files via `inotify` / `notify` crate
- [ ] Auto-create `DurabilityLayer` for each new DB
- [ ] Handle DB deletion (shutdown + remove from map)

### P3.3 Benchmarks vs Litestream
**`scripts/benchmark.sh`** โ€” Same workload, compare metrics.
- [ ] N writes/sec for M minutes
- [ ] Compare: CPU, memory, network egress, S3 request count
- [ ] Scenarios: idle, steady write, burst write, snapshot during write

### P3.4 Config from environment variables
**`src/config.rs`** โ€” Configure without code changes.
- [ ] `WAL_BACKUP_POLL_INTERVAL_MS`, `WAL_BACKUP_SYNC_MODE`
- [ ] `WAL_BACKUP_SNAPSHOT_THRESHOLD`, `WAL_BACKUP_SNAPSHOT_INTERVAL_SECS`
- [ ] `WAL_BACKUP_RESTORE_BEHAVIOR`, `WAL_BACKUP_MAX_WAL_SIZE`

### P3.5 Restore progress reporting
**`src/restore.rs`** โ€” Callback for download progress.
- [ ] Add `RestoreProgress { bytes_downloaded, total_bytes, stage }`
- [ ] Optional callback in `RestoreEngine`
- [ ] CLI shows progress bar

### P3.6 macOS / Windows support
**`src/connection.rs`** โ€” `flock` is Unix-only.
- [ ] `#[cfg(unix)]` โ€” use `libc::flock` (current)
- [ ] `#[cfg(windows)]` โ€” use `LockFileEx` (Windows API)
- [ ] Test on macOS + Windows in CI

### P3.7 ARM / Docker cross-compilation
- [ ] `bundled` SQLite compiles for ARM64
- [ ] CI matrix: x86_64 + aarch64 + wasm32 (if relevant)
- [ ] Docker image with `wal-backup` CLI

### P3.8 Top-level crate re-exports
**`src/lib.rs`** โ€” Review public API for ergonomics.
- [ ] Re-export common types at crate root
- [ ] Add doc examples for all public items
- [ ] Audit `pub` vs `pub(crate)` visibility

### P3.9 Rate-limited sync mode
**`src/replication/shipper.rs`** โ€” Limit request rate to S3.
- [ ] `SyncMode::RateLimited(rps: u32)` โ€” max requests per second
- [ ] Useful for providers with request-based billing or rate limits

### P3.10 Backup integrity check (offline CLI tool)
**`src/bin/wal-backup.rs`** โ€” `wal-backup check --bucket X --prefix Y`.
- [ ] Download manifest
- [ ] Download snapshot, verify SHA256
- [ ] Download all segments, verify SHA256 against manifest
- [ ] Report integrity score: "โœ… All checksums match" or "โŒ N segments corrupted"

---

## ๐Ÿงช P4 โ€” Test Infrastructure

### P4.1 CI: Run E2E tests against real S3 (scheduled)
**`.github/workflows/ci.yml`**
- [ ] Add nightly E2E run against OVH S3 or MinIO
- [ ] Use GitHub Actions secrets for credentials
- [ ] Add status badge to README

### P4.2 CI: Enforce --test-threads=1
- [ ] Add `--test-threads=1` to CI config
- [ ] Document recommended invocation in CONTRIBUTING.md

### P4.3 Coverage reporting
- [ ] `cargo llvm-cov` or `cargo tarpaulin`
- [ ] Set coverage threshold in CI (target: >80%)
- [ ] Add coverage badge to README

### P4.4 CI: clippy + fmt check on PR
- [ ] `cargo clippy --all-targets --all-features -- -D warnings`
- [ ] `cargo fmt --check`
- [ ] Block PR merge on failures

---

## โœ… Done (prior work, not actionable)

- [x] All core features: WAL shipping, snapshots, compaction, GC, backpressure
- [x] E2E verified against OVH S3 (5 phases, 10K rows)
- [x] Bugfixes B1-B4 (WAL spam, duplicate snapshot, streaming upload, memory compaction)
- [x] CLI binary: restore/verify/status/--force-takeover
- [x] S3 cloud example, crash writer example
- [x] Kill -9 crash recovery verified
- [x] Daemon example, multi-tenant API, CI pipeline
- [x] Audits v1, v2, v3 with all bugs fixed
- [x] Corruption prevention guard plan
- [x] Multi-writer analysis document
- [x] Lifecycle test + extensive E2E (T1-T5) + edge cases (E1-E4)
- [x] Stale generation file guard
- [x] **All 16 Audit v3 fixes applied:**
  - [x] C1-C8 (all critical bugs)
  - [x] W2, W6, W8, W10, W11, W12, W13, W14, W18
- [x] **P0 fixes (6 of 9 complete, 3 remaining):**
  - [x] P0.2: EncryptedBucketStore::get_file streaming (OOM fix)
  - [x] P0.3: segment_checksums pruning on GC + salt change
  - [x] P0.4: crash-atomic restore rename protocol with marker file
  - [x] P0.5: manifest version check on deserialization
  - [x] P0.6: NamedTempFile for compaction (RAII cleanup + symlink-safe)
  - [x] P0.8: zeroize_derive feature + Aes256Gcm auto-zeroize
  - [ ] P0.7: compressed/encrypted `put_file` temp files (low-risk, documented)
  - [ ] P0.9: A10 flaky test (~3%, pre-existing, not P0-related)
  - [ ] P0.1: publish to crates.io

---

## ๐Ÿ“Š Summary

| Tier | Total | Open | Done |
|------|-------|------|------|
| **P0** (blocking publish) | 9 | 4 | 5 |
| **P1** (Litestream gaps) | 6 | 6 | 0 |
| **P2** (quality) | 10 | 10 | 0 |
| **P3** (nice-to-have) | 10 | 10 | 0 |
| **P4** (test infra) | 4 | 4 | 0 |
| **Prior work** | โ€” | 0 | 25+ |
| **Total** | **39** | **34** | **30+** |

> **First target:** Clear P0 (4 remaining of 9) โ†’ publish crates.io โ†’ then P1 (6 items, ~14 days) โ†’ "Litestream replacement" ready