carlos / platform Public

ops, lease: only proven damage fails; empty fleets clear scratch (#898)

Residual P2s from the scoped re-review (items 4 and 9).

- lease.CheckDBContext marks only proven damage ErrCheckFailed:
  integrity_check not ok, no tables, or SQLite's own SQLITE_CORRUPT or
  SQLITE_NOTADB verdict. Open and I/O errors keep their own error,
  unmarked; verifyRestored no longer marks every check error.
- The drill's default is inverted: failed/restore_error only for
  ErrCheckFailed, or an LTX checksum/format verdict (ltx and litestream
  sentinels) with no storage or transport error behind it. Everything
  else (io.ErrUnexpectedEOF, net/API errors, ENOSPC, a check that could
  not open the copy, unknown errors) is unverified/storage_unavailable.
- clearCrashedScratch runs right after the root and config checks,
  before the self record and both empty-fleet returns.
- Tests: body cut short, SQLite open failure, unknown error and a reset
  connection behind an LTX checksum error are storage_unavailable; a
  real corrupted database through the real planner, restore and check
  is failed; lease marks integrity, not-a-database and no-tables but not
  an open failure; an empty-fleet run (with and without a prior record)
  removes a stale leftover.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 26e0ed4429aace7a63f591f4a28f4cdf748597e7 parent 615ee1b
7 files changed, +312 −42
  • internal/lease/check.go +42 −14
  • internal/lease/check_test.go +79 −0
  • internal/ops/hibernate_verify.go +34 −15
  • internal/ops/hibernate_verify_restore_test.go +111 −9
  • internal/ops/hibernate_verify_run_test.go +37 −0
  • internal/ops/hibernate_verify_test.go +4 −3
  • internal/ops/ops.go +5 −1

Intent

Human

<task-notification> <task-id>bjzc9cane</task-id> <tool-use-id>toolu_01ACnbV7JGraFcsoRaxMeUkR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/bjzc9cane.output</output-file> <status>completed</status> <summary>Background command "Scoped re-review of the 2a fix wave" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bkqou7stu</task-id> <tool-use-id>toolu_01Mod8TtxdEdTJrtpMT9zerf</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ab362fc0-f177-4a7f-a92e-4a29ea210aad/tasks/bkqou7stu.output</output-file> <status>completed</status> <summary>Background command "Census round 3 for slice 2a" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/lease/check.go b/internal/lease/check.go
index 9b24b0d0f..79a9340a4 100644
--- a/internal/lease/check.go
+++ b/internal/lease/check.go
@@ -13,7 +13,8 @@ import (
"github.com/benbjohnson/litestream"
"github.com/superfly/ltx"
- _ "modernc.org/sqlite"
+ "modernc.org/sqlite"
+ sqlite3 "modernc.org/sqlite/lib"
)
// restoreForVerify is the verify restore behind a package var so the
@@ -168,21 +169,45 @@ func CheckDBContext(ctx context.Context, path string) error {
}
var res string
if err := db.QueryRowContext(ctx, "PRAGMA integrity_check").Scan(&res); err != nil {
- return fmt.Errorf("integrity_check: %w", err)
+ return damagedIf(sqliteSaysDamaged(err), fmt.Errorf("integrity_check: %w", err))
}
if res != "ok" {
- return fmt.Errorf("integrity_check: %s", res)
+ return checkError{fmt.Errorf("integrity_check: %s", res)}
}
var tables int
if err := db.QueryRowContext(ctx, "SELECT count(*) FROM sqlite_master WHERE type='table'").Scan(&tables); err != nil {
- return fmt.Errorf("schema count: %w", err)
+ return damagedIf(sqliteSaysDamaged(err), fmt.Errorf("schema count: %w", err))
}
if tables == 0 {
- return errors.New("restored database has no tables")
+ return checkError{errors.New("restored database has no tables")}
}
return nil
}
+// sqliteSaysDamaged reports whether err is SQLite's own verdict that the
+// file is damaged: SQLITE_CORRUPT, or SQLITE_NOTADB (the bytes are not a
+// database). An open, I/O, full-disk or permission error is not: it says
+// nothing about the file's contents.
+func sqliteSaysDamaged(err error) bool {
+ var se *sqlite.Error
+ if !errors.As(err, &se) {
+ return false
+ }
+ switch se.Code() & 0xff {
+ case sqlite3.SQLITE_CORRUPT, sqlite3.SQLITE_NOTADB:
+ return true
+ }
+ return false
+}
+
+// damagedIf marks err as damage (ErrCheckFailed) when damaged is true.
+func damagedIf(damaged bool, err error) error {
+ if damaged {
+ return checkError{err}
+ }
+ return err
+}
+
// VerifyReplica restores the newest copy of s3://bucket/prefix into a
// throwaway file under dir and proves it opens clean, then deletes it: it is
// VerifyReplicaAt with no target.
@@ -215,9 +240,10 @@ func VerifyReplica(ctx context.Context, bucket, prefix, region, dir string) (uin
// failure, so a caller out of time can abandon the database instead of
// recording it as damaged.
//
-// A copy that restored but failed CheckDB is an error wrapping
-// ErrCheckFailed, with the check's own message; any other error is from
-// the restore itself.
+// A copy that restored and that CheckDB proved damaged is an error
+// wrapping ErrCheckFailed, with the check's own message. A check that
+// could not open or read the copy, and a failed restore, keep their own
+// error unmarked.
func VerifyReplicaAt(ctx context.Context, bucket, prefix, region, dir string, txid uint64) (uint32, error) {
return verifyRestored(ctx, prefix, dir, func(out string) (bool, error) {
return restoreForVerify(ctx, out, bucket, prefix, region, ltx.TXID(txid))
@@ -233,13 +259,15 @@ func VerifyClientAt(ctx context.Context, client litestream.ReplicaClient, prefix
})
}
-// ErrCheckFailed marks a VerifyReplicaAt error from a copy that restored
-// completely and then failed CheckDB: evidence the replica is damaged,
-// where a restore error may be the storage's.
+// ErrCheckFailed marks a CheckDB error (and so a VerifyReplicaAt error)
+// that proves the copy damaged: integrity_check answered something other
+// than "ok", SQLite itself reported the file corrupt or not a database, or
+// the database has no tables. An error opening or reading the copy is
+// never marked: it may be this box's disk, not the replica.
var ErrCheckFailed = errors.New("lease: the restored copy failed its check")
-// checkError is a CheckDB failure carrying ErrCheckFailed and keeping the
-// check's own message.
+// checkError is a CheckDB damage verdict carrying ErrCheckFailed and
+// keeping the check's own message.
type checkError struct{ err error }
func (e checkError) Error() string { return e.err.Error() }
@@ -282,7 +310,7 @@ func verifyRestored(ctx context.Context, prefix, dir string, restore func(out st
if cerr := ctx.Err(); cerr != nil {
return 0, fmt.Errorf("check stopped: %w", cerr)
}
- return 0, checkError{err}
+ return 0, err
}
// The counter is read BEFORE the deferred sweep removes the copy: it is
// what lets the caller ask the second question, whether this replica is
diff --git a/internal/lease/check_test.go b/internal/lease/check_test.go
index 9c5499165..6d9ae2791 100644
--- a/internal/lease/check_test.go
+++ b/internal/lease/check_test.go
@@ -587,6 +587,85 @@ func TestVerifyReplicaAtMarksCheckFailures(t *testing.T) {
}
}
+// corruptDB writes a small DELETE-journal database with page 3 scribbled
+// over: it opens, has its schema, and only integrity_check finds the damage
+// (a result that is not "ok", not a query error).
+func corruptDB(t *testing.T, path string) {
+ t.Helper()
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, q := range []string{"PRAGMA journal_mode=DELETE", "CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)"} {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < 100; i++ {
+ if _, err := db.Exec("INSERT INTO t (body) VALUES (?)", "row padding to force several pages"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ db.Close()
+ f, err := os.OpenFile(path, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ junk := make([]byte, 512)
+ for i := range junk {
+ junk[i] = 0xA5
+ }
+ if _, err := f.WriteAt(junk, 2*4096+100); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// Only a check that proves damage is ErrCheckFailed: integrity_check
+// answering something other than "ok", SQLite's own corrupt or not-a-
+// database verdict, or a database with no tables. A check that could not
+// open or read the copy (an I/O or open failure) keeps its own error and is
+// not marked: it says nothing about the replica (re-review item 4).
+func TestVerifyReplicaAtMarksOnlyDamage(t *testing.T) {
+ prev := restoreForVerify
+ t.Cleanup(func() { restoreForVerify = prev })
+ for name, c := range map[string]struct {
+ restore func(out string) error
+ damage bool
+ }{
+ "integrity_check not ok": {func(out string) error { corruptDB(t, out); return nil }, true},
+ "not a database": {func(out string) error {
+ return os.WriteFile(out, []byte("not a database at all, just text padding padding padding"), 0o600)
+ }, true},
+ "no tables": {func(out string) error {
+ db, err := sql.Open("sqlite", out)
+ if err != nil {
+ return err
+ }
+ defer db.Close()
+ _, err = db.Exec("PRAGMA user_version=1")
+ return err
+ }, true},
+ // The restored path is a directory: SQLite cannot open it.
+ "cannot open": {func(out string) error { return os.Mkdir(out, 0o700) }, false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ restoreForVerify = func(_ context.Context, out, _, _, _ string, _ ltx.TXID) (bool, error) {
+ return true, c.restore(out)
+ }
+ dir := t.TempDir()
+ _, err := VerifyReplicaAt(context.Background(), "bucket", "hib/x.example.com", "", dir, 7)
+ if err == nil || errors.Is(err, ErrCheckFailed) != c.damage {
+ t.Fatalf("VerifyReplicaAt = %v; marked damage %v, want %v", err, errors.Is(err, ErrCheckFailed), c.damage)
+ }
+ if strings.Contains(err.Error(), ErrCheckFailed.Error()) {
+ t.Fatalf("the mark changed the check's message: %v", err)
+ }
+ assertEmptyDir(t, dir)
+ })
+ }
+}
+
// VerifyClientAt is VerifyReplicaAt over a replica client the caller
// built: the same pinned restore, check, counter and sweep.
func TestVerifyClientAt(t *testing.T) {
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go
index d66f08951..e3b053137 100644
--- a/internal/ops/hibernate_verify.go
+++ b/internal/ops/hibernate_verify.go
@@ -33,6 +33,7 @@ import (
"github.com/aws/smithy-go"
"github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
"github.com/carlosframework/platform/internal/activator"
"github.com/carlosframework/platform/internal/boxself"
@@ -109,14 +110,16 @@ const (
// ReasonPlanMoved: the planned position, or an object it needed, was
// compacted away before it could be read, twice running.
ReasonPlanMoved = "plan_moved"
- // ReasonRestoreError: the replica restored into a copy that failed its
- // integrity check, or its bytes would not decode into a database (a
- // failed verdict). Only damage is failed.
+ // ReasonRestoreError: the replica restored into a copy its check proved
+ // damaged, or its LTX failed its checksum or was not LTX (a failed
+ // verdict). Only proven damage is failed.
ReasonRestoreError = "restore_error"
// ReasonStorageUnavailable: listing or planning failed, or the restore
- // failed on the storage (an API, network or credential error) or on
- // this box's own disk (out of space, permissions), which says nothing
- // about the copy.
+ // failed any way that is not proven damage: on the storage (an API,
+ // network or credential error, a body cut short), on this box's own
+ // disk (out of space, permissions, a copy that would not open), or with
+ // an error the drill does not recognise. It says nothing certain about
+ // the copy.
ReasonStorageUnavailable = "storage_unavailable"
// ReasonStale: on the box holding the lease, the replica restores but
// has stopped tracking the live database (a failed verdict).
@@ -456,12 +459,15 @@ func bracketReason(code string) string {
// (os.ErrNotExist, as the S3 client reports a missing key); that is not a
// failure, so it plans once more, and a second miss is restorePlanMoved.
//
-// Only damage is restoreFailed: a copy that restored and failed its check
-// (lease.ErrCheckFailed), or a restore error that is neither the storage's
-// nor this box's disk's, which leaves the replica's bytes not decoding. A
-// planning error, and a restore error from the storage or the local disk
-// (storageError), is restoreUnavailable. An error once ctx has ended is
-// the run's, and the caller abandons the host.
+// Only proven damage is restoreFailed: a copy the check proved damaged
+// (lease.ErrCheckFailed: integrity_check not ok, SQLite's corrupt or
+// not-a-database verdict, no tables), or an LTX that failed its checksum or
+// was not an LTX file (ltxDamage) with no storage or transport error behind
+// it. Every other error is restoreUnavailable: a planning error, the
+// storage's or this box's disk's (storageError), a body cut short
+// (io.ErrUnexpectedEOF), a check that could not open the copy, and any
+// error the drill does not recognise. An error once ctx has ended is the
+// run's, and the caller abandons the host.
func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
var last restoreResult
for attempt := 0; attempt < 2; attempt++ {
@@ -488,14 +494,27 @@ func (d Drill) restore(ctx context.Context, prefix, dir string) restoreResult {
continue
case errors.Is(err, lease.ErrNoReplica):
return restoreResult{kind: restoreNothing, err: err}
- case storageError(err):
- return restoreResult{kind: restoreUnavailable, plan: plan, err: err}
+ case ltxDamage(err) && !storageError(err):
+ return restoreResult{kind: restoreFailed, plan: plan, err: err}
}
- return restoreResult{kind: restoreFailed, plan: plan, err: err}
+ return restoreResult{kind: restoreUnavailable, plan: plan, err: err}
}
return last
}
+// ltxDamage reports whether err carries one of the LTX format's own damage
+// verdicts: a checksum that does not match, a checksum missing or
+// malformed, a file that is not LTX, or litestream's corrupted-file error.
+func ltxDamage(err error) bool {
+ for _, target := range []error{ltx.ErrChecksumMismatch, ltx.ErrNoChecksum, ltx.ErrInvalidChecksumFormat,
+ ltx.ErrInvalidFile, litestream.ErrChecksumMismatch, litestream.ErrLTXCorrupted} {
+ if errors.Is(err, target) {
+ return true
+ }
+ }
+ return false
+}
+
// storageError reports whether err came from reaching the copy's storage
// (an AWS API or operation error, a network or URL error) or from this
// box's own system calls (a path, link or syscall error, an errno: out of
diff --git a/internal/ops/hibernate_verify_restore_test.go b/internal/ops/hibernate_verify_restore_test.go
index b6b9b304f..5f3a9d083 100644
--- a/internal/ops/hibernate_verify_restore_test.go
+++ b/internal/ops/hibernate_verify_restore_test.go
@@ -1,18 +1,23 @@
package ops
import (
+ "bytes"
"context"
+ "database/sql"
"errors"
"fmt"
"io"
"io/fs"
"net"
"os"
+ "path/filepath"
+ "strings"
"sync"
"syscall"
"testing"
"github.com/aws/smithy-go"
+ "github.com/benbjohnson/litestream"
lsfile "github.com/benbjohnson/litestream/file"
"github.com/superfly/ltx"
@@ -21,28 +26,47 @@ import (
"github.com/carlosframework/platform/internal/lease"
)
-// Only damage is failed (Fable P2-5): a copy that restored and failed its
-// check, or replica bytes that would not decode. Anything the storage or
-// this box's own disk did is unverified, storage_unavailable, because it
-// says nothing about the copy, and a failed verdict pages as an incident.
+// Only proven damage is failed (Fable P2-5, re-review item 4): the
+// restored copy's check proved it damaged (lease.ErrCheckFailed), or the
+// replica's LTX failed its checksum or was not an LTX file, with no
+// storage or transport error behind it. Everything else is unverified,
+// storage_unavailable, because it says nothing certain about the copy and
+// a failed verdict pages as an incident: a body cut short, a network or
+// API error, a full disk, a check that could not open the copy, and any
+// error the drill does not recognise.
func TestVerifyHibernatingOnlyDamageFails(t *testing.T) {
s3err := &smithy.OperationError{ServiceID: "S3", OperationName: "GetObject",
Err: &smithy.GenericAPIError{Code: "SlowDown", Message: "reduce your request rate"}}
+ reset := &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}
+ // A real SQLite open failure, from the check lease runs on the copy.
+ openErr := lease.CheckDB(t.TempDir())
+ if openErr == nil || errors.Is(openErr, lease.ErrCheckFailed) {
+ t.Fatalf("fixture: CheckDB on a directory = %v, want an unmarked open error", openErr)
+ }
for name, c := range map[string]struct {
err error
result string
reason string
}{
- "check failed": {fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed),
+ "check proved damage": {fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed),
+ dbverify.ResultFailed, ReasonRestoreError},
+ "ltx checksum mismatch": {fmt.Errorf("restore: decode database: decode page 3: %w", ltx.ErrChecksumMismatch),
dbverify.ResultFailed, ReasonRestoreError},
- "bytes would not decode": {errors.New("restore: decode database: unexpected pgno while decoding page: read 7, expected 6"),
+ "not an ltx file": {fmt.Errorf("restore: decode database: decode header: unmarshal header: %w", ltx.ErrInvalidFile),
dbverify.ResultFailed, ReasonRestoreError},
- "truncated object": {fmt.Errorf("restore: decode database: decode page 3: %w", io.ErrUnexpectedEOF),
+ "ltx corrupted": {fmt.Errorf("restore: %w", litestream.ErrLTXCorrupted),
dbverify.ResultFailed, ReasonRestoreError},
+ "checksum mismatch over a reset connection": {
+ fmt.Errorf("restore: decode database: %w (the replica's last read error: %w)", ltx.ErrChecksumMismatch, reset),
+ dbverify.ResultUnverified, ReasonStorageUnavailable},
+ "body cut short": {fmt.Errorf("restore: decode database: decode page 3: %w", io.ErrUnexpectedEOF),
+ dbverify.ResultUnverified, ReasonStorageUnavailable},
+ "sqlite open failure": {openErr, dbverify.ResultUnverified, ReasonStorageUnavailable},
+ "unknown error": {errors.New("restore: decode database: unexpected pgno while decoding page: read 7, expected 6"),
+ dbverify.ResultUnverified, ReasonStorageUnavailable},
"storage refused": {fmt.Errorf("restore: cannot calc restore plan: %w", s3err),
dbverify.ResultUnverified, ReasonStorageUnavailable},
- "connection reset": {fmt.Errorf("restore: decode database: decode header: EOF (the replica's last read error: %w)",
- &net.OpError{Op: "read", Net: "tcp", Err: syscall.ECONNRESET}),
+ "connection reset": {fmt.Errorf("restore: decode database: decode header: EOF (the replica's last read error: %w)", reset),
dbverify.ResultUnverified, ReasonStorageUnavailable},
"disk full": {fmt.Errorf("restore: decode database: write page 9: %w",
&fs.PathError{Op: "write", Path: "/var/cache/carlos-verify/x/verify.db.tmp", Err: syscall.ENOSPC}),
@@ -142,3 +166,81 @@ func TestVerifyHibernatingReplansAMissingObject(t *testing.T) {
})
}
}
+
+// corruptReplica writes a one-file replica in dir: an LTX snapshot (TXID
+// 1) of a small database whose page 3 is scribbled over. The LTX itself is
+// whole and checksummed, so the restore succeeds, and only the check of
+// the restored copy finds the damage: integrity_check's answer is not ok.
+func corruptReplica(t *testing.T, dir string) {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "corrupt.db")
+ db, err := sql.Open("sqlite", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, q := range []string{"PRAGMA journal_mode=DELETE", "CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)"} {
+ if _, err := db.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for i := 0; i < 100; i++ {
+ if _, err := db.Exec("INSERT INTO t (body) VALUES (?)", "row padding to force several pages"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ db.Close()
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const pageSize = 4096
+ for i := 2*pageSize + 100; i < 2*pageSize+612; i++ {
+ raw[i] = 0xA5
+ }
+ var buf bytes.Buffer
+ enc, err := ltx.NewEncoder(&buf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ commit := uint32(len(raw) / pageSize)
+ if err := enc.EncodeHeader(ltx.Header{Version: ltx.Version, Flags: ltx.HeaderFlagNoChecksum, PageSize: pageSize,
+ Commit: commit, MinTXID: 1, MaxTXID: 1, Timestamp: 1000}); err != nil {
+ t.Fatal(err)
+ }
+ for pgno := uint32(1); pgno <= commit; pgno++ {
+ if err := enc.EncodePage(ltx.PageHeader{Pgno: pgno}, raw[(pgno-1)*pageSize:pgno*pageSize]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := enc.Close(); err != nil {
+ t.Fatal(err)
+ }
+ out := lsfile.NewReplicaClient(dir).LTXFilePath(0, 1, 1)
+ if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(out, buf.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// A real damaged database, through the real planner, downloader, restore
+// and check: failed, restore_error, the check's own words in the detail.
+func TestVerifyHibernatingRealCorruptionFails(t *testing.T) {
+ const host = "a.example.com"
+ fx := newDrillFx(t, host)
+ replica := t.TempDir()
+ corruptReplica(t, replica)
+ client := lsfile.NewReplicaClient(replica)
+ swap(t, &openReplica, func(context.Context, string, string, string) (dbdoor.ReplicaReader, error) {
+ return client, nil
+ })
+ swap(t, &verifyAt, func(ctx context.Context, _, prefix, _, dir string, txid uint64) (uint32, error) {
+ return lease.VerifyClientAt(ctx, client, prefix, dir, txid)
+ })
+ v := fx.run(context.Background(), fx.drill(), fx.routes(host), nil)[host]
+ if v.Result != dbverify.ResultFailed || v.Reason != ReasonRestoreError || !strings.Contains(v.Detail, "integrity_check") {
+ t.Fatalf("verdict %+v, want failed/restore_error from integrity_check", v)
+ }
+ fx.scratchEmpty()
+}
diff --git a/internal/ops/hibernate_verify_run_test.go b/internal/ops/hibernate_verify_run_test.go
index a7e4e59de..2361eea71 100644
--- a/internal/ops/hibernate_verify_run_test.go
+++ b/internal/ops/hibernate_verify_run_test.go
@@ -325,3 +325,40 @@ func TestRunHibernateVerifyWaitsBrieflyForSelf(t *testing.T) {
}
})
}
+
+// A box whose last host has left still reclaims a killed run's restored
+// databases: the cleanup runs before either empty-fleet return (re-review
+// item 9), with no prior record and with one to clear.
+func TestRunHibernateVerifyEmptyFleetClearsCrashedScratch(t *testing.T) {
+ for name, withPrior := range map[string]bool{"no prior record": false, "prior record to clear": true} {
+ t.Run(name, func(t *testing.T) {
+ fx := newRunFx(t)
+ fx.writeSelf(fxSelf, false)
+ if withPrior {
+ prior := &dbverify.Record{V: 2, Box: fxSelf, Hosts: map[string]dbverify.Verdict{
+ "gone.example.com": {Result: dbverify.ResultPassed},
+ }}
+ if err := dbverify.Publish(context.Background(), fx.store, prior); err != nil {
+ t.Fatal(err)
+ }
+ }
+ stale := filepath.Join(fx.tmp, "carlos-hibernate-verify424242")
+ if err := os.MkdirAll(filepath.Join(stale, "drill-1"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(stale, "drill-1", "verify-gone.example.com.db"), []byte("tenant data"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ old := fx.clock.Now().Add(-25 * time.Hour)
+ if err := os.Chtimes(stale, old, old); err != nil {
+ t.Fatal(err)
+ }
+ if code := fx.runner().run(context.Background()); code != 0 {
+ t.Fatalf("exited %d: %s", code, fx.logs)
+ }
+ if _, err := os.Lstat(stale); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("an empty-fleet run left the crashed run's scratch: %v", err)
+ }
+ })
+ }
+}
diff --git a/internal/ops/hibernate_verify_test.go b/internal/ops/hibernate_verify_test.go
index 81b9afbd7..a93f85e60 100644
--- a/internal/ops/hibernate_verify_test.go
+++ b/internal/ops/hibernate_verify_test.go
@@ -25,6 +25,7 @@ import (
"github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
"github.com/carlosframework/platform/internal/dbverify"
"github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -392,7 +393,7 @@ func TestVerifyHibernatingVerdicts(t *testing.T) {
fx.replicaFor[fx.prefix("new.example.com")] = fx.empty
fx.stubVerify(func(_ context.Context, prefix, _ string, _ uint64) (uint32, error) {
if strings.Contains(prefix, "damaged") {
- return 0, errors.New("integrity_check: page 4 corrupt")
+ return 0, fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed)
}
return 1, nil
})
@@ -623,7 +624,7 @@ func TestVerifyHibernatingBracket(t *testing.T) {
"restored": {},
"empty plan": {empty: true},
"restore error": {err: errors.New("restore: decode header: EOF")},
- "integrity failure": {err: errors.New("integrity_check: page 4 corrupt")},
+ "integrity failure": {err: fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed)},
}
for cname, c := range changes {
for _, when := range []string{"planning", "download"} {
@@ -1515,7 +1516,7 @@ func TestRunHibernateVerifyExitCarriesFailuresOnly(t *testing.T) {
t.Fatalf("an unverified host failed the run: %d", code)
}
fx.stubVerify(func(context.Context, string, string, uint64) (uint32, error) {
- return 0, errors.New("integrity_check: page 4 corrupt")
+ return 0, fmt.Errorf("%w: integrity_check: page 4 corrupt", lease.ErrCheckFailed)
})
if code := fx.runner().run(context.Background()); code == 0 {
t.Fatal("a damaged replica exited 0")
diff --git a/internal/ops/ops.go b/internal/ops/ops.go
index a3265183a..324c57d59 100644
--- a/internal/ops/ops.go
+++ b/internal/ops/ops.go
@@ -454,6 +454,11 @@ func (r hibernateRun) run(ctx context.Context) int {
fmt.Println("hibernate-verify: CARLOS_HIBERNATE_BUCKET unset — no hibernating replicas on this box")
return 0
}
+ // A killed run's restored databases are reclaimed whatever this run
+ // goes on to do: before the self record, the store and both
+ // empty-fleet returns, so a box whose last host has left still clears
+ // them (re-review item 9).
+ r.clearCrashedScratch()
self, err := readBoxSelf(r.DataDir, r.Now(), selfMaxAge)
for waited := time.Duration(0); err != nil && waited < r.SelfWait; waited += selfPoll {
if waited == 0 {
@@ -525,7 +530,6 @@ func (r hibernateRun) run(ctx context.Context) int {
return 0
}
- r.clearCrashedScratch()
tmp, err := os.MkdirTemp(r.TmpDir, scratchPrefix)
if err != nil {
r.Logf("hibernate-verify: NOT RUN: scratch: %v", err)