# wal-backup Full Audit — 2026-05-18
## 🔴 Bugs (will cause data loss or corruption)
### 1. `shutdown()` does NOT ship pending WAL frames before checkpoint ✅ FIXED
**File:** `src/connection.rs:672`
**Original:** The shipper was **aborted** before it could ship the last batch of WAL frames. Then `wal_checkpoint(FULL)` moved those unshipped frames into the DB. But they were never uploaded to S3.
**Fix:** `shutdown()` now calls `sync_now()` before aborting the shipper. This ensures all pending WAL frames are shipped to the bucket before checkpoint. The `sync_now()` timeout (5s) prevents blocking forever.
### 2. `writer.json` prevents server takeover ✅ FIXED
On shutdown, `lock.json` is deleted but `writer.json` persists. If Server A is decommissioned and Server B starts with a different `writer_id`, B gets `Error::WrongWriter`.
**Fix:** Added `--force-takeover` flag to `wal-backup restore` CLI command. Deletes `writer.json` and `lock.json` from the bucket before opening. Documented in the error message.
### 3. `local_is_newer_than_manifest()` uses file mtime — unreliable ✅ FIXED
**File:** `src/restore.rs:163`
**Original:** Compared local DB file modification time against `manifest.last_updated`. File mtime can change from `touch`, `rsync`, `cp`, etc. This can cause a false "local is newer" detection, leading to uploading a stale local DB as a snapshot, overwriting newer data in the bucket.
**Fix:** Replaced mtime-based comparison with generation-based comparison using a sidecar file (`db.generation`).
- On restore/upload: write manifest generation to `.generation` sidecar
- On shutdown: write current bucket manifest generation to sidecar
- On open: compare local generation vs bucket generation instead of mtime
- If no generation file exists (DB created outside wal-backup), assume local IS newer (matches first-run behavior)
- If generation file exists and local gen <= bucket gen → local is NOT newer (prevents `touch`/`rsync` false positives)
---
## 🟡 Concerns (won't cause data loss but are risky)
### 4. Encrypted `get_file()` loads full plaintext into memory
**File:** `src/storage/encrypted.rs:172`
AES-GCM requires the full ciphertext for authentication, so the current approach of `decrypt_outer()` → full `Vec<u8>` in memory is **unavoidable for AES-GCM**. But the chunk-writing to disk is cosmetic — the full plaintext was already allocated.
**Impact:** For large databases (>1GB), this means >1GB in memory during restore. The compressed store avoids this by streaming the decompress, but encryption busts the stream.
**Fix (future):** Switch to a streaming AEAD like AES-GCM-SIV or XChaCha20-Poly1305 with chunked encryption. This is a breaking format change.
### 5. `put_if_not_exists` fallback has a race condition
**File:** `src/storage/mod.rs` (ObjectStoreBucket impl)
```rust
Err(object_store::Error::NotImplemented) => {
// Fall back to get-then-put for stores that don't support Create mode
let existing = self.inner.get(&path).await?;
if existing.is_none() {
self.inner.put(&path, data.into()).await?;
} else {
return Err(Error::PreconditionFailed { ... });
}
}
```
Between `get()` returning `None` and `put()`, another process can create the object. This is a classic TOCTOU race.
**Impact:** Only affects local filesystem stores (which don't support `PutMode::Create`). Real S3 stores support it. The race window is tiny and only matters during lock/writer acquisition. If it fires, the `verify_writer_id()` re-read logic handles it correctly.
**Verdict:** Acceptable for testing. The code already handles the race in `verify_writer_id()` by re-reading on `PreconditionFailed`.
### 6. Manifest `last_updated` is a String, not a timestamp
**File:** `src/replication/manifest.rs`
`last_updated: String` is used for conflict detection (`conflict_level()`). It's parsed to `DateTime<Utc>` on every comparison. If parsing fails, the comparison falls through to `ConflictLevel::None`.
**Impact:** If a manifest gets corrupted (bad UTF-8 in timestamp), conflict detection silently fails and both writers proceed.
**Verdict:** Low risk. The timestamp is set by `chrono::Utc::now().to_rfc3339()` which always produces valid output. External corruption would be caught by the manifest checksums on restore.
### 7. Snapshot manager clears `l1_files` and `l1_max_frame` on retry
**File:** `src/replication/snapshot.rs:344-345`
When the snapshot manager gets `PreconditionFailed` on manifest write, it re-reads the remote manifest and overwrites snapshot fields. But it also clears `remote.l1_files` and sets `remote.l1_max_frame = None`. This is correct for a fresh snapshot (L1 files are invalidated by a new snapshot), but if the remote manifest has L1 files from a compaction that happened AFTER the snapshot was taken, those L1 files are lost.
**Impact:** Low. Compaction and snapshotting are on the same server. The snapshot manager takes the snapshot, then writes the manifest. Compaction writes happen in the shipper. The order is: snapshot → shipper sees new salt → shipper compacts later. So L1 files in the remote manifest at snapshot time are from before the snapshot and should be cleared.
**Verdict:** Correct behavior, but worth a comment.
### 8. No `sync_all()` on restore WAL temp file ✅ FIXED
**File:** `src/restore.rs` (`download_wal_segments_to`)
The WAL temp file (`wal.restore-tmp`) was written with `flush()` but no `sync_all()`. On a system crash, the WAL data may not be durable before the atomic rename.
**Fix:** Added `file.sync_all().await?` after `flush()`.
---
## 🟢 Observations (correct behavior, worth noting)
### 9. Writer identity verification is defense-in-depth
`verify_writer_id()` is called at:
- `open()` — before anything else
- Every shipper loop iteration
- Every snapshot loop iteration
If another process overwrites `writer.json`, the next loop iteration detects it and stops the background tasks. This is excellent defense-in-depth.
### 10. Atomic lock acquisition is correct
`put_if_not_exists` for new lock creation → atomic on S3.
`put_if_match` with etag for stale lock acquisition → atomic on S3.
Heartbeat uses `put_if_match` → detects stolen lock.
The only gap is the `NotImplemented` fallback (see #5), which is only for testing.
### 11. Restore is properly all-or-nothing
Snapshot → `db.restore-tmp`, WAL → `wal.restore-tmp`, verify both, then rename both. If any step fails, both temp files are cleaned up. ✅
### 12. Checksums are verified before restore commits
Snapshot checksum is verified after download. L1 and L0 segment checksums are verified during `download_wal_segments_to()`. If any checksum fails, the error propagates up and cleanup runs. ✅
### 13. Manifest merge prevents checksum race
The shipper merges `snapshot`, `snapshot_checksum`, and `db_size` from the remote manifest before writing. This prevents the shipper from overwriting a correct snapshot checksum with stale data. ✅
### 14. Snapshot manager handles PreconditionFailed correctly
On `PreconditionFailed`, re-reads remote manifest, updates snapshot fields, retries. ✅
### 15. `force_snapshot()` prevents duplicate
Clears `force_next` after the direct `take_snapshot()` call, preventing the run loop from taking a redundant second snapshot. ✅
### 16. Kill -9 is safe
The shipper and snapshot manager are stateless loops — they don't hold locks in memory. The flock is kernel-released on process death. The lock.json goes stale after 30s. The WAL frames already shipped to S3 are durable. ✅
---
## 📊 API Surface Audit
### Public types that should stay public ✅
- `DurabilityLayer` — the main entry point
- `Config` — configuration builder
- `SyncMode`, `RestoreBehavior` — config enums
- `Error`, `Result` — error handling
- `BucketStore` — trait for storage backends
- `ObjectStoreBucket` — S3 implementation
- `CompressedBucketStore`, `EncryptedBucketStore` — stacking (feature-gated)
- `Manifest`, `L1File` — needed for custom restore logic
- `WalFile`, `WalFrame`, `WalHeader` — needed for WAL inspection
- `Metrics`, `NoopMetrics` — custom metrics
- `HealthReport` — health status
### Public methods that should be `pub(crate)` 🔧
- `Manifest::set_last_updated_str()` — test-only, panics on bad input
- `Manifest::with_last_updated()` — test-only, panics on bad input
- `Manifest::serialize()` / `deserialize()` — could be `pub(crate)` since users don't need raw manifest access
### Missing from public API
- No way to get the current `Manifest` from `DurabilityLayer` (users can't inspect bucket state programmatically)
- No `DurabilityLayer::bucket()` accessor (can't inspect which bucket/prefix is in use)
- `WalParser` is `pub` in `wal/parser.rs` but not re-exported from `lib.rs`
---
## 📊 Test Coverage Audit
| Config validation | ✅ 9 tests | Good |
| WAL parser | ✅ 12 tests | Good |
| Manifest conflict | ✅ 3 tests | Good |
| Shipper sync | ✅ 8 tests | Good |
| Shipper GC | ✅ 4 tests | Good |
| Shipper compaction | ✅ 4 tests | Good |
| Shipper backpressure | ✅ 2 tests | Good |
| Snapshot | ✅ 5 tests | Good |
| Restore | ✅ 8 tests | Good |
| Restore checksum | ✅ 4 tests | Good |
| Restore atomic | ✅ 2 tests | Good |
| Storage | ✅ 3 tests | Good |
| Compression | ✅ tests | Good |
| Encryption | ✅ tests | Good |
| Error helpers | ✅ 6 tests | Good |
| Connection (flock, writer, lock) | ✅ 13 tests | Good |
| **E2E against real S3** | ✅ 5 phases | Good |
| **Lifecycle (start/stop/kill)** | ✅ 3 phases | Good |
### Missing test coverage
- **Shutdown with pending frames:** No test verifies that `shutdown()` ships all pending WAL frames before checkpoint
- **Kill -9 during snapshot upload:** No test verifies bucket state is consistent after mid-snapshot crash
- **Concurrent shipper + snapshot:** No test with both running simultaneously (the integration tests do this implicitly but don't verify manifest consistency)
- **Corrupt manifest in bucket:** No test for `validate_manifest_against_bucket()` detecting missing objects
- **Encrypted + compressed restore:** No test verifying the full stacking round-trips through both layers
---
## Summary
| 🟢 OK | 8 | #9-16 |
### All bugs fixed:
1. **#1** ✅ — `shutdown()` now calls `sync_now()` before aborting the shipper
2. **#2** ✅ — Added `--force-takeover` CLI flag to delete writer.json + lock.json
3. **#3** ✅ — Replaced mtime comparison with generation-based sidecar file (`.generation`)
4. **#8** ✅ — Added `sync_all()` on WAL temp file during restore
### Remaining concerns (not data-loss risks):
- #4: Encrypted get_file loads full plaintext (unavoidable with AES-GCM)
- #5: put_if_not_exists fallback has TOCTOU (only for local filesystem testing)
- #6: Manifest last_updated is a String (parsing failure skips conflict detection)
- #7: Snapshot manager clears L1 on retry (correct, needs comment)