lease: round-3 fixes to replicate before start (#1290)
H1: an unpinned Replicate pins before deciding and holds the pin through its first sync. H2: a full image gets 2 min plus the size at 1 MiB/s. M1/M2: the clean record lives in the agent continuity directory, written via CreateTemp and trusted only as a regular file. M3: a full image must be uploaded before Replicate returns. A pinned start retries replica reads within firstSyncTimeout. Tests: one per fix, each failing on f1fe437e; four existing tests start their failing replica after start.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+645
−152
docs/superpowers/specs/2026-11-19-replicate-before-start.md+64 −72internal/activator/harelease_test.go+26 −6internal/activator/pendingwake_linux_test.go+12 −3internal/host/agent.go+6 −0internal/lease/continuity.go+200 −55internal/lease/continuity_round3_test.go+260 −0internal/lease/continuity_test.go+25 −5internal/lease/export_test.go+20 −0internal/lease/fence_test.go+18 −2internal/lease/gentake_test.go+7 −1internal/lease/release_test.go+7 −8
diff --git a/docs/superpowers/specs/2026-11-19-replicate-before-start.md b/docs/superpowers/specs/2026-11-19-replicate-before-start.md| index 6ea8cb039..2922a56e0 100644 |
| --- a/docs/superpowers/specs/2026-11-19-replicate-before-start.md |
| +++ b/docs/superpowers/specs/2026-11-19-replicate-before-start.md |
| @@ -1,89 +1,81 @@ |
| # Replicate before start |
| -Discussion #1290. Round 2 of 3, after Astra's round-1 rework. |
| +Discussion #1290. Round 3: the fixes from the review of f1fe437e. |
| ## The invariant |
| A replica either continues, without a gap, the WAL its last clean close |
| -left, or it starts from a full snapshot of the live file. A wake must not |
| -serve until one of the two is true. Every write must reach the replica, or |
| -be included in a snapshot taken before the wake serves. |
| +left, or it restarts from an uploaded full image of the live file. A start |
| +does not serve until one of the two holds. |
| Two mechanisms carry it, both in `internal/lease`: |
| -1. **The clean record.** A close whose final sync and store close both |
| - succeed writes `carlos-clean.json` in the litestream meta directory. It |
| - holds the newest local L0 TXID and the size and mtime of the database |
| - and its WAL. Starting replication (`ProtectStart`, `Replicate` or |
| - `Checkpoint`) deletes the record first and fsyncs the directory. The |
| - files count as continuous only if the record is there and matches them |
| - exactly. A crash, a lost meta directory, a restore, a process that wrote |
| - while nothing replicated, or a repair that failed all leave no matching |
| - record, so the next start writes a full snapshot. That covers Astra's |
| - High 1 (a retry still repairs) and High 2 (missing local metadata). |
| -2. **The start pin.** `ProtectStart`, called before anything that can |
| - migrate runs, holds a SQLite read transaction on a continuous database. |
| - While that reader is held, SQLite can restart the WAL at most once and |
| - cannot backfill any frame written after the pin, so every write the |
| - process makes stays in the WAL until litestream reads it. `Replicate` |
| - takes the pin over. It releases the pin only after litestream's own init |
| - has taken its read lock (a forced, bounded local sync). If the files are |
| - not continuous, nothing is pinned, and `Replicate` makes sure the replica |
| - restarts from a full image before it returns. That image is litestream's |
| - own first file when that file holds every page (a first replication, or |
| - a WAL litestream saw truncated). Otherwise `Replicate` writes a level-9 |
| - snapshot of the live file. |
| +1. **The clean record.** A close whose final sync and store close succeed |
| + writes a record of the newest local L0 TXID and the database and WAL |
| + sizes and mtimes. The record lives in the agent's own directory |
| + (`SetContinuityDir`, `<data>/.continuity`), named from the database |
| + path, never in the app's tree, so the app cannot forge it. It is written |
| + through `os.CreateTemp` and a rename, and trusted only if `Lstat` shows a |
| + regular file. Every start (`ProtectStart`, `Replicate`, `Checkpoint`) |
| + deletes it first. With no directory set, nothing is trusted. |
| +2. **The pin.** A SQLite read transaction, taken *before* the record is |
| + compared with the files. While it is held, the WAL can restart at most |
| + once and nothing written after it can be backfilled, so a process's |
| + writes stay in the WAL until litestream reads them. The pin is held |
| + through litestream's first sync, which takes litestream's own lock. A |
| + database that cannot be pinned (no WAL or shm, not in WAL mode) is not |
| + continuous. |
| -## Wake paths |
| +When continuity is not proven, `Replicate` returns only once a full image |
| +is **uploaded**: either litestream's own first file, when it holds every |
| +page (a first start, or a WAL that was truncated or removed), once the |
| +replica's position shows the replica's own monitor has uploaded it, or |
| +else a level-9 snapshot of the live file. |
| -- **Ordinary wake (`doWakeOnce`).** `ProtectStart` runs after restore and |
| - identity, before the seed (step 3) and the spawn (step 4). Step 4 |
| - includes the rootfs release commands (`spawnPlanned`, the hold's pinned |
| - start, `releaseInWake`), so they run pinned. A hold swap's start is a |
| - pinned wake. An overlap swap starts its successor while the incumbent's |
| - replicator runs. |
| -- **Restore.** A restored or replaced file never matches the record, so the |
| - next `Replicate` writes a full snapshot. |
| -- **HA leases.** Same `Replicate`, with no exemption. The HA finalization |
| - writes the record only when its sync and close succeed. |
| -- **Moves (`Held.Checkpoint`).** Same check. Not continuous means a full |
| - snapshot before the checkpoint's receipt. A successful checkpoint writes |
| - the record. |
| -- **Claim wake (`doClaimWake`).** Claims are shelved and host writes are off |
| - on every box, so it is not reordered. It still cannot serve a gap: with no |
| - pin, `Replicate` decides continuity itself, and a process that wrote first |
| - fails the match and gets a full snapshot before `Publish`. |
| -- **Unit tenants and demos.** A unit tenant is replicated by the box-wide |
| - litestream unit, which runs all the time, so it has no start gap. A |
| - demo's lease is local. Neither takes a pin. |
| -- **First start (no database file).** The process starts first, and |
| - `Replicate` writes a full snapshot before the wake serves. No bootstrap |
| - file: creating the database ahead of the app would fix `page_size`, |
| - `auto_vacuum` and encoding before the app chooses them, and break the |
| - "file absent means fresh" rule that seeds and frameworks rely on. A |
| - database that is minutes old is cheap to snapshot. With nothing earlier |
| - in the replica, there is no chain to continue wrongly. |
| +## Paths |
| + |
| +- **Ordinary wake.** `ProtectStart` runs after restore and before the seed, |
| + release commands and the process. A hold swap's start is such a wake. An |
| + overlap successor starts while the incumbent's replicator runs. |
| +- **Claim wake, and any `Replicate` with no `ProtectStart` before it.** |
| + `Replicate` pins first, decides under the pin, and holds the pin through |
| + its first sync. A process that is already running cannot slip a write |
| + between the decision and the pin. Anything it wrote earlier shows in the |
| + files and forces a full image; anything later stays in the WAL. Claims are |
| + off on every box, so the claim wake is not otherwise reordered. |
| +- **HA leases and moves (`Held.Checkpoint`).** Same rule, no exemption. |
| +- **Restore.** A replaced file never matches the record: a full image. |
| +- **Unit tenants and demos.** The box-wide litestream unit runs all the |
| + time; a demo's lease is local. Neither pins. |
| +- **First start.** The process starts first, then a full image is uploaded |
| + before the wake serves. No bootstrap file: creating the database ahead of |
| + the app would fix `page_size`, `auto_vacuum` and encoding before the app |
| + chooses them, and would break the "no file means fresh" rule that seeds |
| + rely on. |
| ## Failure behaviour |
| -`ProtectStart` failing (pin or record I/O) fails the wake before anything |
| -starts. litestream's init reads the replica's position, so a replica that |
| -cannot be reached now fails the wake too, where before the wake served and |
| -replication lagged. That is the price of "never unprotected". `Replicate`'s init is bounded (`firstSyncTimeout`, 30 s). If it |
| -fails or times out, `Replicate` fails, and the wake goes through |
| -`cleanupFailedWake` (process stopped, lease back). That is High 3. The |
| -person sees the wake fail with "replicate <host>: ..." in `carlos logs |
| ---stream platform`, and the edge answers as for any failed wake. A pinned |
| -wake adds one local sync (milliseconds, no S3 call). A snapshot wake also |
| -uploads one full snapshot, bounded by `gapSnapshotTimeout` (2 min). Only the |
| -first wake after an upgrade, a restore, a crash or a failed repair pays it. |
| -A slow or failing S3 upload in a continuous wake is the monitor's to retry, |
| -as before: the frames are already captured locally under litestream's lock. |
| +- The first sync is bounded by `firstSyncTimeout` (30 s). On a pinned, |
| + continuous start, a failure is retried with backoff inside that bound: a |
| + replica listing that fails once does not fail a wake whose WAL the pin |
| + holds. An unproven start is not retried; it fails the wake. |
| +- A full image gets 2 minutes plus the database's size at 1 MiB/s |
| + (`imageBudget`), so a large database stays wakeable. Every database |
| + takes one on its first wake after the upgrade. |
| +- Any failure fails the start. `cleanupFailedWake` stops the process and |
| + gives the lease back. The person sees "replicate <host>: ..." in `carlos |
| + logs --stream platform`, and the edge answers as for any failed wake. No |
| + record was written, so the next wake tries the full image again. |
| +- litestream's init reads the replica's position, so an unreachable replica |
| + fails wakes; before this change they served with replication lagging. |
| + Serving read-only is not a fallback: apps migrate on boot, so a |
| + "read-only" start would still write. |
| +- A continuous wake costs one local sync (milliseconds), plus retries only |
| + while the replica is failing. |
| ## A replica that is already broken |
| -No release before this one ever wrote a clean record. So the first |
| -`Replicate` of every database after the upgrade writes a full snapshot of |
| -the live file, and the newest restore then starts from it. Older poisoned |
| -L1-L3 files remain only on point-in-time paths before that snapshot, and |
| -age out with snapshot retention (7 days). |
| +No earlier release wrote a record. So each database's first start after |
| +the upgrade uploads a full image, and its newest restore starts from that |
| +image. Poisoned L1-L3 files remain only on point-in-time paths before it, |
| +and they age out with snapshot retention (7 days). |
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go| index 97eafcabb..f1364cf43 100644 |
| --- a/internal/activator/harelease_test.go |
| +++ b/internal/activator/harelease_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "errors" |
| "os" |
| "path/filepath" |
| + "slices" |
| "strconv" |
| "strings" |
| "sync" |
| @@ -856,6 +857,13 @@ func TestHAWakeRequestCounts(t *testing.T) { |
| return e, s.wakePathRequests(s.fx.Requests()[n:]) |
| } |
| e, reqs := wake() |
| + // litestream's monitor writes a fresh replica's first snapshot about a |
| + // second after it opens (#897), and a first wake now lasts until its |
| + // first image is uploaded (#1290), so that snapshot can land inside |
| + // it. It is the store's, not the wake path's. |
| + reqs = slices.DeleteFunc(reqs, func(r string) bool { |
| + return strings.HasPrefix(r, "PUT "+s.b.Cfg.hibernatePrefix(s.rt.Host)+"/0009/") |
| + }) |
| // A first wake: the lock's three, then the launch's publish of its |
| // minted secrets (Task 11): the sealed env, the sealed cutover marker |
| // (durability 3a) and the wake state objects, and the first manifest, |
| @@ -904,14 +912,20 @@ func (s *haSvc) wakePathRequests(reqs []string) []string { |
| if level, ok := strings.CutPrefix(r, "LIST "+prefix); ok && isReplicaLevelDir(level) { |
| continue |
| } |
| - // A compaction into levels 1-8 is the store's monitor finishing |
| - // the last session's work. Replicate's first sync (replicate |
| - // before start, #1290) readies the store before the monitor's |
| - // first pass, so one can land inside the wake. Snapshots (level 9) |
| - // and L0 files still count. |
| - if rel, ok := strings.CutPrefix(r, "PUT "+prefix); ok && len(rel) > 5 && isReplicaLevelDir(rel[:5]) && rel[:4] >= "0001" && rel[:4] <= "0008" { |
| + // litestream's own level 0-8 files: the full image a wake now |
| + // uploads before it serves when continuity is not proven (an HA |
| + // release truncates the WAL; replicate before start, #1290), and |
| + // compactions the store, ready earlier, finishes inside the wake. |
| + // They were the same requests a moment later. Snapshots (level 9) |
| + // still count. |
| + if rel, ok := strings.CutPrefix(r, "PUT "+prefix); ok && replicaDataFile(rel) { |
| continue |
| } |
| + if rel, ok := strings.CutPrefix(r, "PUT "+prefix+"g-"); ok { |
| + if _, file, ok := strings.Cut(rel, "/"); ok && replicaDataFile(file) { |
| + continue |
| + } |
| + } |
| // The same listing under a storage generation (g-N/NNNN/): the |
| // replicator of a generations wake writes there. |
| if rel, ok := strings.CutPrefix(r, "LIST "+prefix+"g-"); ok { |
| @@ -924,6 +938,12 @@ func (s *haSvc) wakePathRequests(reqs []string) []string { |
| return out |
| } |
| +// replicaDataFile reports whether rel is a litestream file of levels 0-8 |
| +// ("NNNN/<min>-<max>.ltx"), not a snapshot. |
| +func replicaDataFile(rel string) bool { |
| + return len(rel) > 5 && isReplicaLevelDir(rel[:5]) && rel[:4] <= "0008" && strings.HasSuffix(rel, ".ltx") |
| +} |
| + |
| // isReplicaLevelDir reports whether rel is one of litestream's level |
| // directories as a listing names it: four digits and a slash. |
| func isReplicaLevelDir(rel string) bool { |
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go| index 1296234f9..04a404179 100644 |
| --- a/internal/activator/pendingwake_linux_test.go |
| +++ b/internal/activator/pendingwake_linux_test.go |
| @@ -1610,8 +1610,13 @@ func TestFleetStopOfANeverCreatedDatabaseFinishes(t *testing.T) { |
| // before the wake) stays pending, the lease held and renewing. |
| func TestFleetStopOfAnUnsyncedDatabaseStaysPending(t *testing.T) { |
| r := newCheckpointRig(t, registry.PlacementTarget("pi")) |
| - t.Cleanup(r.fx.FailReplicaPuts(r.prefix)) |
| + // The bucket refuses writes once the wake is up: a wake whose first |
| + // image cannot be uploaded does not serve at all (replicate before |
| + // start, #1290). The row written after it is what the bucket never |
| + // receives. |
| e := r.wake(t) |
| + t.Cleanup(r.fx.FailReplicaPuts(r.prefix)) |
| + appendRow(t, r.rt.DBPath) |
| stopped := r.stop(e) |
| select { |
| case <-r.kept: |
| @@ -1853,14 +1858,18 @@ func (r *checkpointRig) assertHealedRelease(t *testing.T, rep signalRep, heal fu |
| // reaper releases it once the checkpoint is proven. |
| func TestFailedFleetWakeKeepsAnUnprovenCheckpoint(t *testing.T) { |
| r := newCheckpointRig(t, registry.PlacementTarget("pi")) |
| - heal := r.fx.FailReplicaPuts(r.prefix) |
| - t.Cleanup(heal) |
| + // The bucket refuses writes from just after the replica started: a |
| + // replica whose first image cannot be uploaded never starts at all |
| + // (replicate before start, #1290). |
| + heal := func() {} |
| + t.Cleanup(func() { heal() }) |
| var rep signalRep |
| r.a.retainDB = func(ctx context.Context, rt registry.Route, l Lease) (Rep, error) { |
| got, err := retainDatabase(ctx, rt, l) |
| if err != nil { |
| return got, err |
| } |
| + heal = r.fx.FailReplicaPuts(r.prefix) |
| rep = signalRep{Replicator: got.(*lease.Replicator), closed: make(chan error, 8)} |
| appendRow(t, rt.DBPath) // the boot's write |
| return rep, errors.New("the wake failed after its replica started") |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index be44cabf8..e5ffcaaac 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -613,6 +613,12 @@ func runAgent(args []string, buildClaims ClaimFactory) { |
| if err := lease.SetObligationDir(filepath.Join(dd, ".ha-owed")); err != nil { |
| log.Printf("agent: region HA: obligation store: %v (every HA wake on this box refuses until it opens)", err) |
| } |
| + // Replicate before start (#1290): clean records live in the agent's |
| + // own directory, outside every instance's tree. Without it nothing |
| + // is trusted and every start takes a full image. |
| + if err := lease.SetContinuityDir(filepath.Join(dd, ".continuity")); err != nil { |
| + log.Printf("agent: continuity records: %v (every start takes a full image)", err) |
| + } |
| if logSink != nil { // a typed-nil in the interface would NOT be nil |
| eb.Logs = logSink |
| } |
diff --git a/internal/lease/continuity.go b/internal/lease/continuity.go| index cc91c1222..53a608ff1 100644 |
| --- a/internal/lease/continuity.go |
| +++ b/internal/lease/continuity.go |
| @@ -2,7 +2,9 @@ package lease |
| import ( |
| "context" |
| + "crypto/sha256" |
| "database/sql" |
| + "encoding/hex" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -27,27 +29,68 @@ import ( |
| // succeeded writes it. Every start of replication deletes it first, so a |
| // crash, a lost meta directory, a restore, a process that wrote while |
| // nothing replicated, or a repair that failed all leave no record that |
| -// matches, and the next start snapshots. |
| +// matches, and the next start takes a full image. |
| +// |
| +// The record lives in the agent's own directory (SetContinuityDir), keyed |
| +// by the database path, never beside the database: the app can write |
| +// everything in its instance directory, and a record it could rewrite |
| +// would let it vouch for a gap. With no directory set, nothing is ever |
| +// recorded or trusted, so every start takes a full image. |
| // |
| // The start pin keeps a continuous database continuous across a process |
| // start. While a SQLite reader is held, the WAL can restart at most once |
| // and no frame written after the reader began can be backfilled, so |
| // whatever the process writes stays in the WAL until litestream reads it. |
| -// cleanRecordName is the clean record's file in the litestream meta |
| -// directory: losing the directory loses the record with it. |
| -const cleanRecordName = "carlos-clean.json" |
| - |
| // metaPathOf is the replicator's litestream meta directory for dbPath (the |
| // activator namespace newStore sets). |
| func metaPathOf(dbPath string) string { |
| return filepath.Join(filepath.Dir(dbPath), ".activator-"+filepath.Base(dbPath)+"-litestream") |
| } |
| -// cleanRecord is the state a clean close left: the newest local L0 file |
| -// and the database and WAL exactly as they were. |
| +var continuityDir struct { |
| + sync.Mutex |
| + dir string |
| +} |
| + |
| +// SetContinuityDir is where this process keeps clean records: a directory |
| +// of the agent's own, outside every instance's tree. Created 0700. |
| +func SetContinuityDir(dir string) error { |
| + if dir == "" { |
| + return errors.New("lease: an empty continuity directory") |
| + } |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + return fmt.Errorf("lease: continuity directory: %w", err) |
| + } |
| + continuityDir.Lock() |
| + continuityDir.dir = dir |
| + continuityDir.Unlock() |
| + return nil |
| +} |
| + |
| +// recordPath is dbPath's clean record: a name derived from the cleaned |
| +// absolute path, in the continuity directory. ok is false with no |
| +// directory set. |
| +func recordPath(dbPath string) (dir, path string, ok bool) { |
| + continuityDir.Lock() |
| + dir = continuityDir.dir |
| + continuityDir.Unlock() |
| + if dir == "" { |
| + return "", "", false |
| + } |
| + abs, err := filepath.Abs(dbPath) |
| + if err != nil { |
| + return "", "", false |
| + } |
| + sum := sha256.Sum256([]byte(filepath.Clean(abs))) |
| + return dir, filepath.Join(dir, hex.EncodeToString(sum[:16])+".json"), true |
| +} |
| + |
| +// cleanRecord is the state a clean close left: the database it is for, |
| +// the newest local L0 file, and the database and WAL exactly as they were. |
| type cleanRecord struct { |
| V int `json:"v"` |
| + DB string `json:"db"` |
| TXID uint64 `json:"txid"` |
| DBSize int64 `json:"db_size"` |
| DBMod int64 `json:"db_mtime_ns"` |
| @@ -63,7 +106,7 @@ func currentState(dbPath string) (cleanRecord, bool) { |
| if err != nil { |
| return cleanRecord{}, false |
| } |
| - rec := cleanRecord{V: 1, DBSize: fi.Size(), DBMod: fi.ModTime().UnixNano(), WALSize: -1} |
| + rec := cleanRecord{V: 2, DB: filepath.Clean(dbPath), DBSize: fi.Size(), DBMod: fi.ModTime().UnixNano(), WALSize: -1} |
| switch wi, err := os.Stat(dbPath + "-wal"); { |
| case err == nil: |
| rec.WALSize, rec.WALMod = wi.Size(), wi.ModTime().UnixNano() |
| @@ -83,14 +126,23 @@ func currentState(dbPath string) (cleanRecord, bool) { |
| } |
| // isContinuous reports whether the files are exactly as a clean close left |
| -// them. Anything unreadable is not proof. |
| +// them. The record must be a regular file (never a link), for this |
| +// database; anything unreadable is not proof. |
| func isContinuous(dbPath string) bool { |
| - raw, err := os.ReadFile(filepath.Join(metaPathOf(dbPath), cleanRecordName)) |
| + _, path, ok := recordPath(dbPath) |
| + if !ok { |
| + return false |
| + } |
| + fi, err := os.Lstat(path) |
| + if err != nil || !fi.Mode().IsRegular() { |
| + return false |
| + } |
| + raw, err := os.ReadFile(path) |
| if err != nil { |
| return false |
| } |
| var rec cleanRecord |
| - if json.Unmarshal(raw, &rec) != nil || rec.V != 1 { |
| + if json.Unmarshal(raw, &rec) != nil || rec.V != 2 { |
| return false |
| } |
| now, ok := currentState(dbPath) |
| @@ -99,21 +151,26 @@ func isContinuous(dbPath string) bool { |
| // recordClean writes the clean record for dbPath's files as they are now. |
| // Called only after a final sync and a store close that both succeeded. |
| +// The temporary file is a fresh one (O_EXCL), and the rename replaces |
| +// whatever is at the record's name rather than following it. |
| func recordClean(dbPath string) error { |
| + dir, path, ok := recordPath(dbPath) |
| + if !ok { |
| + return nil |
| + } |
| rec, ok := currentState(dbPath) |
| if !ok { |
| - return nil // nothing to vouch for: the next start snapshots |
| + return nil // nothing to vouch for: the next start takes a full image |
| } |
| raw, err := json.Marshal(rec) |
| if err != nil { |
| return err |
| } |
| - dir := metaPathOf(dbPath) |
| - tmp := filepath.Join(dir, cleanRecordName+".tmp") |
| - f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) |
| + f, err := os.CreateTemp(dir, ".clean-*.tmp") |
| if err != nil { |
| return err |
| } |
| + tmp := f.Name() |
| if _, err = f.Write(raw); err == nil { |
| err = f.Sync() |
| } |
| @@ -121,7 +178,7 @@ func recordClean(dbPath string) error { |
| err = cerr |
| } |
| if err == nil { |
| - err = os.Rename(tmp, filepath.Join(dir, cleanRecordName)) |
| + err = os.Rename(tmp, path) |
| } |
| if err != nil { |
| _ = os.Remove(tmp) |
| @@ -133,8 +190,11 @@ func recordClean(dbPath string) error { |
| // clearClean deletes the clean record, durably, before replication of |
| // dbPath starts. |
| func clearClean(dbPath string) error { |
| - dir := metaPathOf(dbPath) |
| - err := os.Remove(filepath.Join(dir, cleanRecordName)) |
| + dir, path, ok := recordPath(dbPath) |
| + if !ok { |
| + return nil |
| + } |
| + err := os.Remove(path) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| return nil |
| @@ -178,22 +238,14 @@ var starts = struct { |
| }{m: map[string]*Protection{}} |
| // ProtectStart runs before anything that can write dbPath starts. It |
| -// decides continuity, deletes the clean record, and pins a continuous |
| -// database. Replicate (or Checkpoint) of the same path takes the pin over. |
| -// An error means the start must not happen. |
| +// pins the database, decides continuity under the pin, and deletes the |
| +// clean record. Replicate (or Checkpoint) of the same path takes the pin |
| +// over. An error means the start must not happen. |
| func ProtectStart(dbPath string) (*Protection, error) { |
| ReleaseStart(dbPath) |
| - cont := isContinuous(dbPath) |
| - if err := clearClean(dbPath); err != nil { |
| - return nil, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, err) |
| - } |
| - p := &Protection{path: dbPath} |
| - if cont { |
| - pinned, err := p.pin() |
| - if err != nil { |
| - return nil, fmt.Errorf("lease: pin %s before start: %w", dbPath, err) |
| - } |
| - p.continuous = pinned |
| + p, err := protect(dbPath) |
| + if err != nil { |
| + return nil, err |
| } |
| starts.Lock() |
| starts.m[dbPath] = p |
| @@ -201,6 +253,25 @@ func ProtectStart(dbPath string) (*Protection, error) { |
| return p, nil |
| } |
| +// protect pins dbPath first and only then compares the files with the |
| +// clean record, so a process already running cannot write between the |
| +// decision and the pin: anything it wrote before shows in the files, and |
| +// anything after stays in the WAL. A database that cannot be pinned is not |
| +// continuous. The record is deleted before protect returns. |
| +func protect(dbPath string) (*Protection, error) { |
| + p := &Protection{path: dbPath} |
| + pinned, err := p.pin() |
| + if err != nil { |
| + return nil, fmt.Errorf("lease: pin %s: %w", dbPath, err) |
| + } |
| + p.continuous = pinned && isContinuous(dbPath) |
| + if err := clearClean(dbPath); err != nil { |
| + p.Release() |
| + return nil, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, err) |
| + } |
| + return p, nil |
| +} |
| + |
| // Drop releases p if it is still the pending protection of its path (a |
| // start that will not reach Replicate). A later start's protection of the |
| // same path is left alone. |
| @@ -270,36 +341,85 @@ func (p *Protection) pin() (bool, error) { |
| } |
| // beginContinuity is where Replicate and Checkpoint decide: the pin a |
| -// ProtectStart left, or, with none, the files' own state now. The clean |
| -// record is gone either way once it returns. |
| +// ProtectStart left, or, with none, a pin taken now (protect), held by the |
| +// caller through its first sync. A database that cannot be pinned is not |
| +// continuous. The clean record is gone either way once it returns. |
| func beginContinuity(dbPath string) (*Protection, bool, error) { |
| + defer continuityDecided() |
| if p := takeStart(dbPath); p != nil { |
| return p, p.continuous, nil |
| } |
| - cont := isContinuous(dbPath) |
| - if err := clearClean(dbPath); err != nil { |
| - return nil, false, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, err) |
| + p, err := protect(dbPath) |
| + if err != nil { |
| + if cerr := clearClean(dbPath); cerr != nil { |
| + return nil, false, fmt.Errorf("lease: clear the clean record of %s: %w", dbPath, cerr) |
| + } |
| + log.Printf("lease: %s: %v (the start takes a full image)", dbPath, err) |
| + return nil, false, nil |
| } |
| - return nil, cont, nil |
| + return p, p.continuous, nil |
| } |
| +// continuityDecided runs as beginContinuity returns: a test's window to |
| +// write the database between the decision and the replication start. |
| +var continuityDecided = func() {} |
| + |
| // firstSyncTimeout bounds the forced first sync that takes litestream's |
| -// read lock; gapSnapshotTimeout bounds a snapshot when continuity is not |
| -// proven. Either failing fails the start. |
| +// read lock. A full image's upload, litestream's or a snapshot, gets |
| +// gapSnapshotTimeout plus the time the database's size takes at |
| +// gapSnapshotMinRate bytes a second, so a large database stays wakeable. |
| +// Any of them failing fails the start. |
| var ( |
| - firstSyncTimeout = 30 * time.Second |
| - gapSnapshotTimeout = 2 * time.Minute |
| + firstSyncTimeout = 30 * time.Second |
| + gapSnapshotTimeout = 2 * time.Minute |
| + gapSnapshotMinRate int64 = 1 << 20 |
| + firstSyncRetryBase = 100 * time.Millisecond |
| ) |
| +// imageBudget is the time a full image of path's database may take. |
| +func imageBudget(path string) time.Duration { |
| + d := gapSnapshotTimeout |
| + if fi, err := os.Stat(path); err == nil && gapSnapshotMinRate > 0 { |
| + d += time.Duration(float64(fi.Size()) / float64(gapSnapshotMinRate) * float64(time.Second)) |
| + } |
| + return d |
| +} |
| + |
| +// firstSync is litestream's first sync, which takes its read lock and |
| +// reads the replica's position. A continuous, pinned start retries a |
| +// failure until firstSyncTimeout: a replica listing that fails once must |
| +// not fail a wake whose WAL the pin holds anyway. An unproven start does |
| +// not wait. |
| +func firstSync(ctx context.Context, db *litestream.DB, continuous bool) error { |
| + sctx, cancel := context.WithTimeout(ctx, firstSyncTimeout) |
| + defer cancel() |
| + wait := firstSyncRetryBase |
| + for { |
| + err := db.Sync(sctx) |
| + if err == nil && db.PageSize() == 0 { |
| + err = errors.New("the database did not initialize") |
| + } |
| + if err == nil || !continuous { |
| + return err |
| + } |
| + select { |
| + case <-sctx.Done(): |
| + return errors.Join(err, sctx.Err()) |
| + case <-time.After(wait): |
| + } |
| + wait = min(wait*2, 2*time.Second) |
| + } |
| +} |
| + |
| // startProtected is the first sync of a replication start, and, when |
| // continuity is not proven, the full image the replica restarts from. It |
| // returns once litestream holds its read lock and the replica either |
| -// continues or holds that image, or with the error that means the start |
| -// must not serve. |
| +// continues or holds that image, uploaded, or with the error that means |
| +// the start must not serve. |
| // |
| // The image is litestream's own when its first sync was a full one (a |
| -// first replication, or a WAL it could see was truncated or overwritten): |
| -// that file is captured locally and the monitor uploads it, as any other. |
| +// first replication, or a WAL it could see was truncated or removed): the |
| +// replica sync that uploads it must succeed before this returns. |
| // Otherwise a snapshot of the live file is written to the replica now. |
| func startProtected(ctx context.Context, db *litestream.DB, continuous bool) error { |
| if _, err := os.Stat(db.Path()); errors.Is(err, os.ErrNotExist) { |
| @@ -309,23 +429,24 @@ func startProtected(ctx context.Context, db *litestream.DB, continuous bool) err |
| return nil |
| } |
| before := newestLocalL0(db) |
| - sctx, cancel := context.WithTimeout(ctx, firstSyncTimeout) |
| - err := db.Sync(sctx) |
| - cancel() |
| - if err == nil && db.PageSize() == 0 { |
| - err = errors.New("the database did not initialize") |
| - } |
| - if err != nil { |
| + if err := firstSync(ctx, db, continuous); err != nil { |
| return fmt.Errorf("lease: first sync of %s: %w", db.Path(), err) |
| } |
| if continuous { |
| return nil |
| } |
| + sctx, cancel := context.WithTimeout(ctx, imageBudget(db.Path())) |
| + defer cancel() |
| if path, ok := firstLocalL0After(db, before); ok && fullImage(path) { |
| + pos, err := db.Pos() |
| + if err == nil { |
| + err = awaitUploaded(sctx, db, pos.TXID) |
| + } |
| + if err != nil { |
| + return fmt.Errorf("lease: upload of %s's full image: %w", db.Path(), err) |
| + } |
| return nil |
| } |
| - sctx, cancel = context.WithTimeout(ctx, gapSnapshotTimeout) |
| - defer cancel() |
| pos, err := db.Pos() |
| if err != nil { |
| return fmt.Errorf("lease: position of %s: %w", db.Path(), err) |
| @@ -345,6 +466,30 @@ func startProtected(ctx context.Context, db *litestream.DB, continuous bool) err |
| return nil |
| } |
| +// awaitUploaded waits until the replica's position reaches txid. Where |
| +// the replica's own monitor uploads (it holds the replica's lock while it |
| +// does), this watches rather than syncing a second time: a hung upload |
| +// ends at ctx, and the caller's store close cancels it. |
| +func awaitUploaded(ctx context.Context, db *litestream.DB, txid ltx.TXID) error { |
| + if !db.Replica.MonitorEnabled { |
| + // A one-shot store (a checkpoint) has no monitor to wait for: |
| + // nothing else holds the replica's lock, so sync it here. |
| + if err := db.Replica.Sync(ctx); err != nil { |
| + return err |
| + } |
| + } |
| + for { |
| + if db.Replica.Pos().TXID >= txid { |
| + return nil |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return fmt.Errorf("the replica is at %s, the image at %s: %w", db.Replica.Pos().TXID, txid, ctx.Err()) |
| + case <-time.After(50 * time.Millisecond): |
| + } |
| + } |
| +} |
| + |
| // newestLocalL0 is the highest TXID among the local L0 files (0: none). |
| func newestLocalL0(db *litestream.DB) ltx.TXID { |
| ents, _ := os.ReadDir(db.LTXLevelDir(0)) |
diff --git a/internal/lease/continuity_round3_test.go b/internal/lease/continuity_round3_test.go| new file mode 100644 |
| index 000000000..2569008f9 |
| --- /dev/null |
| +++ b/internal/lease/continuity_round3_test.go |
| @@ -0,0 +1,260 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| +) |
| + |
| +// Round 3 of #1290 (the review of f1fe437e). |
| + |
| +// H1: an unpinned Replicate racing a live process. The record is intact |
| +// and the process is open; it migrates right after the continuity |
| +// decision. Replicate must pin before it decides, and hold the pin |
| +// through its first sync. |
| +func TestUnpinnedReplicateRacingAProcessRestoresWhole(t *testing.T) { |
| + g := newGapRig(t) |
| + g.wake("first wake") |
| + app := openWakeApp(t, g.path) |
| + prev := continuityDecided |
| + t.Cleanup(func() { continuityDecided = prev }) |
| + once := false |
| + continuityDecided = func() { |
| + if !once { |
| + once = true |
| + g.migrateOn(app, bigMigration) |
| + } |
| + } |
| + if err := g.replicateAndStop(g.held(nil), app, "second wake"); err != nil { |
| + t.Fatal(err) |
| + } |
| + g.restoresWhole("second wake") |
| +} |
| + |
| +// slowSnapshots is a store that takes delay before each level-9 write. |
| +type slowSnapshots struct { |
| + litestream.ReplicaClient |
| + delay time.Duration |
| +} |
| + |
| +func (c *slowSnapshots) WriteLTXFile(ctx context.Context, level int, lo, hi ltx.TXID, r io.Reader) (*ltx.FileInfo, error) { |
| + if level == litestream.SnapshotLevel { |
| + select { |
| + case <-time.After(c.delay): |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + } |
| + } |
| + return c.ReplicaClient.WriteLTXFile(ctx, level, lo, hi, r) |
| +} |
| + |
| +// H2: a full image's time is scaled to the database's size, so a large |
| +// database under a slow store still wakes: a fixed bound shorter than the |
| +// store's time would fail every retry the same way. |
| +func TestFullImageBudgetScalesWithDatabaseSize(t *testing.T) { |
| + prevBase, prevRate := gapSnapshotTimeout, gapSnapshotMinRate |
| + gapSnapshotTimeout, gapSnapshotMinRate = 50*time.Millisecond, 1<<20 |
| + t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prevBase, prevRate }) |
| + g := newGapRig(t) |
| + g.wake("first wake") |
| + app := g.migrate(bigMigration) |
| + if fi, err := os.Stat(g.path); err != nil || fi.Size() < 4<<20 { |
| + t.Fatalf("the database is not large enough to need its size's time: %v %v", fi, err) |
| + } |
| + slow := &slowSnapshots{ReplicaClient: lsfile.NewReplicaClient(g.replica), delay: 500 * time.Millisecond} |
| + if err := g.replicateAndStop(g.held(slow), app, "slow store wake"); err != nil { |
| + t.Fatal(err) |
| + } |
| + g.restoresWhole("slow store wake") |
| +} |
| + |
| +// M1: the record is written through a fresh temporary file and never |
| +// through a link, and a record that is a link is not trusted. |
| +func TestCleanRecordIgnoresPlantedSymlinks(t *testing.T) { |
| + g := newGapRig(t) |
| + outside := filepath.Join(t.TempDir(), "outside") |
| + if err := os.WriteFile(outside, []byte("untouched"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + app := openWakeApp(t, g.path) |
| + r, err := g.held(nil).Replicate(ctx, g.path, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Planted while replication runs: the old in-tree temporary name. |
| + meta := metaPathOf(g.path) |
| + if err := os.Symlink(outside, filepath.Join(meta, "carlos-clean.json.tmp")); err != nil { |
| + t.Fatal(err) |
| + } |
| + wakeExec(t, app, `INSERT INTO t (body) VALUES ('linked')`) |
| + if err := r.SyncAndWait(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + app.Close() |
| + if err := r.Close(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if b, _ := os.ReadFile(outside); string(b) != "untouched" { |
| + t.Fatalf("the record was written through a planted link: %q", b) |
| + } |
| + _, rec, ok := recordPath(g.path) |
| + if !ok { |
| + t.Fatal("no record path") |
| + } |
| + copyOf := filepath.Join(t.TempDir(), "copy.json") |
| + raw, err := os.ReadFile(rec) |
| + if err != nil { |
| + t.Fatalf("no clean record after a clean close: %v", err) |
| + } |
| + if err := os.WriteFile(copyOf, raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Remove(rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(copyOf, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + p, err := ProtectStart(g.path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ReleaseStart(g.path) |
| + if p.Continuous() { |
| + t.Fatal("a record that is a link was trusted") |
| + } |
| +} |
| + |
| +// M2: the app can write everything beside its database. A record it |
| +// rewrites there from the files' current state is not trusted. |
| +func TestForgedCleanRecordIsNotTrusted(t *testing.T) { |
| + g := newGapRig(t) |
| + g.wake("first wake") |
| + app := openWakeApp(t, g.path) |
| + defer app.Close() // still running: its WAL stays, so the database can be pinned |
| + wakeExec(t, app, `INSERT INTO t (body) VALUES ('outside the replica')`) |
| + forgeRecordBesideDB(t, g.path) |
| + p, err := ProtectStart(g.path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ReleaseStart(g.path) |
| + if p.Continuous() { |
| + t.Fatal("a record the app wrote beside its database was trusted") |
| + } |
| +} |
| + |
| +// forgeRecordBesideDB writes, in the litestream meta directory, the record |
| +// the files make now, in the shape an in-tree record had. |
| +func forgeRecordBesideDB(t *testing.T, dbPath string) { |
| + t.Helper() |
| + fi, err := os.Stat(dbPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + walSize, walMod := int64(-1), int64(0) |
| + if wi, err := os.Stat(dbPath + "-wal"); err == nil { |
| + walSize, walMod = wi.Size(), wi.ModTime().UnixNano() |
| + } |
| + meta := metaPathOf(dbPath) |
| + ents, err := os.ReadDir(filepath.Join(meta, "ltx", "0")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var txid uint64 |
| + for _, e := range ents { |
| + if _, hi, err := ltx.ParseFilename(e.Name()); err == nil && uint64(hi) > txid { |
| + txid = uint64(hi) |
| + } |
| + } |
| + raw, _ := json.Marshal(map[string]any{"v": 1, "txid": txid, "db_size": fi.Size(), "db_mtime_ns": fi.ModTime().UnixNano(), "wal_size": walSize, "wal_mtime_ns": walMod}) |
| + if err := os.WriteFile(filepath.Join(meta, "carlos-clean.json"), raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// refusingUploads refuses every upload. |
| +type refusingUploads struct{ litestream.ReplicaClient } |
| + |
| +func (refusingUploads) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) { |
| + return nil, errors.New("upload refused") |
| +} |
| + |
| +// M3: a full image must be uploaded before Replicate returns: on a first |
| +// start, and after a gap that removed the WAL (litestream's own first file |
| +// is then the full image). |
| +func TestFullImageUploadIsConfirmedBeforeServing(t *testing.T) { |
| + prevBase, prevRate := gapSnapshotTimeout, gapSnapshotMinRate |
| + gapSnapshotTimeout, gapSnapshotMinRate = time.Second, 1<<40 |
| + t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prevBase, prevRate }) |
| + t.Run("first start", func(t *testing.T) { |
| + g := newGapRig(t) |
| + app := openWakeApp(t, g.path) |
| + bad := refusingUploads{lsfile.NewReplicaClient(g.replica)} |
| + if err := g.replicateAndStop(g.held(bad), app, "unuploaded"); err == nil { |
| + t.Fatal("Replicate returned before its first image was uploaded") |
| + } |
| + }) |
| + t.Run("gap with the WAL removed", func(t *testing.T) { |
| + g := newGapRig(t) |
| + g.wake("first wake") |
| + app := openWakeApp(t, g.path) |
| + wakeExec(t, app, `INSERT INTO t (body) VALUES ('outside the replica')`) |
| + app.Close() // the last connection: SQLite checkpoints and removes the WAL |
| + if _, err := os.Stat(g.path + "-wal"); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("the WAL is still there: %v", err) |
| + } |
| + app = openWakeApp(t, g.path) |
| + bad := refusingUploads{lsfile.NewReplicaClient(g.replica)} |
| + if err := g.replicateAndStop(g.held(bad), app, "unuploaded"); err == nil { |
| + t.Fatal("Replicate returned before the full image was uploaded") |
| + } |
| + }) |
| +} |
| + |
| +// flakyListing fails the first n replica listings. |
| +type flakyListing struct { |
| + litestream.ReplicaClient |
| + n atomic.Int32 |
| +} |
| + |
| +func (c *flakyListing) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) { |
| + if c.n.Add(-1) >= 0 { |
| + return nil, errors.New("listing failed once") |
| + } |
| + return c.ReplicaClient.LTXFiles(ctx, level, seek, useMetadata) |
| +} |
| + |
| +// A pinned, continuous start retries a replica read that fails, within |
| +// firstSyncTimeout, instead of failing the wake on the first error. |
| +func TestPinnedReplicateRetriesATransientReplicaRead(t *testing.T) { |
| + prev := firstSyncRetryBase |
| + firstSyncRetryBase = 10 * time.Millisecond |
| + t.Cleanup(func() { firstSyncRetryBase = prev }) |
| + g := newGapRig(t) |
| + g.wake("first wake") |
| + p, err := ProtectStart(g.path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !p.Continuous() { |
| + t.Fatal("not continuous after a clean close") |
| + } |
| + app := openWakeApp(t, g.path) |
| + flaky := &flakyListing{ReplicaClient: lsfile.NewReplicaClient(g.replica)} |
| + flaky.n.Store(2) |
| + if err := g.replicateAndStop(g.held(flaky), app, "retried"); err != nil { |
| + t.Fatalf("a pinned start failed on a transient listing error: %v", err) |
| + } |
| +} |
diff --git a/internal/lease/continuity_test.go b/internal/lease/continuity_test.go| index 88eb2f1bd..21581da76 100644 |
| --- a/internal/lease/continuity_test.go |
| +++ b/internal/lease/continuity_test.go |
| @@ -40,9 +40,22 @@ func newGapRig(t *testing.T) *gapRig { |
| t.Helper() |
| g := &gapRig{t: t, backend: &lockStore{}, path: filepath.Join(t.TempDir(), "app.db"), replica: t.TempDir()} |
| seedDB(t, g.path) |
| + useContinuityDir(t) |
| return g |
| } |
| +// useContinuityDir gives the test an agent continuity directory of its |
| +// own, as the agent sets one at startup. |
| +func useContinuityDir(t *testing.T) string { |
| + t.Helper() |
| + dir := t.TempDir() |
| + if err := SetContinuityDir(dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { setContinuityDirForTest("") }) |
| + return dir |
| +} |
| + |
| func (g *gapRig) held(client litestream.ReplicaClient) *Held { |
| g.t.Helper() |
| h := localHeld(g.t, g.backend, 10*time.Second) |
| @@ -79,8 +92,15 @@ func (g *gapRig) wake(body string) { |
| // WAL. It returns the process, still running. |
| func (g *gapRig) migrate(rows int) *sql.DB { |
| g.t.Helper() |
| - g.rows = rows |
| app := openWakeApp(g.t, g.path) |
| + g.migrateOn(app, rows) |
| + return app |
| +} |
| + |
| +// migrateOn is migrate in a process already running. |
| +func (g *gapRig) migrateOn(app *sql.DB, rows int) { |
| + g.t.Helper() |
| + g.rows = rows |
| wakeExec(g.t, app, `CREATE TABLE m (id INTEGER PRIMARY KEY, body TEXT)`) |
| wakeExec(g.t, app, `CREATE INDEX m_body ON m(body)`) |
| tx, err := app.Begin() |
| @@ -96,7 +116,6 @@ func (g *gapRig) migrate(rows int) *sql.DB { |
| g.t.Fatal(err) |
| } |
| wakeExec(g.t, app, `INSERT INTO t (body) VALUES ('after the migration')`) |
| - return app |
| } |
| // replicateAndStop finishes a wake whose process is app: Replicate on h, |
| @@ -236,9 +255,9 @@ func TestReplicateWithoutLocalMetadataRestoresWhole(t *testing.T) { |
| // within its bound instead of leaving the process running unprotected, |
| // and the next wake repairs. |
| func TestGapRepairTimeoutFailsReplicateAndIsRetried(t *testing.T) { |
| - prev := gapSnapshotTimeout |
| - gapSnapshotTimeout = 300 * time.Millisecond |
| - t.Cleanup(func() { gapSnapshotTimeout = prev }) |
| + prev, prevRate := gapSnapshotTimeout, gapSnapshotMinRate |
| + gapSnapshotTimeout, gapSnapshotMinRate = 300*time.Millisecond, 1<<40 |
| + t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prev, prevRate }) |
| g := newGapRig(t) |
| g.wake("first wake") |
| app := g.migrate(bigMigration) |
| @@ -252,6 +271,7 @@ func TestGapRepairTimeoutFailsReplicateAndIsRetried(t *testing.T) { |
| if d := time.Since(start); d > 20*time.Second { |
| t.Fatalf("Replicate took %s on a 300 ms repair budget", d) |
| } |
| + gapSnapshotTimeout, gapSnapshotMinRate = prev, prevRate // the retry gets the real budget |
| app = openWakeApp(t, g.path) |
| if err := g.replicateAndStop(g.held(nil), app, "retried wake"); err != nil { |
| t.Fatal(err) |
diff --git a/internal/lease/export_test.go b/internal/lease/export_test.go| index e9d2e62f6..69fdbe873 100644 |
| --- a/internal/lease/export_test.go |
| +++ b/internal/lease/export_test.go |
| @@ -171,3 +171,23 @@ func SetBoxNowForTest(now func() time.Time) (restore func()) { |
| func NewReplicaClientForTest(bucket, prefix, region string) (litestream.ReplicaClient, error) { |
| return newReplicaClient(bucket, prefix, region) |
| } |
| + |
| +// setContinuityDirForTest sets the continuity directory without creating |
| +// it; "" is none. |
| +func setContinuityDirForTest(dir string) { |
| + continuityDir.Lock() |
| + continuityDir.dir = dir |
| + continuityDir.Unlock() |
| +} |
| + |
| +// SetContinuityDirForTest is setContinuityDirForTest for the external |
| +// tests. |
| +var SetContinuityDirForTest = setContinuityDirForTest |
| + |
| +// SetImageBudgetForTest bounds a full image's upload at d, whatever the |
| +// database's size, for the test. |
| +func SetImageBudgetForTest(t interface{ Cleanup(func()) }, d time.Duration) { |
| + prev, prevRate := gapSnapshotTimeout, gapSnapshotMinRate |
| + gapSnapshotTimeout, gapSnapshotMinRate = d, 1<<40 |
| + t.Cleanup(func() { gapSnapshotTimeout, gapSnapshotMinRate = prev, prevRate }) |
| +} |
diff --git a/internal/lease/fence_test.go b/internal/lease/fence_test.go| index 3c75a25b8..3e37812fa 100644 |
| --- a/internal/lease/fence_test.go |
| +++ b/internal/lease/fence_test.go |
| @@ -86,6 +86,10 @@ func (c *failingReplica) DeleteAll(ctx context.Context) error { |
| // finalization's calls. |
| type hangingReplica struct { |
| failingReplica |
| + // open passes writes straight through while set: Replicate's first |
| + // image must upload before it returns (replicate before start, |
| + // #1290), so a rig opens the replica for the start and closes it after. |
| + open atomic.Bool |
| entered chan struct{} |
| enterOnce sync.Once |
| cancelled atomic.Int32 // hung writes whose context ended |
| @@ -98,6 +102,15 @@ func newHangingReplica(t *testing.T) *hangingReplica { |
| return &hangingReplica{failingReplica: *newFailingReplica(t), entered: make(chan struct{})} |
| } |
| +// started is fencedReplicator over c, with c open for the start only. |
| +func (c *hangingReplica) started(t *testing.T, h *lease.Held) *fenceRig { |
| + t.Helper() |
| + c.open.Store(true) |
| + g := fencedReplicator(t, h, c) |
| + c.open.Store(false) |
| + return g |
| +} |
| + |
| func (c *hangingReplica) rec(e string) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| @@ -127,6 +140,9 @@ func (c *hangingReplica) OpenLTXFile(ctx context.Context, level int, minTXID, ma |
| } |
| func (c *hangingReplica) WriteLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, r io.Reader) (*ltx.FileInfo, error) { |
| + if c.open.Load() { |
| + return c.failingReplica.WriteLTXFile(ctx, level, minTXID, maxTXID, r) |
| + } |
| c.count(ctx) |
| c.rec("replica write") |
| if !lease.FinalizingForTest(ctx) { |
| @@ -333,7 +349,7 @@ func TestWriteFenceFiresAfterAnEarlierLoss(t *testing.T) { |
| fx := leasetest.NewLockFixture(t) |
| c := newHangingReplica(t) |
| h := haHeldTTL(t, fx, "instances/f", 3*time.Second) |
| - g := fencedReplicator(t, h, c) |
| + g := c.started(t, h) |
| addRows(t, g.path, 3) |
| g.capture(t) |
| waitClosed(t, c.entered, 10*time.Second, "the replica upload") |
| @@ -542,7 +558,7 @@ func TestWriteFenceReleaseKeepsItsDeadlineBehindAHungUpload(t *testing.T) { |
| t.Cleanup(lease.SetOwedClockForTest(func() time.Time { return now })) |
| fx := leasetest.NewLockFixture(t) |
| c := newHangingReplica(t) |
| - g := fencedReplicator(t, haHeld(t, fx, "instances/f"), c) |
| + g := c.started(t, haHeld(t, fx, "instances/f")) |
| addRows(t, g.path, 5) |
| g.capture(t) |
| waitClosed(t, c.entered, 10*time.Second, "the replica upload") |
diff --git a/internal/lease/gentake_test.go b/internal/lease/gentake_test.go| index 4ed765ed6..b35c00540 100644 |
| --- a/internal/lease/gentake_test.go |
| +++ b/internal/lease/gentake_test.go |
| @@ -723,7 +723,13 @@ func TestGenerationWriterRunsRetention(t *testing.T) { |
| if _, ok := fx.m.Current(fx.bucket, k); ok { |
| t.Errorf("%s: retention's delete left it current", k) |
| } |
| - if !strings.HasPrefix(k, replicagen.Prefix(fx.loc, tk.Generation)+"0000/") { |
| + // Snapshot retention may run in the same window: Replicate's |
| + // first sync (replicate before start, #1290) readies the store |
| + // before the snapshot level's first pass, which now runs here |
| + // rather than a second later. Its deletes are inside the |
| + // generation too. |
| + g := replicagen.Prefix(fx.loc, tk.Generation) |
| + if !strings.HasPrefix(k, g+"0000/") && !strings.HasPrefix(k, g+"0009/") { |
| t.Errorf("%s: L0 retention deleted outside L0", k) |
| } |
| } |
diff --git a/internal/lease/release_test.go b/internal/lease/release_test.go| index 51d3daf30..95a508f81 100644 |
| --- a/internal/lease/release_test.go |
| +++ b/internal/lease/release_test.go |
| @@ -592,16 +592,15 @@ func TestCloseProvenEmptyNeedsBothHalves(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - r, err := h.Replicate(ctx, tempDB(t), 0) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - t.Cleanup(func() { r.Abandon(ctx) }) |
| - if err := r.CloseProven(ctx); !errors.Is(err, lease.ErrCheckpointUnproven) { |
| - t.Fatalf("CloseProven over an existing database that cannot sync = %v, want ErrCheckpointUnproven", err) |
| + // Replicate before start (#1290): a first image the bucket cannot |
| + // receive fails the start itself, so this never reaches a close. |
| + lease.SetImageBudgetForTest(t, time.Second) |
| + if r, err := h.Replicate(ctx, tempDB(t), 0); err == nil { |
| + r.Abandon(ctx) |
| + t.Fatal("Replicate started over an existing database the bucket cannot receive") |
| } |
| if fx.LockBody(prefix) == nil { |
| - t.Fatal("the lease was released over an unproven checkpoint") |
| + t.Fatal("the lease was released over an unproven start") |
| } |
| }) |
| t.Run("database missing, bucket holds a backup", func(t *testing.T) { |