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 Full Code Audit — 2026-05-19

## Source: 19 files, ~5600 lines (src/)

---

## 🔴 Bugs (data loss / corruption risk)

### 1. `EncryptedBucketStore::put_file()` loads entire DB into memory

**File:** `src/storage/encrypted.rs:160`

```rust
async fn put_file(&self, key: &str, path: &std::path::Path) -> Result<()> {
    let data = tokio::fs::read(path).await?;  // ← full DB in memory
    let encrypted = self.encrypt_with(self.version, &data)?;
    self.inner.put(key, Bytes::from(encrypted)).await
}
```

For a 2GB database, this means **4GB in RAM** simultaneously (plaintext + ciphertext). This contradicts the `BucketStore::put_file()` trait doc: *"Stream a local file to object storage. Avoids loading the entire file into memory."*

**Impact:** OOM on large databases. The `ObjectStoreBucket::put_file()` correctly uses streaming multipart, but encryption busts the stream because AES-GCM needs the full plaintext.

**Severity:** 🔴 — will crash the process on large DBs. But only triggers when both encryption is enabled AND a snapshot is taken (not on regular WAL segments, which use `put()`).

**Fix options:**
- (a) Encrypt in chunks using a streaming AEAD (XChaCha20-Poly1305 + nonce-per-chunk). Breaking format change.
- (b) Document the memory ceiling: "encryption + snapshot requires ~2x DB size in RAM"
- (c) For now: cap `put_file` encrypted path at 1GB, error clearly above that

### 2. `CompressedBucketStore::put_file()` loads entire file into memory

**File:** `src/storage/compressed.rs` 

Same issue as #1 but for compression. The `put_file()` reads the entire file, compresses it, then uploads. For a 2GB snapshot that compresses to 500MB, you need ~2.5GB in RAM.

**Impact:** Same as #1 — OOM on large databases.

**Fix:** Stream compression to a temp file, then `put_file()` the temp file through the inner store.

### 3. `CompressedBucketStore::get_file()` loads full compressed object into memory

**File:** `src/storage/compressed.rs:101`

```rust
let compressed = match self.inner.get(key).await? {
    Some(c) => c,  // ← full compressed Bytes in memory
};
let compressed_bytes = compressed.to_vec();  // ← another copy
```

For a 500MB compressed snapshot, this is 1GB in memory (Bytes + Vec). The comment says "Memory usage is bounded by the decompress buffer" but that's only for the *output* — the *input* is fully loaded.

**Impact:** High memory usage during restore. Not as bad as #1/#2 since compressed data is smaller, but still contradicts the trait doc.

**Fix:** Use `inner.get_file()` to stream compressed data to a temp file, then decompress from file to file in `spawn_blocking`.

### 4. `generation` uses `wrapping_add` — silent overflow after 2^64 writes

**File:** `src/replication/manifest.rs:108`

```rust
self.generation = self.generation.wrapping_add(1);
```

After 2^64 manifest updates, `generation` wraps to 0. This would cause `local_is_newer_than_manifest()` to incorrectly think the local DB is newer (gen 0 = fresh bucket), potentially uploading a stale local as snapshot and overwriting bucket data.

**Impact:** Astronomically unlikely (2^64 = 1.8×10^19 writes), but if it happens, it's a silent corruption event.

**Fix:** Use `checked_add(1)` and return an error on overflow. Or saturating add. The manifest update should fail rather than silently wrap.

---

## 🟡 Concerns (won't cause data loss but are risky)

### 5. `CompressedBucketStore::get_with_etag()` returns placeholder ETag `"decompressed"`

**File:** `src/storage/compressed.rs:72`

```rust
Ok(Some((Bytes::from(decompressed), "decompressed".to_string())))
```

The ETag is for the *compressed* data on S3, not the decompressed data. Returning a placeholder means any `put_if_match` using this ETag will fail or match the wrong version. Currently `get_with_etag` is only used for manifests (small JSON), so the placeholder is never used for conditional writes. But if someone calls `get_with_etag()` on a compressed key and then tries `put_if_match()`, it will silently use the wrong ETag.

**Fix:** Return the actual inner ETag from the compressed data, and document that callers must use `put_if_match` on the outer (compressed) key.

### 6. Same placeholder ETag issue in `EncryptedBucketStore::get_with_etag()`

**File:** `src/storage/encrypted.rs:148`

Same pattern as #5 — returns `"encrypted"` placeholder. Same analysis: currently safe because only used for manifests, but architecturally wrong.

### 7. `Manifest::conflict_level()` falls back to timestamp comparison on equal generation

**File:** `src/replication/manifest.rs:111`

```rust
ConflictLevel::None => {
    match (self.last_updated.parse(), remote.last_updated.parse()) {
        (Ok(local_dt), Ok(remote_dt)) if remote_dt > local_dt => ConflictLevel::RemoteAhead,
        _ => ConflictLevel::None,
    }
}
```

If two writers have the same generation (impossible in correct single-writer flow, but possible after `wrapping_add` overflow or manual manifest editing), the code compares timestamps. If parsing fails, it returns `ConflictLevel::None` — allowing both writers to proceed. This is the safe default (no false conflict), but it means two writers with identical generation could both write without detection.

**Impact:** Low — requires manifest tampering or generation overflow.

### 8. Snapshot retry doesn't preserve `shipped_frames` or `segment_checksums`

**File:** `src/replication/snapshot.rs:340-345`

When the snapshot manager gets `PreconditionFailed` and re-reads the remote manifest, it sets:
```rust
remote.shipped_frames = 0;
remote.l1_files.clear();
remote.l1_max_frame = None;
```

But it doesn't preserve `remote.segment_checksums` from the original remote manifest — those are just carried through implicitly (the `remote` deserialized manifest already has them). This is actually fine, but the asymmetry with the explicit clearing of `l1_files` and `shipped_frames` is confusing. Worth a comment explaining why `segment_checksums` is preserved.

### 9. `restore.rs`: Empty WAL file created without `sync_all()`

**File:** `src/restore.rs:358`

```rust
tokio::fs::File::create(&wal_tmp_path).await?;
```

When there are no WAL frames, an empty WAL file is created but not `sync_all()`'d before the atomic rename. This is inconsistent with the fix for the WAL temp file that does call `sync_all()`. The empty file doesn't have data to sync, but for consistency and defense-in-depth, it should match.

**Fix:** Add `file.sync_all().await?` after creating the empty WAL file.

### 10. `validate_manifest_against_bucket()` does a full `get()` for every object

**File:** `src/connection.rs:729`

The validation downloads the full content of every snapshot, L1, and L0 segment just to check existence. For a bucket with many segments, this is:
- Slow (N GET requests)
- Expensive (egress on paid S3)
- Unnecessary (HEAD request would suffice)

**Fix:** Use `bucket.exists()` instead of `bucket.get()` for existence checks. Only use `get()` when you need to verify content (checksums).

### 11. Integration tests flaky when run in parallel (~3% failure rate)

**File:** `tests/integration_tests.rs`, `tests/connection_tests.rs`

Running `cargo test --all-features` (parallel) causes intermittent failures in different tests each time. All pass with `--test-threads=1`. Root cause: tests share temp directory namespace and SQLite file paths may collide when parallel.

**Fix:** Use `tempfile::TempDir` with unique prefixes per test, or enforce `--test-threads=1` in the test harness.

---

## 🟢 Observations (correct, worth documenting)

### 12. Encryption + compression stacking order is correct

The recommended stacking order is: `CompressedBucketStore(EncryptedBucketStore(inner))` — encrypt first, then compress. This is correct because encrypted data is high-entropy and doesn't compress well. But note that `put_file()` on the compressed outer layer reads the full file into memory (see #2), so the streaming benefit of `put_file()` is lost when compression or encryption is in the stack.

### 13. `shutdown()` properly syncs before aborting ✅

`sync_now()` is called before aborting background tasks. The generation sidecar is written after reading the manifest. Lock is deleted. Checkpoint happens last. ✅

### 14. Atomic restore is correct ✅

Snapshot → `db.restore-tmp`, WAL → `wal.restore-tmp`, verify checksums, then rename both. Temp files cleaned up on failure. ✅

### 15. Writer identity verification is defense-in-depth ✅

Checked at open, every shipper loop, every snapshot loop. `WrongWriter` error is clear and actionable. ✅

### 16. Manifest merge prevents checksum race ✅

Shipper merges `snapshot`, `snapshot_checksum`, `db_size` from remote manifest before writing. Snapshot manager handles `PreconditionFailed` with retry. ✅

### 17. Key zeroization on Drop ✅

`EncryptedBucketStore::Drop` calls `zeroize` on the current key and clears past keys. ✅

### 18. Zip bomb protection ✅

`CompressedBucketStore` enforces a 2GB max decompressed size limit. ✅

### 19. Flock is correct ✅

`unsafe { libc::flock(fd, 2 | 4) }` (LOCK_EX | LOCK_NB) on `.db.lock` sidecar. Kernel-released on process death. PID written for diagnostics. ✅

### 20. WAL checksum validation is thorough ✅

Cumulative checksums verified per-frame. Big/little endian handled via magic number. ✅

---

## 📊 Summary

| Severity | Count | Items |
|----------|-------|-------|
| 🔴 Bug | 4 | #1 (encrypt put_file memory), #2 (compress put_file memory), #3 (compress get_file memory), #4 (generation wrapping_add) |
| 🟡 Concern | 7 | #5 (compressed etag), #6 (encrypted etag), #7 (equal-gen timestamp), #8 (snapshot retry segments), #9 (empty WAL sync_all), #10 (validate uses get not exists), #11 (test parallelism) |
| 🟢 OK | 9 | #12-20 |

### Priority fixes:

1. **#1 + #2**: `put_file()` on encrypted/compressed stores loads full file into memory. This is the most impactful issue — will OOM on large DBs. Fix: stream to temp file, then upload.
2. **#3**: `get_file()` on compressed store loads full compressed data. Fix: use `inner.get_file()` then decompress file-to-file.
3. **#4**: `generation` uses `wrapping_add` — should use `checked_add` or `saturating_add`.
4. **#5 + #6**: Placeholder ETags — return real inner ETags.
5. **#9**: Add `sync_all()` to empty WAL file creation in restore.
6. **#10**: Use `exists()` instead of `get()` in bucket validation.
7. **#11**: Fix test parallelism (unique temp dirs or `--test-threads=1`).