mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
Merge main with v3-only capture and detach cancellation witnesses
This commit is contained in:
commit
0dc4597555
111 files changed
+5362
-11907
No files matched your search
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// --strict-journal-isolation and --status-listen are off by default; a
|
||||
// non-loopback --status-listen is refused at startup with a clear error.
|
||||
func TestParseFlags_JournalIsolationAndStatusListen(t *testing.T) {
|
||||
f, err := parseFlags([]string{"--authority-store", t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.strictJournalIsolation || f.statusListen != "" {
|
||||
t.Fatalf("defaults: strict=%v status-listen=%q, want off", f.strictJournalIsolation, f.statusListen)
|
||||
}
|
||||
f, err = parseFlags([]string{"--authority-store", t.TempDir(), "--strict-journal-isolation", "--status-listen", "127.0.0.1:9335"})
|
||||
if err != nil || !f.strictJournalIsolation || f.statusListen != "127.0.0.1:9335" {
|
||||
t.Fatalf("set: %+v %v", f, err)
|
||||
}
|
||||
for _, bad := range []string{"0.0.0.0:9335", ":9335", "192.168.1.10:9335"} {
|
||||
_, err := parseFlags([]string{"--authority-store", t.TempDir(), "--status-listen", bad})
|
||||
if err == nil || !strings.Contains(err.Error(), "must be a loopback address") {
|
||||
t.Fatalf("--status-listen %s: %v, want a loopback refusal", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,8 @@ type flags struct {
|
||||
workspaceHEADBase string
|
||||
frontendPublicationRuntimeHTTP bool
|
||||
frontendPublicationRuntimeListen string
|
||||
strictJournalIsolation bool
|
||||
statusListen string
|
||||
version bool
|
||||
// printReadyLine: test-only flag that emits a single
|
||||
// structured JSON line to stdout after the gRPC listener is
|
||||
@@ -110,6 +112,8 @@ func parseFlags(args []string) (flags, error) {
|
||||
fs.StringVar(&f.workspaceHEADBase, "workspace-head-base-url", "", "filer HTTP directory containing per-volume HEAD files; required with --workspace-rpc")
|
||||
fs.BoolVar(&f.frontendPublicationRuntimeHTTP, "frontend-publication-runtime-http", false, "enable disabled-by-default frontend publication HTTP runtime; confirms post-failback authority publication only")
|
||||
fs.StringVar(&f.frontendPublicationRuntimeListen, "frontend-publication-runtime-listen", "127.0.0.1:9334", "HTTP listen address for --frontend-publication-runtime-http")
|
||||
fs.BoolVar(&f.strictJournalIsolation, "strict-journal-isolation", false, "refuse new work on nodes whose durable root shares the authority store's file system (one journal): their heartbeats are refused until they serve a volume, and no placement or move targets them; off = alarm only")
|
||||
fs.StringVar(&f.statusListen, "status-listen", "", "loopback HTTP address for the read-only GET /status/workspace-lease endpoint; empty = off")
|
||||
fs.BoolVar(&f.version, "version", false, "print build provenance and exit")
|
||||
fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout after listener bound")
|
||||
fs.SetOutput(os.Stderr)
|
||||
@@ -131,6 +135,9 @@ func parseFlags(args []string) (flags, error) {
|
||||
if f.authorityStore == "" {
|
||||
return flags{}, fmt.Errorf("--authority-store is required")
|
||||
}
|
||||
if err := master.ValidateStatusListen(f.statusListen); err != nil {
|
||||
return flags{}, err
|
||||
}
|
||||
if f.launcherExternalISCSI && f.launcherCHAPSecretName == "" {
|
||||
return flags{}, fmt.Errorf("cannot enable --launcher-external-iscsi without --launcher-iscsi-chap-secret-name")
|
||||
}
|
||||
@@ -182,6 +189,8 @@ func run(f flags) int {
|
||||
FailbackRuntimeRPC: f.failbackRuntimeRPC,
|
||||
FrontendPublicationRuntimeHTTP: f.frontendPublicationRuntimeHTTP,
|
||||
FrontendPublicationRuntimeListen: f.frontendPublicationRuntimeListen,
|
||||
StrictJournalIsolation: f.strictJournalIsolation,
|
||||
StatusListen: f.statusListen,
|
||||
}
|
||||
if f.workspaceRPC {
|
||||
reader, err := master.NewWorkspaceHEADReader(f.workspaceHEADBase)
|
||||
|
||||
@@ -36,6 +36,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"github.com/seaweedfs/seaweed-block/core/transport"
|
||||
"github.com/seaweedfs/seaweed-block/internal/buildinfo"
|
||||
)
|
||||
@@ -1511,6 +1512,10 @@ func deriveDualLaneAddr(addr string) (string, error) {
|
||||
// beside the volume's durable files, or "" for non-durable memback runs.
|
||||
// hostConfig is the volume host's configuration from the flags.
|
||||
func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config {
|
||||
var ident storeident.Identity
|
||||
if f.durableRoot != "" {
|
||||
ident = storeident.Of(f.durableRoot)
|
||||
}
|
||||
return volume.Config{
|
||||
MasterAddr: f.masterAddr,
|
||||
ServerID: f.serverID,
|
||||
@@ -1524,6 +1529,7 @@ func hostConfig(f flags, readyCh chan<- adapter.AssignmentInfo) volume.Config {
|
||||
EnableT1Readiness: f.enableT1Readiness,
|
||||
WorkspaceLease: f.workspaceLease,
|
||||
RF1Only: rf1Only(f),
|
||||
StorageIdentity: ident,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
)
|
||||
|
||||
// The host config carries the durable root's file-system identity (what the
|
||||
// heartbeat reports); a memback run (no durable root) reports unknown.
|
||||
func TestHostConfigStorageIdentityFromDurableRoot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if got, want := hostConfig(flags{durableRoot: root}, nil).StorageIdentity, storeident.Of(root); got != want {
|
||||
t.Fatalf("durable root identity = %+v, want %+v", got, want)
|
||||
}
|
||||
if got := hostConfig(flags{}, nil).StorageIdentity; got != (storeident.Identity{}) {
|
||||
t.Fatalf("memback identity = %+v, want unknown", got)
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package v2legacy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TODO(format-v3 row 14a): retain raw-codec controls in the default suite;
|
||||
// these real v2-engine fixtures remain explicit in the tagged migration suite.
|
||||
func TestReadSuperblockRefusesOtherFormats(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "v2")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := ReadSuperblock(raw[:SuperblockSize])
|
||||
if err != nil || sb.WALOffset != SuperblockSize || sb.BlockSize != 4096 {
|
||||
t.Fatalf("real v2 superblock: %+v, %v", sb, err)
|
||||
}
|
||||
impl2 := append([]byte(nil), raw[:SuperblockSize]...)
|
||||
binary.LittleEndian.PutUint32(impl2[92:], 2)
|
||||
if _, err := ReadSuperblock(impl2); !errors.Is(err, ErrImplUnsupported) {
|
||||
t.Fatalf("impl version 2: err = %v, want ErrImplUnsupported", err)
|
||||
}
|
||||
v3 := append([]byte(nil), raw[:SuperblockSize]...)
|
||||
binary.LittleEndian.PutUint16(v3[4:], 3)
|
||||
if _, err := ReadSuperblock(v3); !errors.Is(err, ErrNotV2) {
|
||||
t.Fatalf("version 3: err = %v, want ErrNotV2", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Real v2 stores: a cleanly closed, flushed store scans clean; a store with
|
||||
// synced records that were never flushed (a crash) refuses, even though
|
||||
// its superblock may say head = tail (the #156 shape: bounds not persisted
|
||||
// by an ordinary Sync).
|
||||
func TestScanCleanOnRealV2Stores(t *testing.T) {
|
||||
scan := func(t *testing.T, path string) []Finding {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := ReadSuperblock(raw[:SuperblockSize])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return ScanClean(raw[SuperblockSize:SuperblockSize+sb.WALSize], sb.WALCheckpointLSN)
|
||||
}
|
||||
blk := make([]byte, 4096)
|
||||
t.Run("cleanly closed", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "clean")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
if _, err := s.Write(lba, blk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f := scan(t, path); len(f) != 0 {
|
||||
t.Fatalf("a cleanly closed v2 store refused: %+v", f[0])
|
||||
}
|
||||
})
|
||||
t.Run("synced, never flushed", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "dirty")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 2; lba++ {
|
||||
if _, err := s.Write(lba, blk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f := scan(t, path); len(f) == 0 {
|
||||
t.Fatal("synced unflushed v2 records scanned clean")
|
||||
}
|
||||
_ = s.Close()
|
||||
})
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
// Package v2legacy is the frozen v2/impl1 reader used only by the offline
|
||||
// migration tool (`sw-block migrate-v3`, format bump v3, DESIGN r17.4
|
||||
// section 10.1; plan row 13). It is a copy of the v2 superblock layout and
|
||||
// the v2 WAL entry framing as they stand before the format bump, kept here
|
||||
// so that the v3 open code holds no legacy reader and row 14 can delete the
|
||||
// legacy production code. Nothing here writes, recovers or replays: the
|
||||
// scan only decides whether the tool must refuse.
|
||||
package v2legacy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
)
|
||||
|
||||
// SuperblockSize is the v2 superblock region at offset 0; the v2 WAL starts
|
||||
// right after it.
|
||||
const SuperblockSize = 4096
|
||||
|
||||
const (
|
||||
magic = "SWBK"
|
||||
version = 2
|
||||
implWALStore = 1
|
||||
implVersion1 = 1
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNotV2 is any offset-0 content that is not a v2 superblock.
|
||||
ErrNotV2 = errors.New("v2legacy: offset 0 is not a v2 superblock")
|
||||
// ErrImplUnsupported is a v2 superblock of another impl or impl version
|
||||
// (impl 2, C12, is refused by the tool, DESIGN 10).
|
||||
ErrImplUnsupported = errors.New("v2legacy: not walstore impl version 1")
|
||||
)
|
||||
|
||||
// Superblock is the frozen v2 superblock (core/storage/superblock.go at
|
||||
// format version 2).
|
||||
type Superblock struct {
|
||||
Version uint16
|
||||
Flags uint16
|
||||
UUID [16]byte
|
||||
VolumeSize uint64
|
||||
ExtentSize uint32
|
||||
BlockSize uint32
|
||||
WALOffset uint64
|
||||
WALSize uint64
|
||||
WALHead uint64
|
||||
WALTail uint64
|
||||
WALCheckpointLSN uint64
|
||||
CreatedAt uint64
|
||||
ImplKind uint8
|
||||
ImplVersion uint32
|
||||
}
|
||||
|
||||
// ReadSuperblock decodes and validates a v2/impl1 superblock (precondition
|
||||
// 2: magic, version 2, ImplKind walstore, ImplVersion 1).
|
||||
func ReadSuperblock(buf []byte) (Superblock, error) {
|
||||
if len(buf) < SuperblockSize {
|
||||
return Superblock{}, fmt.Errorf("%w: short header (%d bytes)", ErrNotV2, len(buf))
|
||||
}
|
||||
le := binary.LittleEndian
|
||||
if string(buf[0:4]) != magic {
|
||||
return Superblock{}, fmt.Errorf("%w: bad magic", ErrNotV2)
|
||||
}
|
||||
var sb Superblock
|
||||
sb.Version = le.Uint16(buf[4:])
|
||||
if sb.Version != version {
|
||||
return Superblock{}, fmt.Errorf("%w: version %d", ErrNotV2, sb.Version)
|
||||
}
|
||||
sb.Flags = le.Uint16(buf[6:])
|
||||
copy(sb.UUID[:], buf[8:24])
|
||||
sb.VolumeSize = le.Uint64(buf[24:])
|
||||
sb.ExtentSize = le.Uint32(buf[32:])
|
||||
sb.BlockSize = le.Uint32(buf[36:])
|
||||
sb.WALOffset = le.Uint64(buf[40:])
|
||||
sb.WALSize = le.Uint64(buf[48:])
|
||||
sb.WALHead = le.Uint64(buf[56:])
|
||||
sb.WALTail = le.Uint64(buf[64:])
|
||||
sb.WALCheckpointLSN = le.Uint64(buf[72:])
|
||||
sb.CreatedAt = le.Uint64(buf[80:])
|
||||
sb.ImplKind = buf[88]
|
||||
sb.ImplVersion = le.Uint32(buf[92:])
|
||||
switch {
|
||||
case sb.VolumeSize == 0, sb.BlockSize == 0, sb.ExtentSize == 0, sb.WALSize == 0:
|
||||
return Superblock{}, fmt.Errorf("%w: zero geometry field", ErrNotV2)
|
||||
case sb.WALOffset != SuperblockSize:
|
||||
return Superblock{}, fmt.Errorf("%w: WALOffset %d", ErrNotV2, sb.WALOffset)
|
||||
case sb.VolumeSize%uint64(sb.BlockSize) != 0:
|
||||
return Superblock{}, fmt.Errorf("%w: VolumeSize not block aligned", ErrNotV2)
|
||||
}
|
||||
if sb.ImplKind != implWALStore || sb.ImplVersion != implVersion1 {
|
||||
return Superblock{}, fmt.Errorf("%w: ImplKind %d ImplVersion %d", ErrImplUnsupported, sb.ImplKind, sb.ImplVersion)
|
||||
}
|
||||
return sb, nil
|
||||
}
|
||||
|
||||
// The frozen v2 WAL entry framing (core/storage/wal_entry.go): a 30-byte
|
||||
// prefix LSN(8) Reserved(8) Type(1) Flags(1) LBA(8) Length(4), then the
|
||||
// payload (write, batch and padding only), then CRC32-IEEE(4) over prefix
|
||||
// and payload, and EntrySize(4).
|
||||
const (
|
||||
entryPrefix = 30
|
||||
entryHeader = 38
|
||||
|
||||
typeWrite = 0x01
|
||||
typeTrim = 0x02
|
||||
typeBarrier = 0x03
|
||||
typeBatch = 0x04
|
||||
typePadding = 0xFF
|
||||
)
|
||||
|
||||
// Finding is one offset of the WAL region that refuses the migration.
|
||||
type Finding struct {
|
||||
Offset uint64 // relative to the WAL region start
|
||||
Type uint8
|
||||
LSN uint64 // the record's last LSN (a batch counts by its last)
|
||||
Reason string
|
||||
Covered bool // LSN <= checkpoint: not a refusal (reported for tests only)
|
||||
}
|
||||
|
||||
// ScanClean is precondition 3 of DESIGN 10.1: an exhaustive,
|
||||
// refusal-biased scan of the whole v2 WAL region. It tries the frozen
|
||||
// decoder at every byte offset, reading circularly so a record crossing the
|
||||
// region end is tried too. An offset refuses when it decodes as a known
|
||||
// type whose type-derived footprint (38 + Length for write, batch and
|
||||
// padding; 38 for trim and barrier) fits in the region, whose CRC and
|
||||
// EntrySize are valid, and whose last LSN is above checkpoint; or when a
|
||||
// CRC-valid candidate of a known type cannot be classified (a zero or
|
||||
// overflowing batch count). A CRC-valid record at or below the checkpoint
|
||||
// is already in the extent and is ignored. It never runs recovery or
|
||||
// replay. It returns the refusing findings, in offset order.
|
||||
func ScanClean(wal []byte, checkpoint uint64) []Finding {
|
||||
n := uint64(len(wal))
|
||||
var out []Finding
|
||||
at := func(i uint64) byte { return wal[i%n] }
|
||||
read := func(off, length uint64) []byte {
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = at(off + uint64(i))
|
||||
}
|
||||
return b
|
||||
}
|
||||
for off := uint64(0); off < n && n >= entryHeader; off++ {
|
||||
typ := at(off + 16)
|
||||
var payload bool
|
||||
switch typ {
|
||||
case typeWrite, typeBatch, typePadding:
|
||||
payload = true
|
||||
case typeTrim, typeBarrier:
|
||||
default:
|
||||
continue
|
||||
}
|
||||
prefix := read(off, entryPrefix)
|
||||
length := uint64(binary.LittleEndian.Uint32(prefix[26:]))
|
||||
footprint := uint64(entryHeader)
|
||||
if payload {
|
||||
footprint += length
|
||||
}
|
||||
if footprint > n {
|
||||
continue // cannot be a record of this region
|
||||
}
|
||||
body := read(off, footprint)
|
||||
dataEnd := footprint - 8
|
||||
if binary.LittleEndian.Uint32(body[dataEnd:]) != crc32.ChecksumIEEE(body[:dataEnd]) ||
|
||||
uint64(binary.LittleEndian.Uint32(body[dataEnd+4:])) != footprint {
|
||||
continue
|
||||
}
|
||||
lsn := binary.LittleEndian.Uint64(body[0:])
|
||||
last := lsn
|
||||
f := Finding{Offset: off, Type: typ}
|
||||
if typ == typeBatch {
|
||||
count := binary.LittleEndian.Uint64(body[8:])
|
||||
if count == 0 || lsn+count-1 < lsn {
|
||||
f.LSN, f.Reason = lsn, "CRC-valid batch with an unclassifiable block count"
|
||||
out = append(out, f)
|
||||
continue
|
||||
}
|
||||
last = lsn + count - 1
|
||||
}
|
||||
f.LSN = last
|
||||
if last <= checkpoint {
|
||||
continue // already in the extent
|
||||
}
|
||||
f.Reason = fmt.Sprintf("CRC-valid v2 record type %#x with LSN %d above the checkpoint %d", typ, last, checkpoint)
|
||||
out = append(out, f)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package v2legacy
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Plan row 13a controls (DESIGN r17.4 section 10.1 precondition 3; owner
|
||||
// claude03): the frozen v2 decoder and the exhaustive, refusal-biased scan.
|
||||
|
||||
// encode is a test-only encoder of the frozen v2 framing.
|
||||
func encode(lsn, reserved uint64, typ uint8, lba uint64, length uint32, data []byte) []byte {
|
||||
b := make([]byte, entryPrefix+len(data)+8)
|
||||
le := binary.LittleEndian
|
||||
le.PutUint64(b[0:], lsn)
|
||||
le.PutUint64(b[8:], reserved)
|
||||
b[16] = typ
|
||||
le.PutUint64(b[18:], lba)
|
||||
le.PutUint32(b[26:], length)
|
||||
copy(b[entryPrefix:], data)
|
||||
end := entryPrefix + len(data)
|
||||
le.PutUint32(b[end:], crc32.ChecksumIEEE(b[:end]))
|
||||
le.PutUint32(b[end+4:], uint32(entryHeader+len(data)))
|
||||
return b
|
||||
}
|
||||
|
||||
func region(n int, at int, recs ...[]byte) []byte {
|
||||
w := make([]byte, n)
|
||||
for _, r := range recs {
|
||||
for i := range r {
|
||||
w[(at+i)%n] = r[i]
|
||||
}
|
||||
at += len(r)
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func write(lsn uint64) []byte { return encode(lsn, 0, typeWrite, 1, 64, make([]byte, 64)) }
|
||||
|
||||
func TestScanCleanFindsEveryUnflushedV2RecordShape(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
wal []byte
|
||||
checkpoint uint64
|
||||
refuse bool
|
||||
}{
|
||||
{"an empty region", make([]byte, 4096), 0, false},
|
||||
{"a write above the checkpoint", region(4096, 100, write(5)), 4, true},
|
||||
{"a write at the checkpoint is in the extent", region(4096, 100, write(5)), 5, false},
|
||||
{"a record wrapping across the region end", region(4096, 4096-50, write(9)), 0, true},
|
||||
{"a trim whose affected range exceeds the region (footprint 38)", region(4096, 0, encode(7, 0, typeTrim, 0, 1<<30, nil)), 6, true},
|
||||
{"a barrier above the checkpoint", region(4096, 0, encode(7, 0, typeBarrier, 0, 0, nil)), 6, true},
|
||||
{"a batch counts by its last LSN", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 4, true},
|
||||
{"a batch fully below the checkpoint", region(4096, 0, encode(3, 3, typeBatch, 0, 64, make([]byte, 64))), 5, false},
|
||||
{"a CRC-valid batch with a zero count is unclassifiable", region(4096, 0, encode(3, 0, typeBatch, 0, 64, make([]byte, 64))), 9, true},
|
||||
{"a record embedded in another record's payload", region(4096, 0, encode(2, 0, typeWrite, 1, uint32(len(write(9))), write(9))), 5, true},
|
||||
{"a corrupt CRC is no record", func() []byte { w := region(4096, 0, write(9)); w[40] ^= 0xFF; return w }(), 0, false},
|
||||
{"a record larger than the region cannot be one", encode(9, 0, typeWrite, 1, 100, make([]byte, 100))[:64], 0, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := ScanClean(c.wal, c.checkpoint)
|
||||
if (len(got) > 0) != c.refuse {
|
||||
t.Fatalf("findings %+v, want refuse = %v", got, c.refuse)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -77,9 +77,6 @@ func run(args []string, stdout, stderr io.Writer) int {
|
||||
fmt.Fprintln(stdout, buildinfo.Version("sw-block"))
|
||||
return ops.VolumeStatusExitOK
|
||||
}
|
||||
if args[0] == "migrate-v3" {
|
||||
return runMigrateV3(args[1:], stdout, stderr)
|
||||
}
|
||||
if args[0] != "ops" {
|
||||
fmt.Fprintf(stderr, "sw-block: unknown command %q\n", args[0])
|
||||
usage(stderr)
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// `sw-block migrate-v3` (format bump v3, DESIGN r17.4 section 10.1; plan row
|
||||
// 13b): the offline, in-place v2/impl1 -> v3/impl3 descriptor rewrite of a
|
||||
// cleanly closed volume whose WAL is fully flushed. No record is converted
|
||||
// and no extent byte is touched. Every step is durable before the next.
|
||||
|
||||
// errMigrateNotClean is DESIGN 10.1's ErrMigrateNotClean.
|
||||
var errMigrateNotClean = errors.New("migrate-v3: the volume is not cleanly flushed: open with the old binary, flush, close cleanly, retry")
|
||||
|
||||
// errMigrateNeitherSlot: neither offset 0 nor offset 4096 holds a valid
|
||||
// slot or v2 superblock; nothing is changed.
|
||||
var errMigrateNeitherSlot = errors.New("migrate-v3: no valid v2 superblock or v3 descriptor slot; nothing changed")
|
||||
|
||||
// migrateStepHook, when set by a test, runs after each durable step with
|
||||
// its name; returning an error stops the tool there (a simulated crash).
|
||||
var migrateStepHook func(step string) error
|
||||
|
||||
// syncDirHook, when set by a test, runs at every directory fsync; an error
|
||||
// fails that fsync.
|
||||
var syncDirHook func(path string) error
|
||||
|
||||
func runMigrateV3(args []string, stdout, stderr io.Writer) int {
|
||||
fs := flag.NewFlagSet("migrate-v3", flag.ContinueOnError)
|
||||
fs.SetOutput(stderr)
|
||||
chunkBlocks := fs.Uint64("chunk-blocks", 0, "the provider's chunk size in blocks (the map geometry); required")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return 2
|
||||
}
|
||||
if fs.NArg() != 1 || *chunkBlocks == 0 {
|
||||
fmt.Fprintln(stderr, "usage: sw-block migrate-v3 --chunk-blocks N <volume-file>")
|
||||
return 2
|
||||
}
|
||||
if err := migrateV3(fs.Arg(0), *chunkBlocks, stdout); err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func migrateV3(path string, chunkBlocks uint64, out io.Writer) error {
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
if err := storage.LockWALStoreFile(f); err != nil {
|
||||
return err
|
||||
}
|
||||
head := make([]byte, 2*storage.MigrationSlotSize)
|
||||
if _, err := f.ReadAt(head, 0); err != nil {
|
||||
return fmt.Errorf("migrate-v3: read the descriptor region: %w", err)
|
||||
}
|
||||
a, b := head[:storage.MigrationSlotSize], head[storage.MigrationSlotSize:]
|
||||
sb, v2err := v2legacy.ReadSuperblock(a)
|
||||
switch {
|
||||
case v2err == nil:
|
||||
// Not committed: restart from step 1 with a full rescan (the old
|
||||
// binary may have run since; nothing earlier is trusted).
|
||||
return migrateFromV2(f, path, sb, chunkBlocks, out)
|
||||
case errors.Is(v2err, v2legacy.ErrImplUnsupported):
|
||||
return fmt.Errorf("migrate-v3: %w (an impl-2 volume stays on its old binary)", v2err)
|
||||
}
|
||||
stA, genA := storage.ClassifyMigrationSlotV3(a)
|
||||
stB, _ := storage.ClassifyMigrationSlotV3(b)
|
||||
switch {
|
||||
case stA == storage.MigrationSlotCommitted:
|
||||
// Committed. Finish step 6 if B was never rewritten, then step 7.
|
||||
if genA == 2 && stB != storage.MigrationSlotCommitted {
|
||||
rb, err := storage.RolloverSlotV3(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := pwriteSync(f, rb, storage.MigrationSlotBOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return retireC11(path)
|
||||
case stB == storage.MigrationSlotCommitted:
|
||||
// Committed and possibly in use: only step 7.
|
||||
return retireC11(path)
|
||||
case stB == storage.MigrationSlotPrepared:
|
||||
// A torn step 5 or an old-binary run after preparation followed by
|
||||
// damage to A: the bytes cannot tell; never guess.
|
||||
return fmt.Errorf("migrate-v3: %w; nothing changed (an operator decision, using the backup)", storage.ErrMigrationIncomplete)
|
||||
default:
|
||||
return errMigrateNeitherSlot
|
||||
}
|
||||
}
|
||||
|
||||
func migrateFromV2(f *os.File, path string, sb v2legacy.Superblock, chunkBlocks uint64, out io.Writer) error {
|
||||
src := storage.MigrationSourceV3{
|
||||
UUID: sb.UUID, VolumeSize: sb.VolumeSize, ExtentSize: sb.ExtentSize, BlockSize: sb.BlockSize,
|
||||
OldWALOffset: sb.WALOffset, OldWALSize: sb.WALSize, CreatedAt: sb.CreatedAt,
|
||||
CheckpointLSN: sb.WALCheckpointLSN, ChunkBlocks: chunkBlocks,
|
||||
}
|
||||
// Precondition 4 first (read-only): the geometry, including the checked
|
||||
// extent end, refuses before the WAL is read or anything is written.
|
||||
if err := storage.ValidateMigrationV3(src); err != nil {
|
||||
return err
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size := uint64(fi.Size()); sb.WALOffset > size || sb.WALSize > size-sb.WALOffset { // no wrapping sum
|
||||
return fmt.Errorf("%w: the v2 WAL [%d, %d) extends past the file end %d", storage.ErrMigrateGeometry, sb.WALOffset, sb.WALOffset+sb.WALSize, fi.Size())
|
||||
}
|
||||
// Step 1: precondition 3, read-only and before any write.
|
||||
if sb.WALHead != sb.WALTail {
|
||||
return fmt.Errorf("%w (WALHead %d != WALTail %d)", errMigrateNotClean, sb.WALHead, sb.WALTail)
|
||||
}
|
||||
wal := make([]byte, sb.WALSize)
|
||||
if _, err := f.ReadAt(wal, int64(sb.WALOffset)); err != nil {
|
||||
return fmt.Errorf("migrate-v3: read the v2 WAL: %w", err)
|
||||
}
|
||||
if found := v2legacy.ScanClean(wal, sb.WALCheckpointLSN); len(found) > 0 {
|
||||
return fmt.Errorf("%w (%d unflushed record(s); first at WAL offset %d: %s)", errMigrateNotClean, len(found), found[0].Offset, found[0].Reason)
|
||||
}
|
||||
if err := step("scanned"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 2: the atomic operator backup of the v2 superblock.
|
||||
raw := make([]byte, v2legacy.SuperblockSize)
|
||||
if _, err := f.ReadAt(raw, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFileAtomic(path+".v2-superblock.bak", raw); err != nil {
|
||||
return fmt.Errorf("migrate-v3: backup: %w", err)
|
||||
}
|
||||
if err := step("backup"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 3: the initial map sidecar (all UNKNOWN), durable.
|
||||
plan, err := storage.PrepareMigrationV3(path+".chunkmap", src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate-v3: initial map: %w", err)
|
||||
}
|
||||
if err := syncDirOf(path); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("map"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 4: the prepared slot B, over the old WAL's first 4 KiB.
|
||||
if err := pwriteSync(f, plan.PreparedB, storage.MigrationSlotBOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("prepared"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 5: slot A, phase 0: the commit point.
|
||||
if err := pwriteSync(f, plan.CommittedA, storage.MigrationSlotAOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("committed"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 6: slot B rewritten at phase 0 (two-slot redundancy).
|
||||
if err := pwriteSync(f, plan.RolloverB, storage.MigrationSlotBOffset); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := step("rollover"); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 7: retire the v2 C11 bitmap, only after the commit.
|
||||
if err := retireC11(path); err != nil {
|
||||
return err
|
||||
}
|
||||
// Step 8.
|
||||
fmt.Fprintf(out, "migrated %s to v3: descriptor sha256 %s; backups left in place\n", path, hex.EncodeToString(plan.DescriptorHash[:]))
|
||||
return nil
|
||||
}
|
||||
|
||||
func step(name string) error {
|
||||
if h := migrateStepHook; h != nil {
|
||||
return h(name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pwriteSync(f *os.File, b []byte, off int64) error {
|
||||
if _, err := f.WriteAt(b, off); err != nil {
|
||||
return fmt.Errorf("migrate-v3: write at %d: %w", off, err)
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
return fmt.Errorf("migrate-v3: fsync: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeFileAtomic writes b to name via name.tmp, fsync, rename and a
|
||||
// directory fsync; a leftover .tmp from an earlier run is replaced.
|
||||
func writeFileAtomic(name string, b []byte) error {
|
||||
tmp := name + ".tmp"
|
||||
if err := os.Remove(tmp); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
t, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := t.Write(b); err != nil {
|
||||
t.Close()
|
||||
return err
|
||||
}
|
||||
if err := t.Sync(); err != nil {
|
||||
t.Close()
|
||||
return err
|
||||
}
|
||||
if err := t.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, name); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncDirOf(name)
|
||||
}
|
||||
|
||||
// retireC11 is step 7: rename a v2 .chunkbitmap sidecar to
|
||||
// <file>.v2-chunkbitmap.bak and fsync the directory. Absent is done.
|
||||
func retireC11(path string) error {
|
||||
err := os.Rename(path+".chunkbitmap", path+".v2-chunkbitmap.bak")
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if _, serr := os.Stat(path + ".v2-chunkbitmap.bak"); serr != nil {
|
||||
return nil // there was no v2 bitmap
|
||||
}
|
||||
// An earlier run renamed it; its directory fsync may have failed, so
|
||||
// make the rename durable now (codex01 row 13b P2).
|
||||
return syncDirOf(path)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate-v3: retire the v2 chunk bitmap: %w", err)
|
||||
}
|
||||
return syncDirOf(path)
|
||||
}
|
||||
|
||||
// syncDirOf fsyncs the directory holding path. A directory cannot be
|
||||
// fsynced on Windows; there it is a no-op, as in the provider.
|
||||
func syncDirOf(path string) error {
|
||||
if h := syncDirHook; h != nil {
|
||||
if err := h(path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
return nil
|
||||
}
|
||||
d, err := os.Open(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer d.Close()
|
||||
return d.Sync()
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestMigrateV3ExcludesOpenUntilCommitFinishes(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
parked, resume := make(chan struct{}), make(chan struct{})
|
||||
var once sync.Once
|
||||
release := func() { once.Do(func() { close(resume) }) }
|
||||
defer release()
|
||||
migrateStepHook = func(step string) error {
|
||||
if step == "committed" {
|
||||
close(parked)
|
||||
<-resume
|
||||
}
|
||||
return nil
|
||||
}
|
||||
finished := make(chan error, 1)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
finished <- migrateV3(path, 4, &bytes.Buffer{})
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
release()
|
||||
select {
|
||||
case <-done:
|
||||
migrateStepHook = nil
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Error("migration worker did not stop during cleanup")
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-parked:
|
||||
case err := <-finished:
|
||||
t.Fatalf("migration stopped before the held commit: %v", err)
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("migration did not reach the held commit")
|
||||
}
|
||||
if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrWALStoreLocked) {
|
||||
if s != nil {
|
||||
_ = s.Close()
|
||||
}
|
||||
t.Fatalf("open during migration: %v, want volume locked", err)
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case err := <-finished:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("migration did not release its lock")
|
||||
}
|
||||
s, err := storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatalf("open after migration: %v", err)
|
||||
}
|
||||
_ = s.Close()
|
||||
}
|
||||
|
||||
func TestMigrateV3RefusesAnOpenV3Volume(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "volume")
|
||||
s, err := storage.CreateMappedWALStoreV3Test(path, 64, migBlock, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
// Windows byte-range locks reject reads through a second handle. Snapshot
|
||||
// only while no owner is open, then hold the real owner for the CLI call.
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := snapshotFiles(t, path)
|
||||
s, err = storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, msg := migrate(t, path)
|
||||
if code != 1 || !strings.Contains(msg, "locked") {
|
||||
t.Fatalf("migration must refuse an open v3 volume: exit=%d message=%s", code, msg)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !sameFiles(before, snapshotFiles(t, path)) {
|
||||
t.Fatal("refused migration modified the open volume")
|
||||
}
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("migration after owner close: exit=%d message=%s", code, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Row 13b through the actual v3 open (tag swblock_format_v3_test).
|
||||
|
||||
// A migrated volume opens as v3 and serves the v2 blocks unchanged; its
|
||||
// map is the initial one (all UNKNOWN, covered = the v2 checkpoint); a
|
||||
// v3 write and a reopen work. Mutant: an initial map with clean entries
|
||||
// fails here.
|
||||
func TestMigrateV3VolumeOpensAsV3(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("migrate: %s", msg)
|
||||
}
|
||||
s, err := storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatalf("v3 open of a migrated volume: %v", err)
|
||||
}
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
covered, allUnknown := storage.MapCoverageV3Test(s)
|
||||
if !allUnknown || covered != s.CheckpointLSN() {
|
||||
t.Fatalf("initial map: covered %d (checkpoint %d), all UNKNOWN %v", covered, s.CheckpointLSN(), allUnknown)
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
got, err := s.Read(lba)
|
||||
if err != nil || !bytes.Equal(got, migBlk(0x10+byte(lba))) {
|
||||
t.Fatalf("LBA %d after migration: err %v", lba, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Write(7, migBlk(0x77)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := storage.OpenMappedWALStoreV3Test(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := r.Read(7); !bytes.Equal(got, migBlk(0x77)) {
|
||||
t.Fatal("a v3 write after migration did not survive a reopen")
|
||||
}
|
||||
}
|
||||
|
||||
// A prepared-only volume (stopped before the commit, A then damaged) is
|
||||
// refused by v3 open with ErrMigrationIncomplete, as by the tool.
|
||||
func TestMigrateV3PreparedOnlyRefusedByV3Open(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
damageSlotA(t, path)
|
||||
if s, err := storage.OpenMappedWALStoreV3Test(path); !errors.Is(err, storage.ErrMigrationIncomplete) {
|
||||
if s != nil {
|
||||
_ = s.Close()
|
||||
}
|
||||
t.Fatalf("v3 open of a prepared-only volume: err = %v, want ErrMigrationIncomplete", err)
|
||||
}
|
||||
}
|
||||
@@ -1,467 +0,0 @@
|
||||
//go:build swblock_format_v3_test
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/cmd/sw-block/internal/v2legacy"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// Plan row 13b controls (DESIGN r17.4 section 10.1; owner claude03), all
|
||||
// through the actual CLI entry (run).
|
||||
|
||||
const migBlock = 4096
|
||||
|
||||
func migBlk(b byte) []byte { return bytes.Repeat([]byte{b}, migBlock) }
|
||||
|
||||
// v2Volume creates a real v2/impl1 volume with 4 written blocks; clean
|
||||
// closes it (flushing), otherwise it is left synced but unflushed.
|
||||
func v2Volume(t *testing.T, clean bool) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "vol")
|
||||
s, err := storage.CreateLegacyWALStoreTest(path, 64, migBlock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !clean {
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
}
|
||||
for lba := uint32(0); lba < 4; lba++ {
|
||||
if _, err := s.Write(lba, migBlk(0x10+byte(lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if clean {
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func migrate(t *testing.T, path string) (int, string) {
|
||||
t.Helper()
|
||||
var out, errb bytes.Buffer
|
||||
code := run([]string{"migrate-v3", "--chunk-blocks", "4", path}, &out, &errb)
|
||||
return code, out.String() + errb.String()
|
||||
}
|
||||
|
||||
// snapshotFiles reads the volume and every sidecar next to it.
|
||||
func snapshotFiles(t *testing.T, path string) map[string][]byte {
|
||||
t.Helper()
|
||||
got := map[string][]byte{}
|
||||
matches, _ := filepath.Glob(path + "*")
|
||||
for _, m := range matches {
|
||||
b, err := os.ReadFile(m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got[filepath.Base(m)] = b
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func sameFiles(a, b map[string][]byte) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for k, v := range a {
|
||||
if !bytes.Equal(v, b[k]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// A clean v2 volume migrates: slot A committed (slotGen 2), slot B rolled
|
||||
// over (slotGen 3), every extent byte unchanged, the backup holds the old
|
||||
// superblock, a v2 chunk bitmap is retired, the old binary now refuses the
|
||||
// file, and a rerun changes no byte.
|
||||
func TestMigrateV3CleanVolume(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := v2legacy.ReadSuperblock(before)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
extentBase := sb.WALOffset + sb.WALSize
|
||||
if code, msg := migrate(t, path); code != 0 || !strings.Contains(msg, "descriptor sha256") {
|
||||
t.Fatalf("migrate: exit %d: %s", code, msg)
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(after[extentBase:], before[extentBase:]) {
|
||||
t.Fatal("the migration changed extent bytes")
|
||||
}
|
||||
if st, gen := storage.ClassifyMigrationSlotV3(after[:4096]); st != storage.MigrationSlotCommitted || gen != 2 {
|
||||
t.Fatalf("slot A: state %d gen %d, want committed gen 2", st, gen)
|
||||
}
|
||||
if st, gen := storage.ClassifyMigrationSlotV3(after[4096:8192]); st != storage.MigrationSlotCommitted || gen != 3 {
|
||||
t.Fatalf("slot B: state %d gen %d, want committed gen 3", st, gen)
|
||||
}
|
||||
if bak, err := os.ReadFile(path + ".v2-superblock.bak"); err != nil || !bytes.Equal(bak, before[:4096]) {
|
||||
t.Fatalf("backup: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(path + ".chunkbitmap"); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("the v2 chunk bitmap was not retired")
|
||||
}
|
||||
if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err != nil {
|
||||
t.Fatalf("retired bitmap: %v", err)
|
||||
}
|
||||
if s, err := storage.OpenLegacyWALStoreTest(path); err == nil {
|
||||
_ = s.Close()
|
||||
t.Fatal("the old binary opened a migrated volume")
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun: exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a rerun on a committed volume changed bytes")
|
||||
}
|
||||
}
|
||||
|
||||
// Refusals change no byte of the volume or any sidecar: an unflushed WAL
|
||||
// (ErrMigrateNotClean with the operator remedy), an impl-2 volume, and a
|
||||
// file with neither a v2 superblock nor a valid v3 slot. Mutant: skipping
|
||||
// the clean scan migrates the unflushed volume and fails here.
|
||||
func TestMigrateV3RefusalsChangeNothing(t *testing.T) {
|
||||
t.Run("unflushed WAL", func(t *testing.T) {
|
||||
path := v2Volume(t, false)
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if code == 0 || !strings.Contains(msg, "open with the old binary, flush, close cleanly, retry") {
|
||||
t.Fatalf("exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a refused migration changed bytes")
|
||||
}
|
||||
})
|
||||
t.Run("impl 2", func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteAt([]byte{2, 0, 0, 0}, 92); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.Close()
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("an impl-2 volume was not refused unchanged")
|
||||
}
|
||||
})
|
||||
t.Run("neither valid", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "junk")
|
||||
if err := os.WriteFile(path, bytes.Repeat([]byte{0xEE}, 3*4096), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, _ := migrate(t, path); code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("neither-valid was not refused unchanged")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A crash after each step is resumable from the slot bytes alone: before
|
||||
// the commit the rerun restarts with a full rescan; after it, the rerun
|
||||
// only finishes the rollover and the bitmap retirement.
|
||||
func TestMigrateV3CrashAfterEachStepIsResumable(t *testing.T) {
|
||||
for _, stop := range []string{"scanned", "backup", "map", "prepared", "committed", "rollover"} {
|
||||
t.Run(stop, func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == stop {
|
||||
return errors.New("simulated crash after " + s)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
code, _ := migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
if code == 0 {
|
||||
t.Fatal("the simulated crash did not stop the tool")
|
||||
}
|
||||
// Before the commit point (step 5) slot A is still the v2
|
||||
// superblock and the v2 bitmap is not retired; after it A is a
|
||||
// committed v3 slot.
|
||||
crashed, _ := os.ReadFile(path)
|
||||
_, v2err := v2legacy.ReadSuperblock(crashed[:4096])
|
||||
_, bitmapErr := os.Stat(path + ".chunkbitmap")
|
||||
if committed := stop == "committed" || stop == "rollover"; committed {
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(crashed[:4096]); st != storage.MigrationSlotCommitted {
|
||||
t.Fatalf("crash after %s: slot A state %d, want committed", stop, st)
|
||||
}
|
||||
} else if v2err != nil || bitmapErr != nil {
|
||||
t.Fatalf("crash after %s: A still v2 = %v, bitmap present = %v; want both before the commit", stop, v2err == nil, bitmapErr == nil)
|
||||
}
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun after a crash at %s: exit %d: %s", stop, code, msg)
|
||||
}
|
||||
raw, _ := os.ReadFile(path)
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(raw[:4096]); st != storage.MigrationSlotCommitted {
|
||||
t.Fatalf("after the rerun slot A state %d, want committed", st)
|
||||
}
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotCommitted {
|
||||
t.Fatalf("after the rerun slot B state %d, want committed", st)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The old binary runs after preparation (A is still v2, so it opens): the
|
||||
// rerun finds A still v2 and restarts with a full rescan; it refuses while
|
||||
// the old binary's writes are unflushed and migrates once it flushed and
|
||||
// closed. A prepared B with a damaged A is ambiguous and refused with
|
||||
// ErrMigrationIncomplete, writing nothing.
|
||||
func TestMigrateV3OldBinaryAfterPreparation(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop after preparation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
s, err := storage.OpenLegacyWALStoreTest(path)
|
||||
if err != nil {
|
||||
t.Fatalf("the old binary refused a prepared-only volume: %v", err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(9, migBlk(0x99)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
if code, msg := migrate(t, path); code == 0 || !strings.Contains(msg, "not cleanly flushed") {
|
||||
t.Fatalf("rerun over the old binary's unflushed write: exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a refused rerun changed bytes")
|
||||
}
|
||||
_ = s.Close() // stopped without a flush: still not clean
|
||||
if code, _ := migrate(t, path); code == 0 {
|
||||
t.Fatal("the rerun migrated a volume the old binary left unflushed")
|
||||
}
|
||||
// The operator remedy: open with the old binary, flush, close cleanly.
|
||||
s2, err := storage.OpenLegacyWALStoreTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s2.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s2.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun after the old binary closed cleanly: exit %d: %s", code, msg)
|
||||
}
|
||||
|
||||
t.Run("prepared B with a damaged A", func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop after preparation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
f, _ := os.OpenFile(path, os.O_RDWR, 0)
|
||||
_, _ = f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0)
|
||||
f.Close()
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if code == 0 || !strings.Contains(msg, storage.ErrMigrationIncomplete.Error()) || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatalf("exit %d: %s", code, msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The tool never reads or restores its backup: a committed volume reruns
|
||||
// to success with the backup damaged and its slots untouched.
|
||||
func TestMigrateV3NeverRestoresTheBackup(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("migrate: %s", msg)
|
||||
}
|
||||
if err := os.WriteFile(path+".v2-superblock.bak", []byte("damaged"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(path)
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun: %s", msg)
|
||||
}
|
||||
now, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(raw, now) {
|
||||
t.Fatal("a rerun changed the committed volume")
|
||||
}
|
||||
}
|
||||
|
||||
// The old v2 WAL starts at offset 4096, over the prepared slot B, so an
|
||||
// old-binary run can overwrite B partly or wholly (codex03 r8). Either way B
|
||||
// is an invalid slot, never prepared or committed: with A still v2 the rerun
|
||||
// restarts and migrates; with A damaged too, neither slot is valid and the
|
||||
// rerun refuses with no byte changed.
|
||||
func TestMigrateV3OldWALOverwritesThePreparedSlot(t *testing.T) {
|
||||
for _, n := range []int{100, 4096} {
|
||||
for _, damageA := range []bool{false, true} {
|
||||
name := map[int]string{100: "partial", 4096: "full"}[n]
|
||||
if damageA {
|
||||
name += " with A damaged"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
migrateStepHook = func(s string) error {
|
||||
if s == "prepared" {
|
||||
return errors.New("stop after preparation")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
migrate(t, path)
|
||||
migrateStepHook = nil
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteAt(bytes.Repeat([]byte{0xA5}, n), 4096); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if damageA {
|
||||
if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
f.Close()
|
||||
raw, _ := os.ReadFile(path)
|
||||
if st, _ := storage.ClassifyMigrationSlotV3(raw[4096:8192]); st != storage.MigrationSlotInvalid {
|
||||
t.Fatalf("an overwritten B classifies as %d, want invalid", st)
|
||||
}
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if damageA {
|
||||
if code == 0 || !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatalf("neither valid: exit %d, bytes changed: %s", code, msg)
|
||||
}
|
||||
return
|
||||
}
|
||||
if code != 0 {
|
||||
t.Fatalf("rerun with A still v2: exit %d: %s", code, msg)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func damageSlotA(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
if _, err := f.WriteAt(bytes.Repeat([]byte{0xEE}, 4096), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func patchSuperblock(t *testing.T, path string, off int64, v uint64) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
var b [8]byte
|
||||
for i := range b {
|
||||
b[i] = byte(v >> (8 * i))
|
||||
}
|
||||
if _, err := f.WriteAt(b[:], off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 13b P1 and P2: geometry the v3 slot validation would refuse
|
||||
// is refused before ANY write (no backup, no map, the volume unchanged):
|
||||
// an aligned VolumeSize whose extent end overflows, and a v2 WAL size that
|
||||
// extends past the file end (refused before the scan allocates it).
|
||||
// Mutants: no checked extent end in ValidateMigrationV3, no file-size
|
||||
// bound before the WAL read.
|
||||
func TestMigrateV3BadGeometryRefusedBeforeAnyWrite(t *testing.T) {
|
||||
for name, patch := range map[string][2]uint64{
|
||||
"extent end overflows": {24, 1 << 63}, // VolumeSize, block aligned
|
||||
"WAL past the file end": {48, 1<<45 + 4096}, // WALSize, v3 size aligned
|
||||
"WAL region wraps": {48, ^uint64(0) - 4095}, // WALSize 2^64-4096: every sum wraps
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
patchSuperblock(t, path, int64(patch[0]), patch[1])
|
||||
snap := snapshotFiles(t, path)
|
||||
code, msg := migrate(t, path)
|
||||
if code == 0 || !strings.Contains(msg, "cannot be migrated in place") {
|
||||
t.Fatalf("exit %d: %s", code, msg)
|
||||
}
|
||||
if !sameFiles(snap, snapshotFiles(t, path)) {
|
||||
t.Fatal("a geometry refusal wrote a backup, a map or volume bytes")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// codex01 row 13b P2: an earlier run renamed the v2 chunk bitmap but its
|
||||
// directory fsync failed; the rerun (source gone) still fsyncs the
|
||||
// directory so the rename is durable. Mutant: treating the missing source
|
||||
// as done without the fsync fails here.
|
||||
func TestMigrateV3RetirementRerunFsyncsTheDirectory(t *testing.T) {
|
||||
path := v2Volume(t, true)
|
||||
if err := os.WriteFile(path+".chunkbitmap", []byte("c11"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed := false
|
||||
syncDirHook = func(string) error {
|
||||
if _, err := os.Stat(path + ".v2-chunkbitmap.bak"); err == nil && !failed {
|
||||
failed = true
|
||||
return errors.New("injected directory fsync failure")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
defer func() { syncDirHook = nil }()
|
||||
if code, _ := migrate(t, path); code == 0 {
|
||||
t.Fatal("the injected retirement fsync failure did not fail the tool")
|
||||
}
|
||||
calls := 0
|
||||
syncDirHook = func(string) error { calls++; return nil }
|
||||
if code, msg := migrate(t, path); code != 0 {
|
||||
t.Fatalf("rerun: exit %d: %s", code, msg)
|
||||
}
|
||||
if calls == 0 {
|
||||
t.Fatal("the rerun did not fsync the directory of the earlier rename")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRetiredMigrationCommandRefusesWithoutMutation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "legacy")
|
||||
want := []byte("unmodified legacy volume")
|
||||
if err := os.WriteFile(path, want, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out, errout bytes.Buffer
|
||||
if code := run([]string{"migrate-v3", "--path", path}, &out, &errout); code == 0 {
|
||||
t.Fatal("retired converter accepted input")
|
||||
}
|
||||
if !bytes.Contains(errout.Bytes(), []byte("unknown command")) {
|
||||
t.Fatalf("converter still dispatched: %s", errout.Bytes())
|
||||
}
|
||||
got, err := os.ReadFile(path)
|
||||
if err != nil || !bytes.Equal(got, want) {
|
||||
t.Fatalf("retired converter changed input: %v", err)
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil || len(entries) != 1 {
|
||||
t.Fatalf("retired converter created sidecars: %v %v", entries, err)
|
||||
}
|
||||
}
|
||||
@@ -170,6 +170,8 @@ type Publisher struct {
|
||||
leaseMu sync.Mutex
|
||||
leaseViews map[string]*leaseView
|
||||
leaseClosing bool
|
||||
leaseStats leaseCounters // guarded by leaseMu
|
||||
leaseLog func(string) // renewal-path notes; nil = log.Print (test seam)
|
||||
extWG sync.WaitGroup
|
||||
extendFailures map[string]int // guarded by mu
|
||||
|
||||
|
||||
@@ -141,36 +141,70 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
|
||||
return persist()
|
||||
}
|
||||
|
||||
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
func validateWorkspaceMoveRequest(req WorkspaceMoveRequest) error {
|
||||
// v1 moves a replica between hosts without changing its logical slot.
|
||||
// Refuse before locking or persisting a reservation/authority epoch.
|
||||
if req.ExpectedReplicaID != req.TargetReplicaID {
|
||||
return WorkspaceMoveRecord{}, fmt.Errorf("workspace move: v1 requires the same logical replica id")
|
||||
return fmt.Errorf("workspace move: v1 requires the same logical replica id")
|
||||
}
|
||||
if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || req.ExpectedHost == req.TargetHost || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" ||
|
||||
req.TargetDataAddr == "" || req.TargetCtrlAddr == "" || (req.Kind != "clean" && req.Kind != "forced") || req.Force != (req.Kind == "forced") {
|
||||
return WorkspaceMoveRecord{}, fmt.Errorf("workspace move: invalid request")
|
||||
return fmt.Errorf("workspace move: invalid request")
|
||||
}
|
||||
p.mu.Lock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// issuedWorkspaceReplayLocked finds req's journal record: replay is true when
|
||||
// req repeats an issued move (same request id, same validated body); an id
|
||||
// reused with a different body is an error. Caller holds p.mu.
|
||||
func (p *Publisher) issuedWorkspaceReplayLocked(req WorkspaceMoveRequest) (WorkspaceMoveRecord, bool, error) {
|
||||
if s := p.workspace[req.VolumeID]; s != nil {
|
||||
for _, r := range s.Moves {
|
||||
if r.RequestID == req.RequestID {
|
||||
if !sameWorkspaceRequest(r, req) {
|
||||
p.mu.Unlock()
|
||||
return WorkspaceMoveRecord{}, fmt.Errorf("workspace move request id reused")
|
||||
return WorkspaceMoveRecord{}, false, fmt.Errorf("workspace move request id reused")
|
||||
}
|
||||
if r.Issued {
|
||||
p.mu.Unlock()
|
||||
return r, nil
|
||||
return r, true, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return WorkspaceMoveRecord{}, false, nil
|
||||
}
|
||||
|
||||
// IssuedWorkspaceMove reports whether req is an exact replay of an issued
|
||||
// move, with the same validation MoveWorkspace applies before its replay. It
|
||||
// only reads: MoveWorkspace of the same request returns that record and
|
||||
// mints nothing. Admission rules for new work (strict journal isolation) let
|
||||
// such a replay through: they refuse new decisions, never an issued one.
|
||||
func (p *Publisher) IssuedWorkspaceMove(req WorkspaceMoveRequest) bool {
|
||||
if validateWorkspaceMoveRequest(req) != nil {
|
||||
return false
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
_, replay, err := p.issuedWorkspaceReplayLocked(req)
|
||||
return replay && err == nil
|
||||
}
|
||||
|
||||
func (p *Publisher) MoveWorkspace(ctx context.Context, req WorkspaceMoveRequest, head WorkspaceHead) (WorkspaceMoveRecord, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
if err := validateWorkspaceMoveRequest(req); err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
p.mu.Lock()
|
||||
r, replay, err := p.issuedWorkspaceReplayLocked(req)
|
||||
p.mu.Unlock()
|
||||
err := p.applyWithWorkspaceMove(AssignmentAsk{VolumeID: req.VolumeID, ReplicaID: req.TargetReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign}, &workspaceGrant{req, head})
|
||||
if err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
if replay {
|
||||
return r, nil
|
||||
}
|
||||
err = p.applyWithWorkspaceMove(AssignmentAsk{VolumeID: req.VolumeID, ReplicaID: req.TargetReplicaID, DataAddr: req.TargetDataAddr, CtrlAddr: req.TargetCtrlAddr, Intent: IntentReassign}, &workspaceGrant{req, head})
|
||||
if err != nil {
|
||||
return WorkspaceMoveRecord{}, err
|
||||
}
|
||||
@@ -239,25 +273,37 @@ func (p *Publisher) workspaceLineLocked(volume string) (subKey, assignmentState,
|
||||
}
|
||||
|
||||
func (p *Publisher) persistWorkspaceLocked(volume string, s *WorkspaceState) error {
|
||||
_, _, err := p.persistWorkspaceTimedLocked(volume, s)
|
||||
return err
|
||||
}
|
||||
|
||||
// persistWorkspaceTimedLocked is persistWorkspaceLocked that also reports how
|
||||
// long the durable store write itself took (write) and whether it was
|
||||
// attempted (wrote is false when it refused before writing). Caller holds
|
||||
// p.mu.
|
||||
func (p *Publisher) persistWorkspaceTimedLocked(volume string, s *WorkspaceState) (write time.Duration, wrote bool, err error) {
|
||||
if p.store == nil || p.workspaceUncertain[volume] {
|
||||
return fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
return 0, false, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
_, line, ok := p.workspaceLineLocked(volume)
|
||||
if !ok {
|
||||
return fmt.Errorf("workspace authority missing")
|
||||
return 0, false, fmt.Errorf("workspace authority missing")
|
||||
}
|
||||
i := line.info
|
||||
record := DurableRecord{VolumeID: volume, ReplicaID: i.ReplicaID, Epoch: i.Epoch, EndpointVersion: i.EndpointVersion, DataAddr: i.DataAddr, CtrlAddr: i.CtrlAddr,
|
||||
WriteSeq: p.writeSeqByVolume[volume] + 1, Workspace: cloneWorkspace(s)}
|
||||
if err := p.store.Put(record); err != nil {
|
||||
start := time.Now()
|
||||
err = p.store.Put(record)
|
||||
write = time.Since(start)
|
||||
if err != nil {
|
||||
p.workspaceUncertain[volume] = true
|
||||
p.refreshLeaseViewLocked(volume)
|
||||
return err
|
||||
return write, true, err
|
||||
}
|
||||
p.writeSeqByVolume[volume] = record.WriteSeq
|
||||
p.workspace[volume] = cloneWorkspace(s)
|
||||
p.refreshLeaseViewLocked(volume)
|
||||
return nil
|
||||
return write, true, nil
|
||||
}
|
||||
|
||||
type workspaceGrant struct {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Lease headroom observability. Headroom is the durable horizon minus now:
|
||||
// how long the published lease still covers a holder if no extension lands.
|
||||
// Extensions start below 1.25 TTL of headroom and grants are clamped below
|
||||
// 1 TTL, so a lagging authority store shows first as an extension in flight
|
||||
// with headroom under 1.125 TTL, and only later as clamps.
|
||||
//
|
||||
// The extension store write latency (LeaseStats.ExtensionWrite*) is
|
||||
// completed-write telemetry: a write is sampled when its Put returns, so a
|
||||
// write that is still blocked shows up only after it returns, possibly after
|
||||
// headroom is already lost; it is not an early warning by itself. The alarm
|
||||
// is sampled at renewals, never by a timer: it fires at the latest
|
||||
// together with the first clamped grant of a streak (logged before the clamp
|
||||
// line), and earlier only if a renewal lands in the 1-1.125 TTL band while an
|
||||
// extension is pending. A renewer slower than that band may see both on one
|
||||
// renewal.
|
||||
|
||||
// LeaseStats is a snapshot of the workspace lease renewal counters.
|
||||
type LeaseStats struct {
|
||||
// HeadroomAlarms counts alarm streaks, once per volume per streak: a
|
||||
// renewal that found headroom below 1.125 TTL with an extension in
|
||||
// flight, or the first clamped grant (headroom below 1 TTL) of a streak.
|
||||
HeadroomAlarms uint64
|
||||
// ClampsTotal counts grants clamped to the durable horizon.
|
||||
ClampsTotal uint64
|
||||
// ClampsLastMinute counts clamped grants in the last minute.
|
||||
ClampsLastMinute uint64
|
||||
// MinHeadroom is the smallest headroom observed at a grant; valid only
|
||||
// when MinHeadroomObserved.
|
||||
MinHeadroom time.Duration
|
||||
MinHeadroomObserved bool
|
||||
// ExtensionWriteLast is the duration of the latest lease extension's
|
||||
// durable store write (the write alone, failed or not); valid only when
|
||||
// ExtensionWriteObserved. Completed-write telemetry: recorded when the
|
||||
// Put returns, so a write still blocked is not visible here yet.
|
||||
ExtensionWriteLast time.Duration
|
||||
ExtensionWriteObserved bool
|
||||
// ExtensionWriteMaxLastMinute is the slowest extension write in the last
|
||||
// minute (rolling, one bucket per second like ClampsLastMinute); valid
|
||||
// only when ExtensionWriteInLastMinute.
|
||||
ExtensionWriteMaxLastMinute time.Duration
|
||||
ExtensionWriteInLastMinute bool
|
||||
}
|
||||
|
||||
const clampBuckets = 60 // one per second of the last minute
|
||||
|
||||
// leaseCounters is guarded by Publisher.leaseMu.
|
||||
type leaseCounters struct {
|
||||
alarms uint64
|
||||
clamps uint64
|
||||
buckets [clampBuckets]struct{ sec, n int64 } // clamps by unix second
|
||||
minHeadroom int64
|
||||
minObserved bool
|
||||
// Extension store writes: the latest, and the slowest per second of the
|
||||
// last minute.
|
||||
writeLast int64
|
||||
writeObserved bool
|
||||
writeBuckets [clampBuckets]struct {
|
||||
sec, max int64
|
||||
set bool
|
||||
}
|
||||
// Per-minute summary, emitted by the first renewal attempt after the
|
||||
// window, granted or refused: no goroutine or timer of its own. With no
|
||||
// renewal attempts at all nothing is emitted; the counters above (the
|
||||
// status endpoint) still show the clamps.
|
||||
windowStart time.Time
|
||||
windowClamps uint64
|
||||
windowMin int64
|
||||
windowMinSet bool
|
||||
}
|
||||
|
||||
func (c *leaseCounters) clampsSince(now time.Time) uint64 {
|
||||
cut := now.Unix() - clampBuckets
|
||||
var n uint64
|
||||
for _, b := range c.buckets {
|
||||
if b.n > 0 && b.sec > cut && b.sec <= now.Unix() {
|
||||
n += uint64(b.n)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (c *leaseCounters) recordClamp(now time.Time) {
|
||||
c.clamps++
|
||||
c.windowClamps++
|
||||
sec := now.Unix()
|
||||
b := &c.buckets[uint64(sec)%clampBuckets]
|
||||
if b.sec != sec {
|
||||
b.sec, b.n = sec, 0
|
||||
}
|
||||
b.n++
|
||||
}
|
||||
|
||||
// recordExtensionWrite records the duration of one extension store write
|
||||
// that returned at now.
|
||||
func (c *leaseCounters) recordExtensionWrite(now time.Time, d time.Duration) {
|
||||
c.writeLast, c.writeObserved = int64(d), true
|
||||
sec := now.Unix()
|
||||
b := &c.writeBuckets[uint64(sec)%clampBuckets]
|
||||
if !b.set || b.sec != sec {
|
||||
b.sec, b.max, b.set = sec, int64(d), true
|
||||
} else if int64(d) > b.max {
|
||||
b.max = int64(d)
|
||||
}
|
||||
}
|
||||
|
||||
// extensionWriteMaxSince returns the slowest extension write of the last
|
||||
// minute, and whether there was one.
|
||||
func (c *leaseCounters) extensionWriteMaxSince(now time.Time) (int64, bool) {
|
||||
cut := now.Unix() - clampBuckets
|
||||
max, ok := int64(0), false
|
||||
for _, b := range c.writeBuckets {
|
||||
if b.set && b.sec > cut && b.sec <= now.Unix() && (!ok || b.max > max) {
|
||||
max, ok = b.max, true
|
||||
}
|
||||
}
|
||||
return max, ok
|
||||
}
|
||||
|
||||
// summaryDue closes a window that has lasted a minute and returns its summary
|
||||
// note when it had clamps. Every renewal attempt calls it, granted or refused,
|
||||
// so a stall through expiry (only refusals after the clamps) is still
|
||||
// summarized. It opens no window: the first grant does.
|
||||
func (c *leaseCounters) summaryDue(now time.Time) string {
|
||||
if c.windowStart.IsZero() || now.Sub(c.windowStart) < time.Minute {
|
||||
return ""
|
||||
}
|
||||
var note string
|
||||
if c.windowClamps > 0 {
|
||||
note = fmt.Sprintf("workspace lease: %d clamped grants in the last %s (total %d, min headroom %s); the authority store is lagging",
|
||||
c.windowClamps, now.Sub(c.windowStart).Round(time.Second), c.clamps, time.Duration(c.windowMin).Round(time.Millisecond))
|
||||
}
|
||||
c.windowStart, c.windowClamps, c.windowMinSet = now, 0, false
|
||||
return note
|
||||
}
|
||||
|
||||
// observeGrant records the headroom of a grant and returns a per-minute
|
||||
// summary note when a window with clamps has just ended. Call it before
|
||||
// recordClamp of the same grant (it may open a new window).
|
||||
func (c *leaseCounters) observeGrant(now time.Time, headroom int64) string {
|
||||
if c.windowStart.IsZero() {
|
||||
c.windowStart = now
|
||||
}
|
||||
note := c.summaryDue(now)
|
||||
if !c.windowMinSet || headroom < c.windowMin {
|
||||
c.windowMin, c.windowMinSet = headroom, true
|
||||
}
|
||||
if !c.minObserved || headroom < c.minHeadroom {
|
||||
c.minHeadroom, c.minObserved = headroom, true
|
||||
}
|
||||
return note
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStats returns a snapshot of the lease renewal counters.
|
||||
func (p *Publisher) WorkspaceLeaseStats() LeaseStats {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
c := &p.leaseStats
|
||||
now := p.workspaceNow()
|
||||
writeMax, writeRecent := c.extensionWriteMaxSince(now)
|
||||
return LeaseStats{
|
||||
HeadroomAlarms: c.alarms,
|
||||
ClampsTotal: c.clamps,
|
||||
ClampsLastMinute: c.clampsSince(now),
|
||||
MinHeadroom: time.Duration(c.minHeadroom),
|
||||
MinHeadroomObserved: c.minObserved,
|
||||
ExtensionWriteLast: time.Duration(c.writeLast),
|
||||
ExtensionWriteObserved: c.writeObserved,
|
||||
ExtensionWriteMaxLastMinute: time.Duration(writeMax),
|
||||
ExtensionWriteInLastMinute: writeRecent,
|
||||
}
|
||||
}
|
||||
|
||||
// headroomAlarmLocked runs the alarm state machine of one renewal, before the
|
||||
// renewal clamps (a grant clamps exactly when headroom < 1 TTL). Caller holds
|
||||
// leaseMu. It returns a note to log after the unlock, before the clamp note.
|
||||
//
|
||||
// state | condition at a renewal | next | effect
|
||||
// -----------+-----------------------------------------------+------------+------------------
|
||||
// quiet | extending && headroom < 1.125 TTL | alarmed | count + log once
|
||||
// quiet | headroom < 1 TTL (this grant clamps) | alarmed | count + log once
|
||||
// quiet | otherwise | quiet | -
|
||||
// alarmed | headroom >= 1.25 TTL | quiet | streak ends
|
||||
// alarmed | !extending && headroom >= 1.125 TTL | quiet | streak ends
|
||||
// alarmed | otherwise | alarmed | -
|
||||
//
|
||||
// A clamp streak (headroom < 1 TTL) therefore never starts without an alarm
|
||||
// on the same or an earlier renewal, and never re-alarms while it lasts.
|
||||
func (p *Publisher) headroomAlarmLocked(volume string, lv *leaseView, headroom int64) string {
|
||||
ttl := int64(p.workspaceTTL)
|
||||
low, high := ttl+ttl/8, ttl+ttl/4
|
||||
if lv.alarmed {
|
||||
if headroom >= high || (!lv.extending && headroom >= low) {
|
||||
lv.alarmed = false
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var why string
|
||||
switch {
|
||||
case lv.extending && headroom < low:
|
||||
why = "below 1.125 TTL while the extension write is pending"
|
||||
case headroom < ttl:
|
||||
why = "below 1 TTL: this grant is the first clamped to the durable horizon"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
lv.alarmed = true
|
||||
p.leaseStats.alarms++
|
||||
return fmt.Sprintf("workspace lease: volume=%s headroom %s %s; the authority store is lagging",
|
||||
volume, time.Duration(headroom).Round(time.Millisecond), why)
|
||||
}
|
||||
|
||||
func (p *Publisher) logLease(note string) {
|
||||
if note == "" {
|
||||
return
|
||||
}
|
||||
if p.leaseLog != nil {
|
||||
p.leaseLog(note)
|
||||
return
|
||||
}
|
||||
log.Print(note)
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package authority
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// blockedLeaseStore holds every armed workspace-lease write until release
|
||||
// closes, standing in for an authority journal stuck behind other fsyncs.
|
||||
type blockedLeaseStore struct {
|
||||
AuthorityStore
|
||||
armed atomic.Bool
|
||||
entered chan struct{}
|
||||
once sync.Once
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (s *blockedLeaseStore) Put(r DurableRecord) error {
|
||||
if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
s.once.Do(func() { close(s.entered) })
|
||||
<-s.release
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
type noteLog struct {
|
||||
mu sync.Mutex
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (l *noteLog) add(s string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.lines = append(l.lines, s)
|
||||
}
|
||||
|
||||
func (l *noteLog) snapshot() []string {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return append([]string(nil), l.lines...)
|
||||
}
|
||||
|
||||
func indexOf(lines []string, sub string) int {
|
||||
for i, s := range lines {
|
||||
if strings.Contains(s, sub) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// With the authority store's lease write stuck, renewals at an advancing
|
||||
// clock must raise the headroom alarm on a renewal strictly before the first
|
||||
// clamped grant, then count clamps (total and last minute) and the minimum
|
||||
// headroom, and log a per-minute summary once a minute with clamps ends.
|
||||
func TestWorkspaceLeaseHeadroomAlarmPrecedesFirstClamp(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}
|
||||
var nowNS atomic.Int64
|
||||
t0 := time.Unix(1000, 0)
|
||||
nowNS.Store(t0.UnixNano())
|
||||
at := func(d time.Duration) { nowNS.Store(t0.Add(d).UnixNano()) }
|
||||
const ttl = 30 * time.Second
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
notes := ¬eLog{}
|
||||
p.leaseLog = notes.add
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(store.release) }) }
|
||||
t.Cleanup(p.CloseWorkspaceExtenders) // runs after release (LIFO)
|
||||
t.Cleanup(release)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// First grant: synchronous write, horizon t0+45s.
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s := p.WorkspaceLeaseStats(); s.HeadroomAlarms != 0 || s.ClampsTotal != 0 || s.MinHeadroomObserved {
|
||||
t.Fatalf("stats after the first grant: %+v", s)
|
||||
}
|
||||
store.armed.Store(true)
|
||||
renew := func(d time.Duration) (WorkspaceLease, LeaseStats) {
|
||||
t.Helper()
|
||||
at(d)
|
||||
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("renewal at +%s: %v", d, err)
|
||||
}
|
||||
return l, p.WorkspaceLeaseStats()
|
||||
}
|
||||
|
||||
// +10s: headroom 35s < 1.25 TTL starts the extension, which blocks.
|
||||
_, s := renew(10 * time.Second)
|
||||
if s.HeadroomAlarms != 0 || s.ClampsTotal != 0 {
|
||||
t.Fatalf("+10s (headroom 35s, extension just started): %+v", s)
|
||||
}
|
||||
select {
|
||||
case <-store.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the extension write never reached the store")
|
||||
}
|
||||
// +12s: headroom 33s < 33.75s (1.125 TTL), extension pending: alarm, no clamp.
|
||||
l, s := renew(12 * time.Second)
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 0 {
|
||||
t.Fatalf("+12s (headroom 33s, extension pending): want 1 alarm and 0 clamps, got %+v", s)
|
||||
}
|
||||
if want := t0.Add(12*time.Second + ttl).UnixNano(); l.ExpiresAtNS != want {
|
||||
t.Fatalf("+12s grant %d, want unclamped %d", l.ExpiresAtNS, want)
|
||||
}
|
||||
// +13s: same streak, no second alarm.
|
||||
if _, s = renew(13 * time.Second); s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+13s: alarm repeated within one streak: %+v", s)
|
||||
}
|
||||
// +20s, +25s: headroom 25s, 20s < TTL: clamped grants.
|
||||
l, s = renew(20 * time.Second)
|
||||
if want := t0.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want {
|
||||
t.Fatalf("+20s grant %d, want clamped to horizon %d", l.ExpiresAtNS, want)
|
||||
}
|
||||
if s.ClampsTotal != 1 || s.ClampsLastMinute != 1 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+20s: %+v", s)
|
||||
}
|
||||
_, s = renew(25 * time.Second)
|
||||
if s.ClampsTotal != 2 || s.ClampsLastMinute != 2 || !s.MinHeadroomObserved || s.MinHeadroom != 20*time.Second {
|
||||
t.Fatalf("+25s: want 2 clamps, min headroom 20s; got %+v", s)
|
||||
}
|
||||
lines := notes.snapshot()
|
||||
alarmAt, clampAt := indexOf(lines, "below 1.125 TTL while the extension write is pending"), indexOf(lines, "are clamped to the durable horizon")
|
||||
if alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt {
|
||||
t.Fatalf("alarm line must precede the first clamp line: alarm=%d clamp=%d\n%s", alarmAt, clampAt, strings.Join(lines, "\n"))
|
||||
}
|
||||
if !strings.Contains(lines[alarmAt], "volume=v headroom 33s") {
|
||||
t.Fatalf("alarm line: %q", lines[alarmAt])
|
||||
}
|
||||
|
||||
// The store recovers: the extension lands (horizon +10s+45s = +55s).
|
||||
release()
|
||||
waitExtenders(t, p)
|
||||
// +26s: horizon +55s, headroom 29s < TTL: one more clamp; a new extension
|
||||
// starts (trigger +26s, horizon +71s) and lands at once.
|
||||
_, s = renew(26 * time.Second)
|
||||
waitExtenders(t, p)
|
||||
if s.ClampsTotal != 3 {
|
||||
t.Fatalf("+26s: %+v", s)
|
||||
}
|
||||
// +27s: headroom 44s >= 1.25 TTL: unclamped, the alarm streak ends.
|
||||
if _, s = renew(27 * time.Second); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+27s: %+v", s)
|
||||
}
|
||||
// Healthy renewals keep the lease ahead: no clamps, no alarms.
|
||||
for _, d := range []time.Duration{40 * time.Second, 55 * time.Second} {
|
||||
if _, s = renew(d); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 {
|
||||
t.Fatalf("+%s: %+v", d, s)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
}
|
||||
if indexOf(notes.snapshot(), "clamped grants in the last") >= 0 {
|
||||
t.Fatal("summary logged before the minute ended")
|
||||
}
|
||||
// +70s: a minute after the window's first renewal (+10s): the window with
|
||||
// clamps ends and its summary is logged by this renewal.
|
||||
if _, s = renew(70 * time.Second); s.ClampsTotal != 3 {
|
||||
t.Fatalf("+70s: %+v", s)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
lines = notes.snapshot()
|
||||
if i := indexOf(lines, "workspace lease: 3 clamped grants in the last 1m0s (total 3, min headroom 20s)"); i < 0 {
|
||||
t.Fatalf("no per-minute summary:\n%s", strings.Join(lines, "\n"))
|
||||
}
|
||||
// The +20s/+25s/+26s clamps are older than a minute at +87s.
|
||||
at(87 * time.Second)
|
||||
if s = p.WorkspaceLeaseStats(); s.ClampsLastMinute != 0 || s.ClampsTotal != 3 || s.MinHeadroom != 20*time.Second {
|
||||
t.Fatalf("+87s: clamps should age out of the last minute: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// stalledLeaseRig is a publisher whose lease writes, once armed, block until
|
||||
// release, with a settable clock (t0 = first grant, TTL 30s, horizon +45s).
|
||||
type stalledLeaseRig struct {
|
||||
p *Publisher
|
||||
store *blockedLeaseStore
|
||||
notes *noteLog
|
||||
t0 time.Time
|
||||
nowNS atomic.Int64
|
||||
release func()
|
||||
}
|
||||
|
||||
func newStalledLeaseRig(t *testing.T) *stalledLeaseRig {
|
||||
t.Helper()
|
||||
disk, _ := newTempStore(t)
|
||||
r := &stalledLeaseRig{store: &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}, notes: ¬eLog{}, t0: time.Unix(1000, 0)}
|
||||
r.nowNS.Store(r.t0.UnixNano())
|
||||
r.p = NewPublisher(nil, WithStore(r.store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, r.nowNS.Load()) }))
|
||||
r.p.leaseLog = r.notes.add
|
||||
var once sync.Once
|
||||
r.release = func() { once.Do(func() { close(r.store.release) }) }
|
||||
t.Cleanup(r.p.CloseWorkspaceExtenders) // runs after release (LIFO)
|
||||
t.Cleanup(r.release)
|
||||
if err := r.p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.store.armed.Store(true)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *stalledLeaseRig) renew(d time.Duration) (WorkspaceLease, LeaseStats, error) {
|
||||
r.nowNS.Store(r.t0.Add(d).UnixNano())
|
||||
l, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
|
||||
return l, r.p.WorkspaceLeaseStats(), err
|
||||
}
|
||||
|
||||
func (r *stalledLeaseRig) waitEntered(t *testing.T) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-r.store.entered:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("the extension write never reached the store")
|
||||
}
|
||||
}
|
||||
|
||||
// assertAlarmBeforeClamp checks exactly one alarm line containing want, logged
|
||||
// before the first clamp line.
|
||||
func assertAlarmBeforeClamp(t *testing.T, lines []string, want string) {
|
||||
t.Helper()
|
||||
alarms := 0
|
||||
for _, s := range lines {
|
||||
if strings.Contains(s, "the authority store is lagging") && strings.Contains(s, "headroom") && strings.Contains(s, "volume=v") {
|
||||
alarms++
|
||||
}
|
||||
}
|
||||
alarmAt, clampAt := indexOf(lines, want), indexOf(lines, "are clamped to the durable horizon")
|
||||
if alarms != 1 || alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt {
|
||||
t.Fatalf("want one alarm %q before the first clamp line: alarms=%d alarm=%d clamp=%d\n%s", want, alarms, alarmAt, clampAt, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// Skipped band: the extension starts and stalls at +10s, and the next renewal
|
||||
// (+20s) lands already clamped, never in the 1-1.125 TTL band. The alarm fires
|
||||
// on that same renewal, logged before the clamp line, and counts once.
|
||||
func TestWorkspaceLeaseAlarmWhenTheBandIsSkipped(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
if _, s, err := r.renew(10 * time.Second); err != nil || s.HeadroomAlarms != 0 {
|
||||
t.Fatalf("+10s: %+v %v", s, err)
|
||||
}
|
||||
r.waitEntered(t)
|
||||
l, s, err := r.renew(20 * time.Second)
|
||||
if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() {
|
||||
t.Fatalf("+20s: want a grant clamped to the horizon, got %+v %v", l, err)
|
||||
}
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 {
|
||||
t.Fatalf("+20s: want 1 alarm and 1 clamp, got %+v", s)
|
||||
}
|
||||
if _, s, err = r.renew(25 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+25s: alarm repeated or clamp missed: %+v %v", s, err)
|
||||
}
|
||||
assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 25s below 1.125 TTL while the extension write is pending")
|
||||
}
|
||||
|
||||
// First renewal below one TTL: no extension has started yet (the renewal
|
||||
// itself starts it), and the grant clamps. The alarm still fires with that
|
||||
// first clamp, before the clamp line, and does not repeat in the streak.
|
||||
func TestWorkspaceLeaseAlarmWithAFirstRenewalBelowTTL(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
l, s, err := r.renew(16 * time.Second)
|
||||
if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() {
|
||||
t.Fatalf("+16s: want a grant clamped to the horizon, got %+v %v", l, err)
|
||||
}
|
||||
if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 {
|
||||
t.Fatalf("+16s: want 1 alarm with the first clamp, got %+v", s)
|
||||
}
|
||||
r.waitEntered(t) // the renewal started the extension; it stalls
|
||||
if _, s, err = r.renew(18 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+18s: %+v %v", s, err)
|
||||
}
|
||||
assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 29s below 1 TTL: this grant is the first clamped to the durable horizon")
|
||||
}
|
||||
|
||||
// Stall through expiry: after the clamps, every renewal is refused (no host
|
||||
// validity, then expired) and none is granted again. The per-minute summary
|
||||
// is still logged, by the first refused renewal after the minute, once.
|
||||
func TestWorkspaceLeaseSummaryWithoutALaterGrant(t *testing.T) {
|
||||
r := newStalledLeaseRig(t)
|
||||
if _, _, err := r.renew(10 * time.Second); err != nil { // opens the window, starts the extension
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.waitEntered(t)
|
||||
for _, d := range []time.Duration{20 * time.Second, 25 * time.Second} {
|
||||
if _, _, err := r.renew(d); err != nil {
|
||||
t.Fatalf("+%s: %v", d, err)
|
||||
}
|
||||
}
|
||||
for _, d := range []time.Duration{36 * time.Second, 46 * time.Second, 60 * time.Second} {
|
||||
if l, _, err := r.renew(d); err == nil {
|
||||
t.Fatalf("+%s: granted %+v through a stalled store past the horizon", d, l)
|
||||
}
|
||||
}
|
||||
if indexOf(r.notes.snapshot(), "clamped grants in the last") >= 0 {
|
||||
t.Fatal("summary logged before the minute ended")
|
||||
}
|
||||
if _, s, err := r.renew(71 * time.Second); err == nil || s.ClampsTotal != 2 {
|
||||
t.Fatalf("+71s: %+v %v, want a refusal", s, err)
|
||||
}
|
||||
if _, _, err := r.renew(72 * time.Second); err == nil {
|
||||
t.Fatal("+72s granted")
|
||||
}
|
||||
lines := r.notes.snapshot()
|
||||
want := "workspace lease: 2 clamped grants in the last 1m1s (total 2, min headroom 20s)"
|
||||
n := 0
|
||||
for _, s := range lines {
|
||||
if strings.Contains(s, "clamped grants in the last") {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if indexOf(lines, want) < 0 || n != 1 {
|
||||
t.Fatalf("want the summary %q once from refused renewals, got %d summaries:\n%s", want, n, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
// delayedLeaseStore makes every lease write take delay (when set): a slow
|
||||
// authority journal that still completes.
|
||||
type delayedLeaseStore struct {
|
||||
AuthorityStore
|
||||
delay atomic.Int64
|
||||
}
|
||||
|
||||
func (s *delayedLeaseStore) Put(r DurableRecord) error {
|
||||
if d := time.Duration(s.delay.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil {
|
||||
time.Sleep(d)
|
||||
}
|
||||
return s.AuthorityStore.Put(r)
|
||||
}
|
||||
|
||||
// The extension's store write latency is recorded at every extension write:
|
||||
// the latest one, and the slowest of the last minute (rolling per second),
|
||||
// which ages out a minute after the write. The first grant's write is not an
|
||||
// extension and records nothing.
|
||||
func TestWorkspaceLeaseExtensionWriteLatency(t *testing.T) {
|
||||
disk, _ := newTempStore(t)
|
||||
store := &delayedLeaseStore{AuthorityStore: disk}
|
||||
var nowNS atomic.Int64
|
||||
t0 := time.Unix(1000, 0)
|
||||
nowNS.Store(t0.UnixNano())
|
||||
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) }))
|
||||
p.leaseLog = func(string) {}
|
||||
t.Cleanup(p.CloseWorkspaceExtenders)
|
||||
if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
renew := func(d time.Duration) LeaseStats {
|
||||
t.Helper()
|
||||
nowNS.Store(t0.Add(d).UnixNano())
|
||||
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
|
||||
t.Fatalf("renewal at +%s: %v", d, err)
|
||||
}
|
||||
waitExtenders(t, p)
|
||||
return p.WorkspaceLeaseStats()
|
||||
}
|
||||
if s := renew(0); s.ExtensionWriteObserved || s.ExtensionWriteInLastMinute { // first grant
|
||||
t.Fatalf("the first grant recorded an extension write: %+v", s)
|
||||
}
|
||||
const slow = 300 * time.Millisecond
|
||||
store.delay.Store(int64(slow))
|
||||
// +10s: headroom 35s < 1.25 TTL starts an extension; its write takes 300 ms.
|
||||
s := renew(10 * time.Second)
|
||||
if !s.ExtensionWriteObserved || s.ExtensionWriteLast < slow || s.ExtensionWriteLast > slow+time.Second {
|
||||
t.Fatalf("+10s: want the last extension write ~%s, got %+v", slow, s)
|
||||
}
|
||||
if !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute < slow {
|
||||
t.Fatalf("+10s: want max >= %s in the last minute, got %+v", slow, s)
|
||||
}
|
||||
store.delay.Store(0)
|
||||
// +20s: horizon +55s, headroom 35s: a fast extension write.
|
||||
s = renew(20 * time.Second)
|
||||
if s.ExtensionWriteLast >= slow || s.ExtensionWriteMaxLastMinute < slow {
|
||||
t.Fatalf("+20s: want a fast last write and the 300 ms max kept, got %+v", s)
|
||||
}
|
||||
// +71s: the +10s write is older than a minute; the +20s one is not.
|
||||
nowNS.Store(t0.Add(71 * time.Second).UnixNano())
|
||||
if s = p.WorkspaceLeaseStats(); !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute >= slow || s.ExtensionWriteLast >= slow {
|
||||
t.Fatalf("+71s: the 300 ms max must age out, got %+v", s)
|
||||
}
|
||||
// +81s: no write in the last minute; the last write stays reported.
|
||||
nowNS.Store(t0.Add(81 * time.Second).UnixNano())
|
||||
if s = p.WorkspaceLeaseStats(); s.ExtensionWriteInLastMinute || !s.ExtensionWriteObserved {
|
||||
t.Fatalf("+81s: want no write in the last minute, last still observed; got %+v", s)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ type leaseDerived struct {
|
||||
bound bool // an authority line exists for the volume
|
||||
replica string
|
||||
epoch uint64
|
||||
issuedHost string // NewHost of the issued move that minted the line; "" if none
|
||||
leasePresent bool
|
||||
revoking bool
|
||||
movePending bool // the last workspace move is reserved, not issued
|
||||
@@ -33,6 +34,7 @@ type leaseView struct {
|
||||
deadline time.Time
|
||||
extending bool
|
||||
clamped bool // a renewal was clamped below now+TTL; logged once per streak
|
||||
alarmed bool // a headroom alarm streak is open (headroomAlarmLocked)
|
||||
}
|
||||
|
||||
// deriveLeaseLocked computes the derived lease view from published state.
|
||||
@@ -44,6 +46,11 @@ func (p *Publisher) deriveLeaseLocked(volume string) leaseDerived {
|
||||
}
|
||||
if s := p.workspace[volume]; s != nil {
|
||||
d.movePending = len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued
|
||||
for _, r := range s.Moves {
|
||||
if d.bound && r.Issued && r.NewReplicaID == d.replica && r.NewEpoch == d.epoch {
|
||||
d.issuedHost = r.NewHost
|
||||
}
|
||||
}
|
||||
if s.Lease != nil {
|
||||
d.leasePresent, d.revoking, d.horizon, d.lease = true, s.Lease.Revoking, s.Lease.ExpiresAtNS, *s.Lease
|
||||
d.maxSkewNS = int64(p.workspaceSkew(s.Lease))
|
||||
@@ -140,6 +147,33 @@ func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) {
|
||||
return l, true
|
||||
}
|
||||
|
||||
// PublishedLine is a volume's committed authority line as the lease view
|
||||
// publishes it.
|
||||
type PublishedLine struct {
|
||||
ReplicaID string
|
||||
Epoch uint64
|
||||
// IssuedHost is the target host of the issued move that minted this line;
|
||||
// "" when no issued move did (a placement or static topology line).
|
||||
IssuedHost string
|
||||
}
|
||||
|
||||
// PublishedAuthorityLines returns the committed authority line of every
|
||||
// volume that has one. It reads the lease views under the leaf leaseMu only:
|
||||
// it never waits on p.mu, which writers hold across store writes, and it
|
||||
// sees only state those writers already published (a reserved, unissued
|
||||
// move never shows here).
|
||||
func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
|
||||
p.leaseMu.Lock()
|
||||
defer p.leaseMu.Unlock()
|
||||
out := make(map[string]PublishedLine, len(p.leaseViews))
|
||||
for volume, lv := range p.leaseViews {
|
||||
if lv.d.bound {
|
||||
out[volume] = PublishedLine{ReplicaID: lv.d.replica, Epoch: lv.d.epoch, IssuedHost: lv.d.issuedHost}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// RenewWorkspaceLease answers a live holder from memory: it takes only the
|
||||
// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant
|
||||
// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu
|
||||
@@ -151,35 +185,47 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
}
|
||||
p.leaseMu.Lock()
|
||||
now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it
|
||||
// unlock releases leaseMu on a path that grants nothing and logs a due
|
||||
// per-minute summary after the unlock: every renewal attempt, granted or
|
||||
// refused, may close the window (a stall through expiry refuses only).
|
||||
unlock := func() {
|
||||
summary := p.leaseStats.summaryDue(now)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(summary)
|
||||
}
|
||||
lv := p.leaseViews[volume]
|
||||
if lv == nil || !lv.d.bound || lv.d.replica != holder || lv.d.epoch != epoch {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
|
||||
}
|
||||
if lv.d.movePending {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: move pending")
|
||||
}
|
||||
if !lv.d.leasePresent {
|
||||
p.leaseMu.Unlock() // never re-enter p.mu while holding the leaf
|
||||
unlock() // never re-enter p.mu while holding the leaf
|
||||
return p.firstWorkspaceGrant(ctx, volume, holder, epoch)
|
||||
}
|
||||
if lv.d.revoking { // tell the host to drain; never extend
|
||||
l := lv.d.lease
|
||||
l.ExpiresAtNS = lv.replyExpiryNS()
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return l, nil
|
||||
}
|
||||
if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking")
|
||||
}
|
||||
// Where the synchronous write used to refuse (persistWorkspaceLocked):
|
||||
// a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001).
|
||||
if lv.d.storeless || lv.d.uncertain {
|
||||
p.leaseMu.Unlock()
|
||||
unlock()
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
|
||||
}
|
||||
// The headroom alarm is sampled here, before the clamp: at the latest it
|
||||
// fires on the first clamped grant of a streak (headroomAlarmLocked).
|
||||
headroom := lv.d.horizon - now.UnixNano()
|
||||
alarm := p.headroomAlarmLocked(volume, lv, headroom)
|
||||
grant := now.Add(p.workspaceTTL).UnixNano()
|
||||
clamped := grant > lv.d.horizon
|
||||
if clamped {
|
||||
@@ -190,12 +236,19 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
// its remaining validity; refuse with an error instead.
|
||||
if grant-lv.d.maxSkewNS/2 <= now.UnixNano() {
|
||||
horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242)
|
||||
summary := p.leaseStats.summaryDue(now)
|
||||
p.leaseMu.Unlock()
|
||||
p.logLease(alarm)
|
||||
p.logLease(summary)
|
||||
return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
if g := time.Unix(0, grant); g.After(lv.deadline) {
|
||||
lv.deadline = g
|
||||
}
|
||||
summary := p.leaseStats.observeGrant(now, headroom)
|
||||
if clamped {
|
||||
p.leaseStats.recordClamp(now)
|
||||
}
|
||||
var note string
|
||||
switch {
|
||||
case clamped && !lv.clamped:
|
||||
@@ -213,9 +266,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
|
||||
}
|
||||
l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}
|
||||
p.leaseMu.Unlock()
|
||||
if note != "" {
|
||||
log.Print(note)
|
||||
}
|
||||
p.logLease(alarm)
|
||||
p.logLease(note)
|
||||
p.logLease(summary)
|
||||
return l, nil
|
||||
}
|
||||
|
||||
@@ -305,9 +358,15 @@ func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, tr
|
||||
return
|
||||
}
|
||||
s.Lease.ExpiresAtNS = h
|
||||
start := time.Now()
|
||||
err := p.persistWorkspaceLocked(volume, s)
|
||||
took := time.Since(start).Round(time.Millisecond)
|
||||
write, wrote, err := p.persistWorkspaceTimedLocked(volume, s)
|
||||
if wrote {
|
||||
// The store write alone, failed or not, recorded when it returns
|
||||
// (completed-write telemetry; a blocked write is not seen until then).
|
||||
p.leaseMu.Lock()
|
||||
p.leaseStats.recordExtensionWrite(p.workspaceNow(), write)
|
||||
p.leaseMu.Unlock()
|
||||
}
|
||||
took := write.Round(time.Millisecond)
|
||||
if err != nil {
|
||||
if p.extendFailures[volume] == 0 {
|
||||
note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v",
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// hangGuard returns a context that only guards against a hung test. It ends
|
||||
// before the test binary's own deadline (go test -timeout), not at a fixed
|
||||
// wall-clock bound, so a loaded host slows these tests down instead of
|
||||
// failing them: what they assert is the order and outcome of the operations.
|
||||
func hangGuard(t *testing.T) context.Context {
|
||||
t.Helper()
|
||||
deadline, ok := t.Deadline()
|
||||
ctx, cancel := context.WithDeadline(context.Background(), hangGuardDeadline(time.Now(), deadline, ok))
|
||||
t.Cleanup(cancel)
|
||||
return ctx
|
||||
}
|
||||
|
||||
const (
|
||||
hangGuardNoDeadline = 10 * time.Minute // no -timeout: still bounded
|
||||
hangGuardMaxMargin = 30 * time.Second
|
||||
)
|
||||
|
||||
// hangGuardDeadline leaves a tenth of the remaining budget (at most 30 s)
|
||||
// before the binary's deadline, so the guard fires first and the test still
|
||||
// has time to report and clean up, however short the budget. An expired
|
||||
// budget gives an expired guard: the test fails at once instead of racing the
|
||||
// binary's own timeout.
|
||||
func hangGuardDeadline(now, deadline time.Time, ok bool) time.Time {
|
||||
if !ok {
|
||||
return now.Add(hangGuardNoDeadline)
|
||||
}
|
||||
remaining := deadline.Sub(now)
|
||||
if remaining <= 0 {
|
||||
return deadline
|
||||
}
|
||||
margin := remaining / 10
|
||||
if margin > hangGuardMaxMargin {
|
||||
margin = hangGuardMaxMargin
|
||||
}
|
||||
return deadline.Add(-margin)
|
||||
}
|
||||
|
||||
func TestHangGuardDeadline(t *testing.T) {
|
||||
now := time.Unix(1700000000, 0)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
deadline time.Time
|
||||
ok bool
|
||||
want time.Time
|
||||
}{
|
||||
{"no deadline", time.Time{}, false, now.Add(hangGuardNoDeadline)},
|
||||
{"long budget", now.Add(time.Hour), true, now.Add(time.Hour - hangGuardMaxMargin)},
|
||||
{"short budget", now.Add(20 * time.Second), true, now.Add(18 * time.Second)},
|
||||
{"nearly expired", now.Add(100 * time.Millisecond), true, now.Add(90 * time.Millisecond)},
|
||||
{"expired", now.Add(-time.Second), true, now.Add(-time.Second)},
|
||||
} {
|
||||
if got := hangGuardDeadline(now, c.deadline, c.ok); !got.Equal(c.want) {
|
||||
t.Errorf("%s: guard at %v, want %v", c.name, got.Sub(now), c.want.Sub(now))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ package durable_test
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -25,7 +26,7 @@ type faultRemote struct {
|
||||
*storage.MemChunkRemote
|
||||
mu sync.Mutex
|
||||
putErr error // returned by every Put while set
|
||||
casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold"
|
||||
casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold", "hold-detach"
|
||||
getHeadErr error // returned by every GetHead while set
|
||||
getHeadFail int // the next N GetHead calls fail
|
||||
getHeadHold bool // every GetHead blocks until its caller gives up
|
||||
@@ -33,6 +34,104 @@ type faultRemote struct {
|
||||
// remote only when release closes; its own result goes to delayedErr.
|
||||
release chan struct{}
|
||||
delayedErr chan error
|
||||
// held records the CAS held by "hold-detach", heldRead the first HEAD read
|
||||
// held once readArmed is set: when and why each context ended, and what
|
||||
// its witness saw (see witnessHeld).
|
||||
held heldOp
|
||||
heldRead heldOp
|
||||
readArmed bool
|
||||
}
|
||||
|
||||
type heldOp struct {
|
||||
entered bool
|
||||
ctx context.Context
|
||||
ended time.Time
|
||||
cause error // context.Cause once the context ended
|
||||
witness heldObservation
|
||||
}
|
||||
|
||||
// heldObservation is one sample of a held operation's context, taken
|
||||
// between from and at.
|
||||
type heldObservation struct {
|
||||
ran bool
|
||||
from, at time.Time
|
||||
entered bool // the operation was already held when sampled
|
||||
cause error // its context.Cause then (nil: still live)
|
||||
}
|
||||
|
||||
const (
|
||||
// The witness samples witnessDelay after a traced deadline, so a cancel
|
||||
// shifted witnessShift past it is still live at the sample.
|
||||
witnessDelay = 50 * time.Millisecond
|
||||
witnessShift = 100 * time.Millisecond
|
||||
witnessAttempts = 3
|
||||
)
|
||||
|
||||
var errWitnessUnexercised = errors.New("witness not exercised")
|
||||
|
||||
// witnessVerdict judges one sample of the operation held under deadline.
|
||||
// Only a sample of an already held operation, taken after the deadline and
|
||||
// before the shift, discriminates: then its context must already be
|
||||
// cancelled for that deadline's expiry. Any other sample (late timer,
|
||||
// operation not yet held) proves nothing either way and is reported as
|
||||
// unexercised; it is never filled in from a later observation.
|
||||
func witnessVerdict(deadline time.Time, o heldObservation) error {
|
||||
switch {
|
||||
case !o.ran:
|
||||
return fmt.Errorf("%w: the witness never ran", errWitnessUnexercised)
|
||||
case o.from.Before(deadline):
|
||||
return fmt.Errorf("%w: sampled %v before the deadline", errWitnessUnexercised, deadline.Sub(o.from))
|
||||
case !o.at.Before(deadline.Add(witnessShift)):
|
||||
return fmt.Errorf("%w: sampled up to %v after the deadline, not within %v", errWitnessUnexercised, o.at.Sub(deadline), witnessShift)
|
||||
case !o.entered:
|
||||
return fmt.Errorf("%w: the operation was not held yet when sampled", errWitnessUnexercised)
|
||||
case !errors.Is(o.cause, context.DeadlineExceeded):
|
||||
return fmt.Errorf("held operation live or cancelled otherwise (cause %v) %v after its traced deadline", o.cause, o.from.Sub(deadline))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func heldDetachCAS(r *faultRemote) *heldOp { return &r.held }
|
||||
func heldSettleRead(r *faultRemote) *heldOp { return &r.heldRead }
|
||||
|
||||
// witnessHeld samples the context of the operation op selects once,
|
||||
// witnessDelay after the traced deadline, recording when the sample was
|
||||
// taken. done is closed once the sample is recorded.
|
||||
func (r *faultRemote) witnessHeld(deadline time.Time, op func(*faultRemote) *heldOp) (done <-chan struct{}, stop func() bool) {
|
||||
ch := make(chan struct{})
|
||||
tm := time.AfterFunc(time.Until(deadline.Add(witnessDelay)), func() {
|
||||
r.set(func(r *faultRemote) {
|
||||
h := op(r)
|
||||
o := heldObservation{ran: true, from: time.Now()}
|
||||
if h.ctx != nil {
|
||||
o.entered, o.cause = true, context.Cause(h.ctx)
|
||||
}
|
||||
o.at = time.Now()
|
||||
h.witness = o
|
||||
})
|
||||
close(ch)
|
||||
})
|
||||
return ch, tm.Stop
|
||||
}
|
||||
|
||||
// retryUnexercised runs attempt until its witness is exercised: an attempt
|
||||
// whose sample proved nothing (a loaded host) is retried, up to
|
||||
// witnessAttempts; attempt fails t itself on any defect.
|
||||
func retryUnexercised(t *testing.T, attempt func(t *testing.T) error) {
|
||||
t.Helper()
|
||||
for n := 1; ; n++ {
|
||||
var verdict error
|
||||
if !t.Run(fmt.Sprintf("attempt%d", n), func(t *testing.T) { verdict = attempt(t) }) {
|
||||
return
|
||||
}
|
||||
if verdict == nil {
|
||||
return
|
||||
}
|
||||
if n == witnessAttempts {
|
||||
t.Fatalf("no attempt in %d exercised the witness; last: %v", n, verdict)
|
||||
}
|
||||
t.Logf("attempt %d: %v; retrying", n, verdict)
|
||||
}
|
||||
}
|
||||
|
||||
var errInjected = errors.New("injected remote fault")
|
||||
@@ -59,7 +158,17 @@ func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
}
|
||||
r.mu.Unlock()
|
||||
if hold {
|
||||
var mine bool
|
||||
r.set(func(r *faultRemote) {
|
||||
if mine = r.readArmed && !r.heldRead.entered; mine {
|
||||
r.heldRead.entered, r.heldRead.ctx = true, ctx
|
||||
}
|
||||
})
|
||||
<-ctx.Done()
|
||||
if mine {
|
||||
ended := time.Now()
|
||||
r.set(func(r *faultRemote) { r.heldRead.ended, r.heldRead.cause = ended, context.Cause(ctx) })
|
||||
}
|
||||
return storage.ChunkHead{}, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
@@ -71,7 +180,12 @@ func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
|
||||
func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
|
||||
r.mu.Lock()
|
||||
mode := r.casMode
|
||||
r.casMode = "" // one fault, on the next CAS only
|
||||
switch {
|
||||
case mode == "hold-detach" && next.State != storage.ChunkHeadDetached:
|
||||
mode = "" // only the detach CAS is held; others (a running chunk loop) pass
|
||||
default:
|
||||
r.casMode = "" // one fault, on the next CAS only
|
||||
}
|
||||
r.mu.Unlock()
|
||||
switch mode {
|
||||
case "precondition":
|
||||
@@ -81,6 +195,14 @@ func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer
|
||||
case "hold": // held until the caller gives up: not applied
|
||||
<-ctx.Done()
|
||||
return 0, ctx.Err()
|
||||
case "hold-detach": // the detach CAS, held until its caller gives up; witnessed
|
||||
r.set(func(r *faultRemote) {
|
||||
r.held.entered, r.held.ctx = true, ctx
|
||||
})
|
||||
<-ctx.Done()
|
||||
ended := time.Now()
|
||||
r.set(func(r *faultRemote) { r.held.ended, r.held.cause = ended, context.Cause(ctx) })
|
||||
return 0, ctx.Err()
|
||||
case "delayed":
|
||||
r.mu.Lock()
|
||||
release, out := r.release, r.delayedErr
|
||||
@@ -224,10 +346,25 @@ func TestWALStoreChunk_UndecidableDetachStaysStopped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The freeze is bounded by DetachFreezeTimeout: a CAS that hangs ends there,
|
||||
// the outcome is settled (HEAD still at base: cancelled) and serving resumes,
|
||||
// all well inside bound + settle.
|
||||
// The freeze is bounded by DetachFreezeTimeout: a detach CAS that hangs ends at
|
||||
// the cut's deadline (three quarters of the bound), the outcome is settled
|
||||
// (HEAD still at base: cancelled) inside the bound, and serving resumes. The
|
||||
// test asserts against the deadlines the detach itself traced, so a loaded
|
||||
// host cannot turn the order into a timing failure; the settlement keeps a
|
||||
// quarter of a 2 s bound for its HEAD read and cancel.
|
||||
//
|
||||
// The CAS must also be cancelled at the traced cut deadline, not later. That
|
||||
// takes a sample between the deadline and a 100 ms shift; an attempt whose
|
||||
// sample missed that window (a loaded host) proves nothing and is retried,
|
||||
// up to witnessAttempts.
|
||||
func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) {
|
||||
retryUnexercised(t, detachFreezeAttempt)
|
||||
}
|
||||
|
||||
// detachFreezeAttempt runs one bounded detach; it fails t on any defect and
|
||||
// returns the cut witness's verdict when that sample proved nothing.
|
||||
func detachFreezeAttempt(t *testing.T) error {
|
||||
const freeze = 2 * time.Second
|
||||
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk,
|
||||
@@ -235,7 +372,7 @@ func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) {
|
||||
BlockSize: 4096,
|
||||
NumBlocks: pcBlocks,
|
||||
ChunkBlocks: pcChunkBlocks,
|
||||
DetachFreezeTimeout: 300 * time.Millisecond,
|
||||
DetachFreezeTimeout: freeze,
|
||||
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
|
||||
}, v1View())
|
||||
if err != nil {
|
||||
@@ -256,18 +393,95 @@ func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) {
|
||||
if _, err := b.Write(context.Background(), 8192, block(2)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote.set(func(r *faultRemote) { r.casMode = "hold" })
|
||||
start := time.Now()
|
||||
remote.set(func(r *faultRemote) { r.casMode = "hold-detach" })
|
||||
deadlines := map[string]time.Time{}
|
||||
var witnessed <-chan struct{}
|
||||
durable.SetTestDetachTrace(p, func(stage string, d time.Time) {
|
||||
deadlines[stage] = d
|
||||
if stage == "cut" {
|
||||
var stop func() bool
|
||||
witnessed, stop = remote.witnessHeld(d, heldDetachCAS)
|
||||
t.Cleanup(func() { stop() })
|
||||
}
|
||||
})
|
||||
_, _, err = p.DetachVolume(context.Background(), "v1")
|
||||
took := time.Since(start)
|
||||
end := time.Now()
|
||||
if witnessed == nil {
|
||||
t.Fatal("the detach traced no cut deadline")
|
||||
}
|
||||
<-witnessed
|
||||
if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err)
|
||||
}
|
||||
// The cut gets three quarters of the bound, the settlement the rest.
|
||||
if took < 225*time.Millisecond || took > 300*time.Millisecond+200*time.Millisecond {
|
||||
t.Fatalf("detach with a hung CAS took %v; want the cut ended at 3/4 of the 300 ms freeze bound and the total within it", took)
|
||||
// One budget from one origin: the cut ends at three quarters of it, the
|
||||
// settlement at its end (exact, both derive from the same start).
|
||||
cut, settle := deadlines["cut"], deadlines["settle"]
|
||||
if gap := settle.Sub(cut); gap != freeze/4 {
|
||||
t.Fatalf("settlement deadline %v after the cut deadline; want a quarter of the %v bound", gap, freeze)
|
||||
}
|
||||
// The held operation is the detach CAS itself, released by the cut's
|
||||
// expiry. Its context's own deadline proves nothing: a CAS carries its
|
||||
// own operation timeout, and the cut may be a timer, not a deadline.
|
||||
var held heldOp
|
||||
remote.set(func(r *faultRemote) { held = r.held })
|
||||
if !held.entered {
|
||||
t.Fatal("the detach CAS was never held")
|
||||
}
|
||||
if held.ended.Before(cut) {
|
||||
t.Fatalf("held detach CAS ended %v before its deadline", cut.Sub(held.ended))
|
||||
}
|
||||
// Deadline or timer, the CAS was cancelled for the cut's own expiry and
|
||||
// by the traced cut deadline (plus the witness slack), not later.
|
||||
if !errors.Is(held.cause, context.DeadlineExceeded) {
|
||||
t.Fatalf("held detach CAS cancelled with cause %v; want the cut's deadline expiry", held.cause)
|
||||
}
|
||||
verdict := witnessVerdict(cut, held.witness)
|
||||
if verdict != nil && !errors.Is(verdict, errWitnessUnexercised) {
|
||||
t.Fatal(verdict)
|
||||
}
|
||||
if end.Before(held.ended) {
|
||||
t.Fatal("detach returned before its held CAS ended")
|
||||
}
|
||||
if late := end.Sub(settle); late > 500*time.Millisecond {
|
||||
t.Fatalf("detach returned %v after the freeze bound", late)
|
||||
}
|
||||
assertServing(t, p, b, remote)
|
||||
return verdict
|
||||
}
|
||||
|
||||
// The verdict counts only a sample of an already held CAS, taken inside the
|
||||
// window, as evidence; a late sample of a context that a shifted cut has
|
||||
// cancelled by then, or a CAS that entered after the sample, prove nothing.
|
||||
func TestHeldWitnessVerdict(t *testing.T) {
|
||||
cut := time.Unix(1700000000, 0)
|
||||
at := func(d time.Duration) time.Time { return cut.Add(d) }
|
||||
ms := time.Millisecond
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
o heldObservation
|
||||
want string // "pass", "unexercised" or "fail"
|
||||
}{
|
||||
{"cancelled at the cut", heldObservation{true, at(50 * ms), at(51 * ms), true, context.DeadlineExceeded}, "pass"},
|
||||
{"still live: shifted cut", heldObservation{true, at(50 * ms), at(51 * ms), true, nil}, "fail"},
|
||||
{"cancelled otherwise", heldObservation{true, at(50 * ms), at(51 * ms), true, context.Canceled}, "fail"},
|
||||
{"never sampled", heldObservation{}, "unexercised"},
|
||||
{"entered after the sample", heldObservation{true, at(50 * ms), at(51 * ms), false, nil}, "unexercised"},
|
||||
{"delayed sample of a shifted cut", heldObservation{true, at(120 * ms), at(121 * ms), true, context.DeadlineExceeded}, "unexercised"},
|
||||
{"sample straddles the shift", heldObservation{true, at(90 * ms), at(100 * ms), true, context.DeadlineExceeded}, "unexercised"},
|
||||
{"sampled before the cut", heldObservation{true, at(-ms), at(0), true, nil}, "unexercised"},
|
||||
} {
|
||||
err := witnessVerdict(cut, c.o)
|
||||
got := "fail"
|
||||
switch {
|
||||
case err == nil:
|
||||
got = "pass"
|
||||
case errors.Is(err, errWitnessUnexercised):
|
||||
got = "unexercised"
|
||||
}
|
||||
if got != c.want {
|
||||
t.Errorf("%s: %s (%v), want %s", c.name, got, err, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// HEAD belongs to a newer epoch: the detach's CAS is refused and the volume
|
||||
@@ -338,11 +552,18 @@ func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// P1 (review): one freeze budget covers the cut AND the settlement: with the
|
||||
// CAS and every HEAD read hung, DetachVolume returns within the bound (here
|
||||
// undecided, so the volume stays stopped).
|
||||
// The freeze bound covers the settlement too: with the detach CAS and the
|
||||
// settlement's HEAD read both hung, the cut ends at its deadline, the read
|
||||
// at the bound, the outcome stays unknown and the volume stays stopped. The
|
||||
// bounds are the deadlines the detach traced, and each held operation is
|
||||
// witnessed: the read must be cancelled at the traced settlement deadline,
|
||||
// not later (retried, like the cut witness, when a sample proves nothing).
|
||||
func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) {
|
||||
const freeze = 400 * time.Millisecond
|
||||
retryUnexercised(t, settleBoundAttempt)
|
||||
}
|
||||
|
||||
func settleBoundAttempt(t *testing.T) error {
|
||||
const freeze = 2 * time.Second
|
||||
remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()}
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{
|
||||
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
|
||||
@@ -361,25 +582,66 @@ func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) {
|
||||
if _, err := b.Write(context.Background(), 4096, block(1)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true })
|
||||
remote.set(func(r *faultRemote) { r.casMode = "hold-detach"; r.getHeadHold = true })
|
||||
deadlines := map[string]time.Time{}
|
||||
durable.SetTestDetachTrace(p, func(stage string, d time.Time) { deadlines[stage] = d })
|
||||
start := time.Now()
|
||||
var witnessed <-chan struct{}
|
||||
durable.SetTestDetachTrace(p, func(stage string, d time.Time) {
|
||||
deadlines[stage] = d
|
||||
if stage == "settle" {
|
||||
// Only reads from here on are the settlement's.
|
||||
remote.set(func(r *faultRemote) { r.readArmed = true })
|
||||
var stop func() bool
|
||||
witnessed, stop = remote.witnessHeld(d, heldSettleRead)
|
||||
t.Cleanup(func() { stop() })
|
||||
}
|
||||
})
|
||||
_, _, err = p.DetachVolume(context.Background(), "v1")
|
||||
took := time.Since(start)
|
||||
cutAt, settleAt := deadlines["cut"].Sub(start), deadlines["settle"].Sub(start)
|
||||
if cutAt < freeze*3/4-50*time.Millisecond || cutAt > freeze*3/4+50*time.Millisecond || settleAt < freeze-50*time.Millisecond || settleAt > freeze+50*time.Millisecond {
|
||||
t.Fatalf("deadlines: cut %v, settle %v after the start; want three quarters of the %v freeze, then the bound", cutAt, settleAt, freeze)
|
||||
end := time.Now()
|
||||
if witnessed == nil {
|
||||
t.Fatal("the detach traced no settlement deadline")
|
||||
}
|
||||
<-witnessed
|
||||
if !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
|
||||
t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err)
|
||||
}
|
||||
if took > freeze+200*time.Millisecond {
|
||||
t.Fatalf("detach took %v; the %v freeze bound must cover the settlement too", took, freeze)
|
||||
cut, settle := deadlines["cut"], deadlines["settle"]
|
||||
if gap := settle.Sub(cut); gap != freeze/4 {
|
||||
t.Fatalf("settlement deadline %v after the cut deadline; want a quarter of the %v bound", gap, freeze)
|
||||
}
|
||||
var cas, read heldOp
|
||||
remote.set(func(r *faultRemote) { cas, read = r.held, r.heldRead })
|
||||
// The cut ended on the hung detach CAS, not earlier in the capture.
|
||||
if !cas.entered {
|
||||
t.Fatal("the detach CAS was never held")
|
||||
}
|
||||
if cas.ended.Before(cut) {
|
||||
t.Fatalf("held detach CAS ended %v before the cut deadline", cut.Sub(cas.ended))
|
||||
}
|
||||
// The settlement's HEAD read was held until the bound, and the detach
|
||||
// returned right after it (scheduling slack only).
|
||||
if !read.entered {
|
||||
t.Fatal("the settlement's HEAD read was never held")
|
||||
}
|
||||
if read.ended.Before(settle) {
|
||||
t.Fatalf("held settlement read ended %v before the settlement deadline", settle.Sub(read.ended))
|
||||
}
|
||||
if !errors.Is(read.cause, context.DeadlineExceeded) {
|
||||
t.Fatalf("held settlement read cancelled with cause %v; want the bound's expiry", read.cause)
|
||||
}
|
||||
verdict := witnessVerdict(settle, read.witness)
|
||||
if verdict != nil && !errors.Is(verdict, errWitnessUnexercised) {
|
||||
t.Fatal(verdict)
|
||||
}
|
||||
if end.Before(read.ended) {
|
||||
t.Fatal("detach returned before its held settlement read ended")
|
||||
}
|
||||
if late := end.Sub(settle); late > 500*time.Millisecond {
|
||||
t.Fatalf("detach returned %v after the freeze bound; the bound must cover the settlement too", late)
|
||||
}
|
||||
if _, err := b.Write(context.Background(), 8192, block(2)); !errors.Is(err, frontend.ErrNotReady) {
|
||||
t.Fatalf("write after an undecided detach: %v; want ErrNotReady", err)
|
||||
}
|
||||
return verdict
|
||||
}
|
||||
|
||||
// P2 (review): the lost detach CAS really is in flight. It reaches the remote
|
||||
|
||||
@@ -25,8 +25,7 @@ func awaitRestoreCondition(t *testing.T, ctx context.Context, what string, ready
|
||||
}
|
||||
|
||||
func TestRestoreCheckpointBeforeAssignmentPreservesRemoteBytes(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
view := newStubView(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})
|
||||
p := chunkProvider(t, t.TempDir(), remote, view, 0)
|
||||
@@ -80,8 +79,7 @@ func (r *publishAfterAbsentRead) GetHead(ctx context.Context) (storage.ChunkHead
|
||||
}
|
||||
|
||||
func TestRestoreHEADAppearsBetweenClaimAndAttach(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
data := bytes.Repeat([]byte{0xA7}, pcChunkBlocks*4096)
|
||||
wrapped := &publishAfterAbsentRead{ChunkRemote: remote, beforeReturn: func() {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
@@ -87,8 +86,7 @@ func failSeedFD(t *testing.T, root string) func() {
|
||||
}
|
||||
|
||||
func TestRestoreFailedSeedSyncRetryCaptureAndReopen(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
root := filepath.Join(t.TempDir(), "provider")
|
||||
remote := storage.NewMemChunkRemote()
|
||||
data := bytes.Repeat([]byte{0xA7}, 4*4096)
|
||||
@@ -191,8 +189,7 @@ func TestRestoreFailedSeedSyncRetryCaptureAndReopen(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRestoreFailedSeedNeverTakesOwnership(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
root := filepath.Join(t.TempDir(), "provider")
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil {
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
@@ -24,8 +23,7 @@ func (r *takeoverOrderRemote) CASHead(ctx context.Context, v storage.ChunkHeadVe
|
||||
}
|
||||
|
||||
func TestRestoreSeedPrecedesTakeoverCAS(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -81,8 +79,7 @@ func TestRestoreSeedPrecedesTakeoverCAS(t *testing.T) {
|
||||
// A restored restart under the same assignment must reactivate a detached
|
||||
// image before exposing I/O, not treat it as an already-settled active claim.
|
||||
func TestRestoreEqualOwnerDetachedHEADIsReactivated(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
makeProvider := func() *durable.DurableProvider {
|
||||
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "node-a/r1",
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
|
||||
@@ -49,8 +48,7 @@ func (o *countingRebaser) seen() []uint64 {
|
||||
// before the takeover CAS. Returns the recovery error.
|
||||
func restoreWithObserver(t *testing.T, obs *countingRebaser, atCAS func(p *durable.DurableProvider)) (storage.ChunkRemote, *durable.DurableProvider, *atomic.Int32, error) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
ctx := hangGuard(t)
|
||||
remote := storage.NewMemChunkRemote()
|
||||
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, storage.ChunkHead{Epoch: 1, Holder: "old", RemoteLSN: 7}); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -104,8 +102,7 @@ func TestRestoreRefusedShipRebaseKeepsHeadAndIOClosed(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("restore succeeded although the observer refused the post-seed ship-LSN rebase")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
h, herr := remote.GetHead(ctx)
|
||||
if herr != nil || calls.Load() != 0 || h.Epoch != 1 || h.Holder != "old" {
|
||||
t.Fatalf("HEAD claimed despite a refused ship rebase: CAS calls=%d head=%+v err=%v; want 0 calls, epoch 1 holder old", calls.Load(), h, herr)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type bootstrapBlobs struct {
|
||||
@@ -36,8 +35,7 @@ func (b *bootstrapBlobs) Get(_ context.Context, id string) ([]byte, error) {
|
||||
}
|
||||
|
||||
func TestRestoreEnsureVolumeZeroHEADPreservesCheckpointedBootstrap(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
ctx := hangGuard(t)
|
||||
filer := chunkstore.NewMemFiler()
|
||||
catalog, err := chunkstore.NewCatalog(filer, "/bootstrap")
|
||||
if err != nil {
|
||||
|
||||
@@ -17,6 +17,7 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -30,6 +31,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/host/bootstrap"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -78,6 +80,18 @@ type Config struct {
|
||||
FrontendPublicationRuntimeHTTP bool
|
||||
FrontendPublicationRuntimeListen string
|
||||
|
||||
// StrictJournalIsolation refuses nodes whose durable root shares the
|
||||
// authority store's file system (one journal): a co-located node that
|
||||
// serves no volume yet gets its heartbeats refused, and no new placement
|
||||
// or move targets a co-located node. A co-located node that already
|
||||
// serves volumes is only alarmed (refusing it would stop its lease
|
||||
// renewals). Off: alarm only.
|
||||
StrictJournalIsolation bool
|
||||
|
||||
// StatusListen, when non-empty, serves the read-only status endpoint
|
||||
// GET /status/workspace-lease on this loopback address.
|
||||
StatusListen string
|
||||
|
||||
// Logger is used for structured startup and error logging. If
|
||||
// nil, the default log package logger is used.
|
||||
Logger *log.Logger
|
||||
@@ -107,6 +121,9 @@ type Host struct {
|
||||
ln net.Listener
|
||||
frontendRuntimeLn net.Listener
|
||||
frontendRuntimeHTTP *http.Server
|
||||
statusLn net.Listener
|
||||
statusHTTP *http.Server
|
||||
journal *journalIsolation
|
||||
grpc *grpc.Server
|
||||
topo authority.AcceptedTopology
|
||||
lifecycle *LifecycleStores
|
||||
@@ -184,6 +201,9 @@ func New(cfg Config) (*Host, error) {
|
||||
if cfg.Listen == "" {
|
||||
return nil, fmt.Errorf("master.New: Listen is required")
|
||||
}
|
||||
if err := ValidateStatusListen(cfg.StatusListen); err != nil {
|
||||
return nil, fmt.Errorf("master.New: %w", err)
|
||||
}
|
||||
lg := cfg.Logger
|
||||
if lg == nil {
|
||||
lg = log.Default()
|
||||
@@ -205,11 +225,12 @@ func New(cfg Config) (*Host, error) {
|
||||
ctrl := authority.NewTopologyController(ctrlCfg, holder)
|
||||
|
||||
h := &Host{
|
||||
cfg: cfg,
|
||||
log: lg,
|
||||
ctrl: ctrl,
|
||||
topo: cfg.Topology,
|
||||
events: newEventRing(1024),
|
||||
cfg: cfg,
|
||||
log: lg,
|
||||
ctrl: ctrl,
|
||||
topo: cfg.Topology,
|
||||
events: newEventRing(1024),
|
||||
journal: newJournalIsolation(storeident.Identity{}), // sampled once the store exists
|
||||
}
|
||||
|
||||
boot, err := bootstrap.BootstrapWithOptions(cfg.AuthorityStoreDir, ctrl, bootstrap.Options{
|
||||
@@ -221,6 +242,10 @@ func New(cfg Config) (*Host, error) {
|
||||
return nil, fmt.Errorf("master.New: Bootstrap: %w", err)
|
||||
}
|
||||
holder.set(boot.Publisher)
|
||||
// Bootstrap creates a fresh store directory: sample its file system only
|
||||
// now, or a first start would compare against an unknown device forever.
|
||||
// An unknown identity (stat error, unsupported platform) never matches.
|
||||
h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir))
|
||||
|
||||
var sink authority.ControllerSink = ctrl
|
||||
if len(cfg.Topology.Volumes) == 0 {
|
||||
@@ -277,6 +302,23 @@ func New(cfg Config) (*Host, error) {
|
||||
h.frontendRuntimeHTTP = &http.Server{Handler: h.frontendPublicationRuntimeHandler()}
|
||||
}
|
||||
|
||||
if cfg.StatusListen != "" {
|
||||
statusLn, err := net.Listen("tcp", cfg.StatusListen)
|
||||
if err != nil {
|
||||
if h.frontendRuntimeLn != nil {
|
||||
_ = h.frontendRuntimeLn.Close()
|
||||
}
|
||||
_ = ln.Close()
|
||||
_ = boot.Close()
|
||||
return nil, fmt.Errorf("master.New: status listen %q: %w", cfg.StatusListen, err)
|
||||
}
|
||||
h.statusLn = statusLn
|
||||
// Every connection phase is bounded: a client that withholds a
|
||||
// declared body or never reads the reply is cut off.
|
||||
h.statusHTTP = &http.Server{Handler: h.statusHandler(), ReadHeaderTimeout: statusReadTimeout, ReadTimeout: statusReadTimeout,
|
||||
WriteTimeout: statusWriteTimeout, IdleTimeout: statusIdleTimeout}
|
||||
}
|
||||
|
||||
grpcSrv := grpc.NewServer()
|
||||
svc := newServices(h)
|
||||
control.RegisterObservationServiceServer(grpcSrv, svc)
|
||||
@@ -293,6 +335,12 @@ func New(cfg Config) (*Host, error) {
|
||||
if h.frontendRuntimeLn != nil {
|
||||
lg.Printf("blockmaster: frontend publication runtime listen=%s", h.frontendRuntimeLn.Addr().String())
|
||||
}
|
||||
if h.statusLn != nil {
|
||||
lg.Printf("blockmaster: status listen=%s", h.statusLn.Addr().String())
|
||||
}
|
||||
if cfg.StrictJournalIsolation {
|
||||
lg.Printf("blockmaster: strict journal isolation: nodes sharing the authority store's file system are refused new work")
|
||||
}
|
||||
for _, e := range boot.ReloadSkips {
|
||||
lg.Printf("blockmaster: reload skip: %v", e)
|
||||
}
|
||||
@@ -344,6 +392,15 @@ func (h *Host) FrontendPublicationRuntimeAddr() string {
|
||||
return h.frontendRuntimeLn.Addr().String()
|
||||
}
|
||||
|
||||
// StatusAddr returns the bound status HTTP address, or empty when the status
|
||||
// endpoint is disabled.
|
||||
func (h *Host) StatusAddr() string {
|
||||
if h.statusLn == nil {
|
||||
return ""
|
||||
}
|
||||
return h.statusLn.Addr().String()
|
||||
}
|
||||
|
||||
// Publisher exposes the reloaded publisher for tests and for the
|
||||
// evidence-query path.
|
||||
func (h *Host) Publisher() *authority.Publisher {
|
||||
@@ -454,6 +511,16 @@ func (h *Host) Start() context.Context {
|
||||
}()
|
||||
}
|
||||
|
||||
if h.statusHTTP != nil && h.statusLn != nil {
|
||||
h.wg.Add(1)
|
||||
go func() {
|
||||
defer h.wg.Done()
|
||||
if err := h.statusHTTP.Serve(h.statusLn); err != nil && err != http.ErrServerClosed {
|
||||
h.log.Printf("blockmaster: status Serve: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return ctx
|
||||
}
|
||||
|
||||
@@ -466,6 +533,10 @@ func (h *Host) Close(ctx context.Context) error {
|
||||
if h.frontendRuntimeHTTP != nil {
|
||||
_ = h.frontendRuntimeHTTP.Shutdown(ctx)
|
||||
}
|
||||
var statusErr error
|
||||
if h.statusHTTP != nil {
|
||||
statusErr = h.closeStatusHTTP(ctx)
|
||||
}
|
||||
h.obs.Stop()
|
||||
|
||||
done := make(chan struct{})
|
||||
@@ -484,5 +555,29 @@ func (h *Host) Close(ctx context.Context) error {
|
||||
if h.boot != nil && h.boot.Publisher != nil {
|
||||
h.boot.Publisher.CloseWorkspaceExtenders()
|
||||
}
|
||||
return h.boot.Close()
|
||||
return errors.Join(statusErr, h.boot.Close())
|
||||
}
|
||||
|
||||
// Status endpoint connection bounds.
|
||||
const (
|
||||
statusReadTimeout = 5 * time.Second
|
||||
statusWriteTimeout = 5 * time.Second
|
||||
statusIdleTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// closeStatusHTTP shuts the status endpoint down gracefully until ctx ends,
|
||||
// then force-closes the connections still open (Shutdown leaves them). It
|
||||
// returns the force close's error, if any; an expired graceful shutdown that
|
||||
// the force close completed is only logged.
|
||||
func (h *Host) closeStatusHTTP(ctx context.Context) error {
|
||||
defer h.statusLn.Close() // a listener Start never served is not Shutdown's
|
||||
err := h.statusHTTP.Shutdown(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
h.log.Printf("blockmaster: status graceful shutdown: %v; closing its open connections", err)
|
||||
if cerr := h.statusHTTP.Close(); cerr != nil && !errors.Is(cerr, net.ErrClosed) {
|
||||
return fmt.Errorf("status endpoint close: %w", cerr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
)
|
||||
|
||||
// journalIsolation tracks nodes whose durable root shares the authority
|
||||
// store's file system. On one ext4 file system every fsync goes through one
|
||||
// jbd2 journal: a volume's WAL fsync storm delays the authority journal's
|
||||
// lease extensions, grants clamp to the durable horizon and leases run out.
|
||||
//
|
||||
// The colocated set is the latest heartbeat fact per server (memory only): a
|
||||
// node that moves its durable root off the store's file system leaves the set
|
||||
// on its next heartbeat. What a node serves is never read from here; that is
|
||||
// decided from durable state (nodeServesVolumes).
|
||||
type journalIsolation struct {
|
||||
mu sync.Mutex
|
||||
self storeident.Identity
|
||||
colocated map[string]storeident.Identity // server id -> its reported identity
|
||||
}
|
||||
|
||||
func newJournalIsolation(self storeident.Identity) *journalIsolation {
|
||||
return &journalIsolation{self: self, colocated: map[string]storeident.Identity{}}
|
||||
}
|
||||
|
||||
// observe records server's reported identity. It returns whether the node is
|
||||
// co-located and, on its first detection, the line to log.
|
||||
func (j *journalIsolation) observe(server string, id storeident.Identity) (bool, string) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
if !j.self.SameFileSystem(id) {
|
||||
delete(j.colocated, server)
|
||||
return false, ""
|
||||
}
|
||||
if _, seen := j.colocated[server]; seen {
|
||||
return true, ""
|
||||
}
|
||||
j.colocated[server] = id
|
||||
return true, fmt.Sprintf("blockmaster: node %s shares the authority store's file system (machine %s, dev %d): its fsyncs share the authority journal", server, id.MachineID, id.Dev)
|
||||
}
|
||||
|
||||
func (j *journalIsolation) isColocated(server string) bool {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
_, ok := j.colocated[server]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (j *journalIsolation) count() int {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
return len(j.colocated)
|
||||
}
|
||||
|
||||
func (j *journalIsolation) setSelf(id storeident.Identity) {
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
j.self = id
|
||||
}
|
||||
|
||||
// nodeServesVolumes reports whether durable state already gives server work:
|
||||
// a lifecycle placement slot on it, or a current authority line whose source
|
||||
// host (an issued move's target, the placement, or a static topology slot) is
|
||||
// it. Both survive a master restart, so a restart never turns a serving node
|
||||
// into a new one. A heartbeat must not wait behind a slow authority write: it
|
||||
// takes neither workspaceMu nor the publisher lock (held across authority
|
||||
// store writes), only the published authority lines and the lifecycle
|
||||
// stores, whose locks cover only their own file I/O.
|
||||
func (h *Host) nodeServesVolumes(server string) bool {
|
||||
lines := h.Publisher().PublishedAuthorityLines()
|
||||
if h.lifecycle != nil {
|
||||
for _, p := range h.lifecycle.Placements.ListPlacements() {
|
||||
for _, slot := range p.Slots {
|
||||
if slot.ServerID == server {
|
||||
return true // also every line a placement slot sources
|
||||
}
|
||||
}
|
||||
}
|
||||
for volume, line := range lines {
|
||||
if _, live := h.lifecycle.Volumes.GetVolumeSnapshot(volume); live && line.IssuedHost == server {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, v := range h.topo.Volumes {
|
||||
line, ok := lines[v.VolumeID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, slot := range v.Slots {
|
||||
if slot.ServerID == server && slot.ReplicaID == line.ReplicaID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// refuseColocatedHeartbeat is the strict heartbeat rule: a co-located node
|
||||
// that serves nothing yet is refused; a serving one is only alarmed.
|
||||
func (h *Host) refuseColocatedHeartbeat(server string, id storeident.Identity) error {
|
||||
colocated, note := h.journal.observe(server, id)
|
||||
if note != "" {
|
||||
h.log.Print(note)
|
||||
}
|
||||
if !colocated || !h.cfg.StrictJournalIsolation || h.nodeServesVolumes(server) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("heartbeat: node %s shares the authority store's file system (machine %s, dev %d) and serves no volume; strict journal isolation refuses it", server, id.MachineID, id.Dev)
|
||||
}
|
||||
|
||||
// colocatedTargetRefused reports whether strict isolation refuses new work
|
||||
// (a placement or move target) on server.
|
||||
func (h *Host) colocatedTargetRefused(server string) bool {
|
||||
return h.cfg.StrictJournalIsolation && h.journal.isColocated(server)
|
||||
}
|
||||
|
||||
// reconcilePlacements runs the product loop's placement reconcile. Under
|
||||
// strict isolation each volume plans against the nodes without co-located
|
||||
// ones, except the nodes its existing placement already names: a placement
|
||||
// on a co-located node is kept (re-planning it away would move a serving
|
||||
// volume), and no new placement chooses a co-located node.
|
||||
func (h *Host) reconcilePlacements(stores *LifecycleStores, nodes []lifecycle.NodeRegistration) []lifecycle.ReconcileResult {
|
||||
if !h.cfg.StrictJournalIsolation {
|
||||
return lifecycle.ReconcilePlacement(stores.liveVolumes(), nodes, stores.Placements)
|
||||
}
|
||||
var out []lifecycle.ReconcileResult
|
||||
for _, v := range stores.liveVolumes() {
|
||||
placed := map[string]bool{}
|
||||
if p, ok := stores.Placements.GetPlacement(v.Spec.VolumeID); ok {
|
||||
for _, slot := range p.Slots {
|
||||
placed[slot.ServerID] = true
|
||||
}
|
||||
}
|
||||
allowed := make([]lifecycle.NodeRegistration, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
if placed[n.ServerID] || !h.journal.isColocated(n.ServerID) {
|
||||
allowed = append(allowed, n)
|
||||
}
|
||||
}
|
||||
out = append(out, lifecycle.ReconcilePlacement([]lifecycle.VolumeRecord{v}, allowed, stores.Placements)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ValidateStatusListen accepts "" (disabled) or a loopback host:port
|
||||
// (127.0.0.0/8, ::1, localhost). The status endpoint is unauthenticated.
|
||||
func ValidateStatusListen(addr string) error {
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
host, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("--status-listen %q: %v", addr, err)
|
||||
}
|
||||
if host == "localhost" {
|
||||
return nil
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("--status-listen %q must be a loopback address (127.0.0.0/8, ::1 or localhost)", addr)
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStatus is the GET /status/workspace-lease body.
|
||||
type WorkspaceLeaseStatus struct {
|
||||
ColocatedNodes int `json:"colocated_nodes"`
|
||||
HeadroomAlarms uint64 `json:"headroom_alarms"`
|
||||
ClampsTotal uint64 `json:"clamps_total"`
|
||||
ClampsLastMinute uint64 `json:"clamps_last_minute"`
|
||||
MinHeadroomMS int64 `json:"min_headroom_ms"` // -1: no grant observed yet
|
||||
StrictJournalIsolation bool `json:"strict_journal_isolation"`
|
||||
// Lease extension store write latency, the earliest lag signal.
|
||||
ExtensionWriteLastMS int64 `json:"extension_write_last_ms"` // -1: no extension write yet
|
||||
ExtensionWriteMaxLastMinuteMS int64 `json:"extension_write_max_last_minute_ms"` // -1: none in the last minute
|
||||
}
|
||||
|
||||
// WorkspaceLeaseStatus returns the journal-isolation and lease headroom
|
||||
// counters served by the status endpoint.
|
||||
func (h *Host) WorkspaceLeaseStatus() WorkspaceLeaseStatus {
|
||||
st := WorkspaceLeaseStatus{ColocatedNodes: h.journal.count(), MinHeadroomMS: -1, StrictJournalIsolation: h.cfg.StrictJournalIsolation,
|
||||
ExtensionWriteLastMS: -1, ExtensionWriteMaxLastMinuteMS: -1}
|
||||
if p := h.Publisher(); p != nil {
|
||||
s := p.WorkspaceLeaseStats()
|
||||
st.HeadroomAlarms, st.ClampsTotal, st.ClampsLastMinute = s.HeadroomAlarms, s.ClampsTotal, s.ClampsLastMinute
|
||||
if s.MinHeadroomObserved {
|
||||
st.MinHeadroomMS = s.MinHeadroom.Milliseconds()
|
||||
}
|
||||
if s.ExtensionWriteObserved {
|
||||
st.ExtensionWriteLastMS = s.ExtensionWriteLast.Milliseconds()
|
||||
}
|
||||
if s.ExtensionWriteInLastMinute {
|
||||
st.ExtensionWriteMaxLastMinuteMS = s.ExtensionWriteMaxLastMinute.Milliseconds()
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
func (h *Host) statusHandler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/status/workspace-lease", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(h.WorkspaceLeaseStatus())
|
||||
})
|
||||
return mux
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
const colocatedMoveRefusal = `move target node "node-b" shares the authority store's file system (strict journal isolation)`
|
||||
|
||||
// issueMove serves vol from node-a at epoch 1 and moves it cleanly to node-b
|
||||
// through the Workspace RPC. It returns the request and its grant.
|
||||
func (r *isolationRig) issueMove(t *testing.T, vol, requestID string) (*control.WorkspaceMove, *control.WorkspaceGrant) {
|
||||
t.Helper()
|
||||
r.createVolume(t, vol)
|
||||
r.place(t, vol, "node-a")
|
||||
if err := r.m.ObservationHost().Ingest(authority.Observation{ServerID: "node-a", ObservedAt: time.Now().UTC(),
|
||||
Slots: []authority.SlotFact{{VolumeID: vol, ReplicaID: "r1", DataAddr: "127.0.0.1:19131", CtrlAddr: "127.0.0.1:19132"}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
line := waitAuthorityLine(t, r.m.Publisher(), vol)
|
||||
if line.Epoch != 1 || line.ReplicaID != "r1" {
|
||||
t.Fatalf("fixture authority line: %+v", line)
|
||||
}
|
||||
id := &control.WorkspaceIdentity{VolumeId: vol, ReplicaId: "r1", Epoch: 1}
|
||||
if _, err := r.ws.RenewWorkspaceLease(r.ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.RevokeWorkspace(r.ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ws.AckWorkspaceRevoked(r.ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := &control.WorkspaceMove{RequestId: requestID, VolumeId: vol, ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"}
|
||||
grant, err := r.ws.MoveWorkspace(r.ctx, q)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !grant.Issued || grant.NewEpoch != 2 || grant.NewHost != "node-b" {
|
||||
t.Fatalf("fixture grant: %+v", grant)
|
||||
}
|
||||
return q, grant
|
||||
}
|
||||
|
||||
// Strict isolation refuses new work, never an issued decision: a move issued
|
||||
// to node-b before node-b reported its identity, whose reply was lost, is
|
||||
// retried after node-b turned out co-located. The SAME request gets the
|
||||
// identical durable grant (no new epoch, no second record); a new request id
|
||||
// or a changed body to node-b is refused for co-location. Also after a
|
||||
// master restart, whose co-located set starts empty.
|
||||
func TestStrictReplaysAnIssuedMoveToANowColocatedTarget(t *testing.T) {
|
||||
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
|
||||
r := newIsolationRig(t, true, authorityDir, lifecycleDir)
|
||||
q, issued := r.issueMove(t, "moved", "m1") // the caller never sees this reply
|
||||
check := func(r *isolationRig, what string) {
|
||||
t.Helper()
|
||||
if err := r.heartbeat("node-b", masterStore); err != nil {
|
||||
t.Fatalf("%s: the issued move's target was refused: %v", what, err)
|
||||
}
|
||||
if !r.m.colocatedTargetRefused("node-b") {
|
||||
t.Fatalf("%s: node-b not recorded as co-located", what)
|
||||
}
|
||||
before, _ := r.m.Publisher().VolumeAuthorityLine("moved")
|
||||
again, err := r.ws.MoveWorkspace(r.ctx, q)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: retry of the issued request: %v, want its durable grant", what, err)
|
||||
}
|
||||
if !proto.Equal(again, issued) {
|
||||
t.Fatalf("%s: retry returned %+v, want the issued grant %+v", what, again, issued)
|
||||
}
|
||||
after, _ := r.m.Publisher().VolumeAuthorityLine("moved")
|
||||
if after != before || after.Epoch != issued.NewEpoch {
|
||||
t.Fatalf("%s: retry published again: line %+v -> %+v", what, before, after)
|
||||
}
|
||||
if st := r.m.Publisher().WorkspaceState("moved"); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued {
|
||||
t.Fatalf("%s: move journal after the retry: %+v", what, st)
|
||||
}
|
||||
fresh := proto.Clone(q).(*control.WorkspaceMove)
|
||||
fresh.RequestId = "m2"
|
||||
changed := proto.Clone(q).(*control.WorkspaceMove)
|
||||
changed.Kind, changed.Force = "forced", true
|
||||
for name, m := range map[string]*control.WorkspaceMove{"new request id": fresh, "same id, changed body": changed} {
|
||||
_, err := r.ws.MoveWorkspace(r.ctx, m)
|
||||
if status.Code(err) != codes.FailedPrecondition || status.Convert(err).Message() != colocatedMoveRefusal {
|
||||
t.Fatalf("%s: %s to the co-located node: %v, want %q", what, name, err, colocatedMoveRefusal)
|
||||
}
|
||||
}
|
||||
if final, _ := r.m.Publisher().VolumeAuthorityLine("moved"); final != before {
|
||||
t.Fatalf("%s: a refused request changed authority: %+v -> %+v", what, before, final)
|
||||
}
|
||||
}
|
||||
check(r, "live master")
|
||||
r.close(t)
|
||||
check(newIsolationRig(t, true, authorityDir, lifecycleDir), "restarted master")
|
||||
}
|
||||
|
||||
// The recorded placement repeated after its node turned out co-located keeps
|
||||
// its idempotent result; a different placement on that node is refused.
|
||||
func TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
r.createVolume(t, "fresh")
|
||||
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
place := &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"}
|
||||
if _, err := r.ws.PlaceWorkspace(r.ctx, place); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.heartbeat("node-b", masterStore); err != nil {
|
||||
t.Fatalf("the placed node was refused: %v", err)
|
||||
}
|
||||
if !r.m.colocatedTargetRefused("node-b") {
|
||||
t.Fatal("node-b not recorded as co-located")
|
||||
}
|
||||
if _, err := r.ws.PlaceWorkspace(r.ctx, place); err != nil {
|
||||
t.Fatalf("repeating the recorded placement: %v, want its idempotent result", err)
|
||||
}
|
||||
_, err := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r2"})
|
||||
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("a different placement on the co-located node: %v, want a co-location refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
// On a first start the authority store directory does not exist before
|
||||
// Bootstrap creates it. The master must sample the created directory: a
|
||||
// heartbeat carrying that file system's identity is co-located (alarm by
|
||||
// default, refusal under strict) without any test override.
|
||||
func TestFirstStartSamplesTheCreatedAuthorityStore(t *testing.T) {
|
||||
for _, strict := range []bool{false, true} {
|
||||
t.Run(map[bool]string{true: "strict", false: "default"}[strict], func(t *testing.T) {
|
||||
authorityDir := filepath.Join(t.TempDir(), "authority") // created by Bootstrap
|
||||
r := startIsolationRig(t, strict, authorityDir, t.TempDir(), nil)
|
||||
self := storeident.Of(authorityDir)
|
||||
if !self.Known() {
|
||||
t.Skip("file system identity is unknown on this platform")
|
||||
}
|
||||
err := r.heartbeat("node-a", self)
|
||||
if strict {
|
||||
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("strict heartbeat on the fresh store's file system: %v, want a co-location refusal", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("default heartbeat refused: %v", err)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), "node node-a "+colocatedLine) || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatalf("co-located node on the fresh store not detected:\n%s", r.logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A heartbeat never waits on the publisher lock, which writers hold across
|
||||
// durable writes: with a write held under that lock, the heartbeat of an
|
||||
// issued move's target (serving only through that move) completes at once,
|
||||
// and a co-located node that serves nothing is still refused at once.
|
||||
func TestStrictServingHeartbeatDoesNotWaitOnAHeldAuthorityWrite(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
r.issueMove(t, "moved", "m1")
|
||||
if p, _ := r.m.Lifecycle().Placements.GetPlacement("moved"); len(p.Slots) != 1 || p.Slots[0].ServerID != "node-a" {
|
||||
t.Fatalf("fixture: node-b must serve through the issued move only: %+v", p)
|
||||
}
|
||||
r.createVolume(t, "held")
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
held := make(chan error, 1)
|
||||
// RecordWorkspacePlacement holds the publisher lock across its durable
|
||||
// write, as an extension does across its authority fsync.
|
||||
go func() {
|
||||
held <- r.m.Publisher().RecordWorkspacePlacement(r.ctx, "held", func() error {
|
||||
close(entered)
|
||||
<-release
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
var beats sync.WaitGroup
|
||||
t.Cleanup(func() { // release first, then join every worker
|
||||
releaseOnce.Do(func() { close(release) })
|
||||
select {
|
||||
case <-held:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Error("held write did not settle")
|
||||
}
|
||||
beats.Wait()
|
||||
})
|
||||
select {
|
||||
case <-entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("the held write never started")
|
||||
}
|
||||
beat := func(server string) error {
|
||||
t.Helper()
|
||||
done := make(chan error, 1)
|
||||
start := time.Now()
|
||||
beats.Add(1)
|
||||
go func() { defer beats.Done(); done <- r.heartbeat(server, masterStore) }()
|
||||
select {
|
||||
case err := <-done:
|
||||
t.Logf("heartbeat of %s took %s with the authority write held", server, time.Since(start).Round(time.Millisecond))
|
||||
return err
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("heartbeat of %s still blocked %s behind the held authority write", server, time.Since(start).Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := beat("node-b"); err != nil {
|
||||
t.Fatalf("serving co-located node refused: %v", err)
|
||||
}
|
||||
if err := beat("node-c"); status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("idle co-located node: %v, want a co-location refusal", err)
|
||||
}
|
||||
}
|
||||
|
||||
// stalledStatusRequest opens a connection to the status endpoint and sends a
|
||||
// request whose declared body never comes.
|
||||
func stalledStatusRequest(t *testing.T, addr string) net.Conn {
|
||||
t.Helper()
|
||||
conn, err := net.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
if _, err := fmt.Fprintf(conn, "POST /status/workspace-lease HTTP/1.1\r\nHost: status\r\nContent-Length: 100\r\n\r\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
// readUntilClosed reads conn until the server closes it; it fails the test
|
||||
// when the connection is still open at deadline.
|
||||
func readUntilClosed(t *testing.T, conn net.Conn, deadline time.Time, what string) {
|
||||
t.Helper()
|
||||
if err := conn.SetReadDeadline(deadline); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err := io.Copy(io.Discard, conn)
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() {
|
||||
t.Fatalf("%s: the stalled status connection was still open at the deadline", what)
|
||||
}
|
||||
}
|
||||
|
||||
// A status client that declares a body and never sends it is cut off by the
|
||||
// read bound, not held open forever.
|
||||
func TestStatusEndpointCutsOffAStalledBody(t *testing.T) {
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: "127.0.0.1:0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
start := time.Now()
|
||||
conn := stalledStatusRequest(t, m.StatusAddr())
|
||||
readUntilClosed(t, conn, start.Add(statusReadTimeout+3*time.Second), "read bound")
|
||||
t.Logf("stalled body cut off after %s (bound %s)", time.Since(start).Round(time.Millisecond), statusReadTimeout)
|
||||
}
|
||||
|
||||
// When graceful shutdown runs out, Close force-closes the status connections
|
||||
// still open, long before their read bound would.
|
||||
func TestHostCloseForceClosesAStalledStatusConnection(t *testing.T) {
|
||||
logs := &syncBuffer{}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: "127.0.0.1:0", Logger: log.New(logs, "", 0)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
conn := stalledStatusRequest(t, m.StatusAddr())
|
||||
time.Sleep(200 * time.Millisecond) // the server has read the headers: the connection is active
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
if err := m.Close(ctx); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
readUntilClosed(t, conn, start.Add(2*time.Second), "Close")
|
||||
if took := time.Since(start); took >= statusReadTimeout-time.Second {
|
||||
t.Fatalf("connection closed after %s: that is the read bound, not Close", took)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "status graceful shutdown") {
|
||||
t.Fatalf("expired graceful shutdown not logged:\n%s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// The status endpoint carries the extension write latency: -1 before any
|
||||
// extension, then the measured write once a renewal past 1.25 TTL of
|
||||
// headroom (7.5 s after the first grant, TTL 30 s) has started one.
|
||||
func TestStatusReportsExtensionWriteLatency(t *testing.T) {
|
||||
h, c, _ := reviewBindingHost(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
reviewLegacyBind(t, h, c, ctx, "vol-b")
|
||||
line := waitAuthorityLine(t, h.Publisher(), "vol-b")
|
||||
svc := &services{host: h}
|
||||
id := &control.WorkspaceIdentity{VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
|
||||
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
|
||||
t.Fatal(err) // first grant: not an extension
|
||||
}
|
||||
get := func() map[string]any {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
h.statusHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/status/workspace-lease", nil))
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return body
|
||||
}
|
||||
if b := get(); b["extension_write_last_ms"] != float64(-1) || b["extension_write_max_last_minute_ms"] != float64(-1) {
|
||||
t.Fatalf("before any extension: %v", b)
|
||||
}
|
||||
time.Sleep(8 * time.Second)
|
||||
if _, err := svc.RenewWorkspaceLease(ctx, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) {
|
||||
b := get()
|
||||
last, _ := b["extension_write_last_ms"].(float64)
|
||||
max, _ := b["extension_write_max_last_minute_ms"].(float64)
|
||||
if last >= 0 && max >= last {
|
||||
t.Logf("extension write: last %v ms, max in the last minute %v ms", last, max)
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("no extension write reported: %v", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With a known file system id on both sides, machine id + device alone no
|
||||
// longer make a node co-located: a different fsid is another file system.
|
||||
// The same three facts are co-located; a heartbeat without an fsid (an older
|
||||
// volume binary) falls back to machine id + device.
|
||||
func TestColocationComparesFSIDWhenBothSidesKnowIt(t *testing.T) {
|
||||
self := storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0x1111}
|
||||
r := startIsolationRig(t, false, t.TempDir(), t.TempDir(), &self)
|
||||
for _, c := range []struct {
|
||||
server string
|
||||
id storeident.Identity
|
||||
want bool
|
||||
}{
|
||||
{"node-a", storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0x2222}, false},
|
||||
{"node-b", storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0x1111}, true},
|
||||
{"node-c", storeident.Identity{MachineID: "machine-1", Dev: 2049}, true},
|
||||
} {
|
||||
if err := r.heartbeat(c.server, c.id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := strings.Contains(r.logs.String(), "node "+c.server+" "+colocatedLine); got != c.want {
|
||||
t.Fatalf("%s reporting %+v: co-located alarm = %v, want %v\n%s", c.server, c.id, got, c.want, r.logs.String())
|
||||
}
|
||||
}
|
||||
if n := r.m.WorkspaceLeaseStatus().ColocatedNodes; n != 2 {
|
||||
t.Fatalf("colocated_nodes = %d, want 2", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/authority"
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
// masterStore is the identity the tests give the master's authority store
|
||||
// (the real one is platform-dependent: unknown on Windows).
|
||||
var masterStore = storeident.Identity{MachineID: "machine-1", Dev: 2049}
|
||||
|
||||
const colocatedLine = "shares the authority store's file system"
|
||||
|
||||
type isolationRig struct {
|
||||
m *Host
|
||||
logs *syncBuffer
|
||||
ws control.WorkspaceServiceClient
|
||||
lc control.LifecycleServiceClient
|
||||
obs control.ObservationServiceClient
|
||||
ctx context.Context
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newIsolationRig(t *testing.T, strict bool, authorityDir, lifecycleDir string) *isolationRig {
|
||||
t.Helper()
|
||||
return startIsolationRig(t, strict, authorityDir, lifecycleDir, &masterStore)
|
||||
}
|
||||
|
||||
// startIsolationRig starts the rig's master; self, when not nil, replaces the
|
||||
// identity the master sampled from its authority store.
|
||||
func startIsolationRig(t *testing.T, strict bool, authorityDir, lifecycleDir string, self *storeident.Identity) *isolationRig {
|
||||
t.Helper()
|
||||
logs := &syncBuffer{}
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: authorityDir, LifecycleStoreDir: lifecycleDir, WorkspaceRPC: true,
|
||||
StrictJournalIsolation: strict, Logger: log.New(logs, "", 0),
|
||||
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
|
||||
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if self != nil {
|
||||
m.journal.setSelf(*self) // before Start: no RPC has run yet
|
||||
}
|
||||
m.Start()
|
||||
r := &isolationRig{m: m, logs: logs}
|
||||
t.Cleanup(func() {
|
||||
if !r.closed {
|
||||
closeTestMaster(t, m)
|
||||
}
|
||||
})
|
||||
conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
for _, n := range []lifecycle.NodeRegistration{
|
||||
{ServerID: "node-a", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"},
|
||||
{ServerID: "node-b", DataAddr: "127.0.0.1:19301", CtrlAddr: "127.0.0.1:19302"},
|
||||
} {
|
||||
if _, err := m.Lifecycle().Nodes.RegisterNode(n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r.ws, r.lc, r.obs, r.ctx = control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn), control.NewObservationServiceClient(conn), ctx
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *isolationRig) close(t *testing.T) {
|
||||
t.Helper()
|
||||
r.closed = true
|
||||
closeTestMaster(t, r.m)
|
||||
}
|
||||
|
||||
var hbPorts = map[string][2]string{
|
||||
"node-a": {"127.0.0.1:19111", "127.0.0.1:19112"},
|
||||
"node-b": {"127.0.0.1:19311", "127.0.0.1:19312"},
|
||||
"node-c": {"127.0.0.1:19511", "127.0.0.1:19512"},
|
||||
}
|
||||
|
||||
func (r *isolationRig) heartbeat(server string, id storeident.Identity) error {
|
||||
_, err := r.obs.ReportHeartbeat(r.ctx, &control.HeartbeatReport{ServerId: server, SentAt: timestamppb.Now(), Reachable: true, Eligible: true,
|
||||
MachineId: id.MachineID, DurableRootDev: id.Dev, DurableRootFsid: id.FSID,
|
||||
Slots: []*control.HeartbeatSlot{{VolumeId: "hb-" + server, ReplicaId: "r-" + server, DataAddr: hbPorts[server][0], CtrlAddr: hbPorts[server][1]}}})
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *isolationRig) createVolume(t *testing.T, vol string) {
|
||||
t.Helper()
|
||||
if _, err := r.lc.CreateVolume(r.ctx, &control.CreateVolumeRequest{VolumeId: vol, SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *isolationRig) place(t *testing.T, vol, server string) {
|
||||
t.Helper()
|
||||
if _, err := r.m.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: vol, DesiredRF: 1,
|
||||
Candidates: []lifecycle.PlacementCandidate{{VolumeID: vol, ServerID: server, ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Default (not strict): a node on the authority store's file system is
|
||||
// alarmed once and counted, and its heartbeats are accepted. A different
|
||||
// device, or a different machine with the same device number, is silent.
|
||||
func TestColocatedNodeIsAlarmedButAcceptedByDefault(t *testing.T) {
|
||||
r := newIsolationRig(t, false, t.TempDir(), t.TempDir())
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := r.heartbeat("node-a", masterStore); err != nil {
|
||||
t.Fatalf("heartbeat %d of the co-located node refused without strict isolation: %v", i, err)
|
||||
}
|
||||
}
|
||||
want := "blockmaster: node node-a shares the authority store's file system (machine machine-1, dev 2049): its fsyncs share the authority journal"
|
||||
if n := strings.Count(r.logs.String(), want); n != 1 {
|
||||
t.Fatalf("alarm logged %d times, want once:\n%s", n, r.logs.String())
|
||||
}
|
||||
if got := r.m.WorkspaceLeaseStatus().ColocatedNodes; got != 1 {
|
||||
t.Fatalf("colocated_nodes = %d, want 1", got)
|
||||
}
|
||||
for _, id := range []storeident.Identity{
|
||||
{MachineID: "machine-1", Dev: 2050}, // same machine, other file system
|
||||
{MachineID: "machine-2", Dev: 2049}, // same device number, other machine
|
||||
{}, // unknown
|
||||
} {
|
||||
if err := r.heartbeat("node-b", id); err != nil {
|
||||
t.Fatalf("heartbeat %+v: %v", id, err)
|
||||
}
|
||||
}
|
||||
if strings.Contains(r.logs.String(), "node node-b "+colocatedLine) {
|
||||
t.Fatalf("node-b alarmed:\n%s", r.logs.String())
|
||||
}
|
||||
if got := r.m.WorkspaceLeaseStatus().ColocatedNodes; got != 1 {
|
||||
t.Fatalf("colocated_nodes = %d after silent nodes, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A node that moves its durable root off the authority store's file system
|
||||
// leaves the co-located set on its next heartbeat: strict isolation accepts
|
||||
// it again and no longer refuses new work on it.
|
||||
func TestColocatedNodeLeavesTheSetWhenItMovesOff(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
if err := r.heartbeat("node-a", masterStore); status.Code(err) != codes.FailedPrecondition {
|
||||
t.Fatalf("strict heartbeat of a co-located new node: %v, want FailedPrecondition", err)
|
||||
}
|
||||
if !r.m.colocatedTargetRefused("node-a") || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatal("co-located node not recorded")
|
||||
}
|
||||
if err := r.heartbeat("node-a", storeident.Identity{MachineID: "machine-1", Dev: 2050}); err != nil {
|
||||
t.Fatalf("strict refused the node after it moved off the store's file system: %v", err)
|
||||
}
|
||||
if r.m.colocatedTargetRefused("node-a") || r.m.WorkspaceLeaseStatus().ColocatedNodes != 0 {
|
||||
t.Fatal("node still counted as co-located after it moved off")
|
||||
}
|
||||
}
|
||||
|
||||
// Strict: a co-located node that serves no volume is refused
|
||||
// (FailedPrecondition) and still alarmed; a node elsewhere is accepted.
|
||||
func TestStrictRefusesColocatedNodeWithoutVolumes(t *testing.T) {
|
||||
r := newIsolationRig(t, true, t.TempDir(), t.TempDir())
|
||||
err := r.heartbeat("node-a", masterStore)
|
||||
if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), colocatedLine) {
|
||||
t.Fatalf("strict heartbeat of a co-located new node: %v, want FailedPrecondition naming the shared file system", err)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), "node node-a "+colocatedLine) || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatalf("refused node not alarmed/counted:\n%s", r.logs.String())
|
||||
}
|
||||
if err := r.heartbeat("node-b", storeident.Identity{MachineID: "machine-1", Dev: 2050}); err != nil {
|
||||
t.Fatalf("strict refused a node on another file system: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Strict: a co-located node that already serves a volume keeps getting its
|
||||
// heartbeats accepted (alarm only), also after a master restart: "serves" is
|
||||
// read from durable state, not from what this process has seen.
|
||||
func TestStrictAcceptsColocatedNodeThatAlreadyServes(t *testing.T) {
|
||||
authorityDir, lifecycleDir := t.TempDir(), t.TempDir()
|
||||
r := newIsolationRig(t, true, authorityDir, lifecycleDir)
|
||||
r.createVolume(t, "placed")
|
||||
r.place(t, "placed", "node-a")
|
||||
if err := r.heartbeat("node-a", masterStore); err != nil {
|
||||
t.Fatalf("strict refused a co-located node that serves a volume: %v", err)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), "node node-a "+colocatedLine) || r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatalf("serving co-located node not alarmed:\n%s", r.logs.String())
|
||||
}
|
||||
r.close(t)
|
||||
|
||||
again := newIsolationRig(t, true, authorityDir, lifecycleDir)
|
||||
if err := again.heartbeat("node-a", masterStore); err != nil {
|
||||
t.Fatalf("after a master restart, strict refused the serving co-located node: %v", err)
|
||||
}
|
||||
if !strings.Contains(again.logs.String(), "node node-a "+colocatedLine) {
|
||||
t.Fatalf("restarted master did not alarm:\n%s", again.logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Strict refuses a new placement or move onto a co-located node; without
|
||||
// strict neither is refused for that reason.
|
||||
func TestStrictRefusesPlacementAndMoveOntoColocatedNode(t *testing.T) {
|
||||
for _, strict := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "strict", false: "default"}[strict], func(t *testing.T) {
|
||||
r := newIsolationRig(t, strict, t.TempDir(), t.TempDir())
|
||||
_ = r.heartbeat("node-b", masterStore) // strict refuses it (no volume); both modes record it
|
||||
if r.m.WorkspaceLeaseStatus().ColocatedNodes != 1 {
|
||||
t.Fatal("node-b not recorded as co-located")
|
||||
}
|
||||
r.createVolume(t, "placed")
|
||||
r.place(t, "placed", "node-a")
|
||||
r.createVolume(t, "fresh")
|
||||
if _, err := r.ws.RegisterWorkspaceBinding(r.ctx, &control.WorkspaceBinding{VolumeId: "fresh", ServerId: "node-b", DataAddr: "127.0.0.1:19321", CtrlAddr: "127.0.0.1:19322"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, placeErr := r.ws.PlaceWorkspace(r.ctx, &control.WorkspacePlacement{VolumeId: "fresh", ServerId: "node-b", ReplicaId: "r1"})
|
||||
_, moveErr := r.ws.MoveWorkspace(r.ctx, &control.WorkspaceMove{RequestId: "m1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1",
|
||||
TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "clean"})
|
||||
if strict {
|
||||
if status.Code(placeErr) != codes.FailedPrecondition || !strings.Contains(status.Convert(placeErr).Message(), colocatedLine) {
|
||||
t.Fatalf("strict PlaceWorkspace onto a co-located node: %v", placeErr)
|
||||
}
|
||||
if _, ok := r.m.Lifecycle().Placements.GetPlacement("fresh"); ok {
|
||||
t.Fatal("refused placement was recorded")
|
||||
}
|
||||
want := `move target node "node-b" shares the authority store's file system (strict journal isolation)`
|
||||
if status.Code(moveErr) != codes.FailedPrecondition || status.Convert(moveErr).Message() != want {
|
||||
t.Fatalf("strict MoveWorkspace onto a co-located node: %v, want %q", moveErr, want)
|
||||
}
|
||||
if !strings.Contains(r.logs.String(), `MoveWorkspace refused volume="placed" request="m1": `+want) {
|
||||
t.Fatalf("move refusal not logged:\n%s", r.logs.String())
|
||||
}
|
||||
return
|
||||
}
|
||||
if placeErr != nil {
|
||||
t.Fatalf("default PlaceWorkspace onto a co-located node refused: %v", placeErr)
|
||||
}
|
||||
if moveErr != nil && strings.Contains(moveErr.Error(), colocatedLine) {
|
||||
t.Fatalf("default MoveWorkspace refused for co-location: %v", moveErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Strict: the product loop never creates a new placement on a co-located
|
||||
// node (the only node with capacity here); without strict it does.
|
||||
func TestStrictProductLoopSkipsColocatedNodeForNewPlacement(t *testing.T) {
|
||||
for _, strict := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "strict", false: "default"}[strict], func(t *testing.T) {
|
||||
r := newIsolationRig(t, strict, t.TempDir(), t.TempDir())
|
||||
if _, err := r.m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-c", DataAddr: "127.0.0.1:19501", CtrlAddr: "127.0.0.1:19502",
|
||||
Pools: []lifecycle.StoragePool{{PoolID: "p1", TotalBytes: 1 << 30, FreeBytes: 1 << 30, BlockSize: 4096}}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = r.heartbeat("node-c", masterStore)
|
||||
r.createVolume(t, "auto")
|
||||
if _, err := r.m.RunLifecycleProductTick(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, ok := r.m.Lifecycle().Placements.GetPlacement("auto")
|
||||
if strict && ok {
|
||||
t.Fatalf("strict product loop placed a new volume on the co-located node: %+v", p)
|
||||
}
|
||||
if !strict && (!ok || p.Slots[0].ServerID != "node-c") {
|
||||
t.Fatalf("default product loop did not place on node-c: %+v ok=%v", p, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The status endpoint is loopback-only and serves the counters as JSON.
|
||||
func TestStatusEndpointLoopbackOnlyAndServesJSON(t *testing.T) {
|
||||
for _, bad := range []string{"0.0.0.0:9335", ":9335", "10.0.0.5:9335", "[::]:9335", "example.com:9335"} {
|
||||
if err := ValidateStatusListen(bad); err == nil {
|
||||
t.Fatalf("ValidateStatusListen(%q) accepted a non-loopback address", bad)
|
||||
}
|
||||
if _, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: bad}); err == nil || !strings.Contains(err.Error(), "loopback") {
|
||||
t.Fatalf("master.New with --status-listen %q: %v, want a loopback refusal", bad, err)
|
||||
}
|
||||
}
|
||||
for _, ok := range []string{"", "127.0.0.1:9335", "127.1.2.3:0", "[::1]:9335", "localhost:9335"} {
|
||||
if err := ValidateStatusListen(ok); err != nil {
|
||||
t.Fatalf("ValidateStatusListen(%q): %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
m, err := New(Config{Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), StatusListen: "127.0.0.1:0", StrictJournalIsolation: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Start()
|
||||
defer closeTestMaster(t, m)
|
||||
resp, err := http.Get("http://" + m.StatusAddr() + "/status/workspace-lease")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "application/json" {
|
||||
t.Fatalf("status %d content-type %q", resp.StatusCode, resp.Header.Get("Content-Type"))
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range []string{"colocated_nodes", "headroom_alarms", "clamps_total", "clamps_last_minute", "min_headroom_ms", "strict_journal_isolation",
|
||||
"extension_write_last_ms", "extension_write_max_last_minute_ms"} {
|
||||
if _, ok := body[k]; !ok {
|
||||
t.Fatalf("status JSON lacks %q: %v", k, body)
|
||||
}
|
||||
}
|
||||
if body["strict_journal_isolation"] != true || body["colocated_nodes"] != float64(0) || body["min_headroom_ms"] != float64(-1) ||
|
||||
body["extension_write_last_ms"] != float64(-1) || body["extension_write_max_last_minute_ms"] != float64(-1) {
|
||||
t.Fatalf("status JSON values: %v", body)
|
||||
}
|
||||
if post, err := http.Post("http://"+m.StatusAddr()+"/status/workspace-lease", "application/json", nil); err != nil || post.StatusCode != http.StatusMethodNotAllowed {
|
||||
t.Fatalf("POST: %v %v", post, err)
|
||||
} else {
|
||||
post.Body.Close()
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,9 @@ func (h *Host) RunLifecycleProductTick() (LifecycleProductTickResult, error) {
|
||||
return LifecycleProductTickResult{}, nil
|
||||
}
|
||||
nodes := stores.Nodes.ListNodes()
|
||||
reconciled := lifecycle.ReconcilePlacement(stores.liveVolumes(), nodes, stores.Placements)
|
||||
// New placements never choose a co-located node under strict journal
|
||||
// isolation; existing placements still verify against every node.
|
||||
reconciled := h.reconcilePlacements(stores, nodes)
|
||||
placements := stores.Placements.ListPlacements()
|
||||
verified := h.verifyPlacements(placements, nodes)
|
||||
result := LifecycleProductTickResult{
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/lifecycle"
|
||||
"github.com/seaweedfs/seaweed-block/core/ops"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
@@ -285,6 +286,12 @@ func (s *services) ReportHeartbeat(ctx context.Context, r *control.HeartbeatRepo
|
||||
if err := validateHeartbeat(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Journal isolation: alarm on a durable root sharing the authority
|
||||
// store's file system; under strict isolation refuse it unless the node
|
||||
// already serves volumes (refusing a serving node stops its renewals).
|
||||
if err := s.host.refuseColocatedHeartbeat(r.ServerId, storeident.Identity{MachineID: r.GetMachineId(), Dev: r.GetDurableRootDev(), FSID: r.GetDurableRootFsid()}); err != nil {
|
||||
return nil, status.Error(codes.FailedPrecondition, err.Error())
|
||||
}
|
||||
msg := heartbeatFromWire(r)
|
||||
if err := s.host.ingestHeartbeatRecordingHealth(msg); err != nil {
|
||||
return nil, fmt.Errorf("ingest: %w", err)
|
||||
|
||||
@@ -136,9 +136,17 @@ func (s *services) PlaceWorkspace(ctx context.Context, q *control.WorkspacePlace
|
||||
if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok {
|
||||
return nil, workspaceError(fmt.Errorf("workspace placement: unknown server"))
|
||||
}
|
||||
identical := func(p lifecycle.PlacementIntent) bool {
|
||||
return len(p.Slots) == 1 && p.Slots[0].ServerID == binding.ServerID && p.Slots[0].ReplicaID == q.GetReplicaId() && p.Slots[0].DataAddr == binding.DataAddr && p.Slots[0].CtrlAddr == binding.CtrlAddr
|
||||
}
|
||||
// Strict journal isolation refuses new work only: repeating the
|
||||
// recorded placement keeps its idempotent result.
|
||||
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); !(ok && identical(p)) && s.host.colocatedTargetRefused(binding.ServerID) {
|
||||
return nil, workspaceError(fmt.Errorf("workspace placement: node %q shares the authority store's file system (strict journal isolation)", binding.ServerID))
|
||||
}
|
||||
err = s.host.Publisher().RecordWorkspacePlacement(ctx, q.GetVolumeId(), func() error {
|
||||
if p, ok := s.host.lifecycle.Placements.GetPlacement(q.GetVolumeId()); ok {
|
||||
if len(p.Slots) == 1 && p.Slots[0].ServerID == binding.ServerID && p.Slots[0].ReplicaID == q.GetReplicaId() && p.Slots[0].DataAddr == binding.DataAddr && p.Slots[0].CtrlAddr == binding.CtrlAddr {
|
||||
if identical(p) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("workspace placement: existing intent differs")
|
||||
|
||||
@@ -2,6 +2,8 @@ package master
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -234,6 +236,10 @@ func TestWorkspaceBindingChosenObservationMustMatchServerAndPair(t *testing.T) {
|
||||
}
|
||||
|
||||
// The ACK must complete while the unrelated remote reader/prober remains held.
|
||||
// errHeldNotJoined: the held remote operation's worker did not return within
|
||||
// its own bound after being released.
|
||||
var errHeldNotJoined = errors.New("held remote operation not joined")
|
||||
|
||||
func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) {
|
||||
for _, mode := range []string{"head", "promotion"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
@@ -257,12 +263,44 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
var releaseOnce sync.Once
|
||||
releaseHeld := func() { releaseOnce.Do(func() { close(release) }) }
|
||||
// Registered before either worker launches: every exit releases the
|
||||
// held call, and a worker that was launched is joined under its own
|
||||
// bound, not under the fixture context a blocked ACK has already
|
||||
// used up. A setup failure before the launch joins nothing.
|
||||
launched := false
|
||||
launch := func(worker func() error) {
|
||||
launched = true
|
||||
go func() { done <- worker() }()
|
||||
}
|
||||
var joinOnce sync.Once
|
||||
var joined error
|
||||
join := func() error {
|
||||
if !launched {
|
||||
return nil
|
||||
}
|
||||
joinOnce.Do(func() {
|
||||
select {
|
||||
case joined = <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
joined = errHeldNotJoined
|
||||
}
|
||||
})
|
||||
return joined
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
releaseHeld()
|
||||
if err := join(); errors.Is(err, errHeldNotJoined) {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
if mode == "head" {
|
||||
reviewLegacyBind(t, h, c, ctx, "probe")
|
||||
go func() {
|
||||
launch(func() error {
|
||||
_, e := client.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "held", VolumeId: "probe", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:9200", TargetCtrlAddr: "127.0.0.1:9100", Kind: "clean"})
|
||||
done <- e
|
||||
}()
|
||||
return e
|
||||
})
|
||||
} else {
|
||||
if _, e := h.Lifecycle().Volumes.CreateVolume(lifecycle.VolumeSpec{VolumeID: "vol-rf3", SizeBytes: 1 << 20, ReplicationFactor: 3}); e != nil {
|
||||
t.Fatal(e)
|
||||
@@ -275,21 +313,21 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) {
|
||||
waitAuthorityLine(t, h.Publisher(), "vol-rf3")
|
||||
ingestRF3Observation(t, h, false, true, true)
|
||||
h.SetPromotionEvidenceProvider(reviewHeldPromotion{arrived, release})
|
||||
go func() { _, e := h.RunLifecycleProductTick(); done <- e }()
|
||||
launch(func() error { _, e := h.RunLifecycleProductTick(); return e })
|
||||
}
|
||||
select {
|
||||
case <-arrived:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("remote call not reached", ctx.Err())
|
||||
}
|
||||
ackCtx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
_, e := client.AckWorkspaceRevoked(ackCtx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9})
|
||||
cancel()
|
||||
close(release)
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("remote operation did not finish", ctx.Err())
|
||||
// The held remote call is released only after the ACK returns, so an
|
||||
// ACK that waited for it would run into the test's own deadline. No
|
||||
// separate 1 s bound: the ACK includes a durable persist, which a
|
||||
// loaded host can slow past that without anything being blocked.
|
||||
_, e := client.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9})
|
||||
releaseHeld()
|
||||
if err := join(); errors.Is(err, errHeldNotJoined) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e != nil {
|
||||
t.Fatal("held remote operation blocked ACK", e)
|
||||
|
||||
@@ -189,6 +189,12 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
matched = true
|
||||
}
|
||||
}
|
||||
req := authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID,
|
||||
ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()}
|
||||
// Strict journal isolation refuses new work only: an exact replay of an
|
||||
// issued move (its reply lost, the target found co-located since) gets
|
||||
// its durable grant back from MoveWorkspace, never a definite refusal.
|
||||
replay := ok && s.host.Publisher().IssuedWorkspaceMove(req)
|
||||
switch {
|
||||
case endpointErr != nil:
|
||||
refusal = fmt.Sprintf("move target endpoints invalid: %v", endpointErr)
|
||||
@@ -198,6 +204,8 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId())
|
||||
case target.ServerID == oldHost:
|
||||
refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID)
|
||||
case !replay && s.host.colocatedTargetRefused(target.ServerID):
|
||||
refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
|
||||
case !matched:
|
||||
refusal = fmt.Sprintf("move target endpoints %s/%s on %q are not registered (%s)", q.GetTargetDataAddr(), q.GetTargetCtrlAddr(), target.ServerID, registeredTargetEndpoints(target, bindings, explicit))
|
||||
}
|
||||
@@ -207,8 +215,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove)
|
||||
if err = s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
r, err := s.host.Publisher().MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: q.GetRequestId(), VolumeID: q.GetVolumeId(), ExpectedReplicaID: q.GetExpectedReplicaId(), ExpectedHost: oldHost, TargetHost: target.ServerID,
|
||||
ExpectedEpoch: q.GetExpectedEpoch(), TargetReplicaID: q.GetTargetReplicaId(), TargetDataAddr: q.GetTargetDataAddr(), TargetCtrlAddr: q.GetTargetCtrlAddr(), Kind: q.GetKind(), Force: q.GetForce()}, head)
|
||||
r, err := s.host.Publisher().MoveWorkspace(ctx, req, head)
|
||||
if err != nil {
|
||||
return nil, workspaceError(err)
|
||||
}
|
||||
|
||||
@@ -162,4 +162,17 @@ func TestWorkspaceRPCCleanMovePreservesReplicaIdentity(t *testing.T) {
|
||||
if state := restarted.Publisher().WorkspaceState("vol-a"); state == nil || len(state.Moves) != 1 || !state.Moves[0].Issued {
|
||||
t.Fatal(state)
|
||||
}
|
||||
// Journal isolation reads "serves" from durable state: the issued move's
|
||||
// target serves vol-a through its authority line alone (the placement
|
||||
// still names the old node), also on a restarted master.
|
||||
if p, ok := restarted.Lifecycle().Placements.GetPlacement("vol-a"); ok {
|
||||
for _, slot := range p.Slots {
|
||||
if slot.ServerID == "node-b" {
|
||||
t.Fatalf("placement already names the move target: %+v", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !restarted.nodeServesVolumes("node-b") {
|
||||
t.Fatal("the issued move's target does not count as serving vol-a")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/seaweedfs/seaweed-block/core/engine"
|
||||
"github.com/seaweedfs/seaweed-block/core/replication"
|
||||
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/protobuf/proto"
|
||||
@@ -72,6 +73,12 @@ type Config struct {
|
||||
// readiness is installed, and latched like a failed role admission.
|
||||
RF1Only string
|
||||
|
||||
// StorageIdentity identifies the file system of the durable root
|
||||
// (machine id + st_dev + statfs f_fsid), reported in every heartbeat so the master can
|
||||
// detect a durable root that shares the authority store's journal. Zero
|
||||
// means unknown (memback, non-unix, or the root could not be read).
|
||||
StorageIdentity storeident.Identity
|
||||
|
||||
// ReplicationVolume, when non-nil, receives peer-set updates on
|
||||
// every self-replica AssignmentFact. The Host calls
|
||||
// UpdateReplicaSet(peer_set_generation, targets) BEFORE
|
||||
@@ -639,6 +646,10 @@ func (h *Host) buildReport() *control.HeartbeatReport {
|
||||
SentAt: timestamppb.Now(),
|
||||
Reachable: true,
|
||||
Eligible: true,
|
||||
// Raw identity facts; the master compares them with its own store.
|
||||
MachineId: h.cfg.StorageIdentity.MachineID,
|
||||
DurableRootDev: h.cfg.StorageIdentity.Dev,
|
||||
DurableRootFsid: h.cfg.StorageIdentity.FSID,
|
||||
Slots: []*control.HeartbeatSlot{
|
||||
{
|
||||
VolumeId: h.cfg.VolumeID,
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storeident"
|
||||
)
|
||||
|
||||
// Every heartbeat carries the durable root's file-system identity as raw
|
||||
// facts, so the master can detect a root on its authority store's journal.
|
||||
// An unconfigured identity reports zero (unknown).
|
||||
func TestBuildReportCarriesStorageIdentity(t *testing.T) {
|
||||
h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "node-a", VolumeID: "v1", ReplicaID: "r1",
|
||||
DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101",
|
||||
StorageIdentity: storeident.Identity{MachineID: "machine-1", Dev: 2049, FSID: 0xfeed}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = h.Close() }()
|
||||
r := h.buildReport()
|
||||
if r.GetMachineId() != "machine-1" || r.GetDurableRootDev() != 2049 || r.GetDurableRootFsid() != 0xfeed {
|
||||
t.Fatalf("report identity = (%q, %d, %#x), want (machine-1, 2049, 0xfeed)", r.GetMachineId(), r.GetDurableRootDev(), r.GetDurableRootFsid())
|
||||
}
|
||||
|
||||
plain := newTestVolumeHost(t)
|
||||
defer func() { _ = plain.Close() }()
|
||||
if r := plain.buildReport(); r.GetMachineId() != "" || r.GetDurableRootDev() != 0 {
|
||||
t.Fatalf("unconfigured identity reported (%q, %d), want unknown", r.GetMachineId(), r.GetDurableRootDev())
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -116,6 +116,17 @@ message HeartbeatReport {
|
||||
bool reachable = 3;
|
||||
bool eligible = 4;
|
||||
repeated HeartbeatSlot slots = 5;
|
||||
// machine_id and durable_root_dev identify the file system of the
|
||||
// reporting process's durable root (the machine's /etc/machine-id and
|
||||
// the root's st_dev). Raw observation facts: the master compares them
|
||||
// with its own authority store to detect a shared file system (one
|
||||
// journal). Empty / 0 means unknown and is never compared.
|
||||
string machine_id = 6;
|
||||
uint64 durable_root_dev = 7;
|
||||
// durable_root_fsid is the durable root's statfs f_fsid (high word
|
||||
// first). 0 means unknown (older reporters, platforms without statfs):
|
||||
// the master then compares machine_id and durable_root_dev only.
|
||||
uint64 durable_root_fsid = 8;
|
||||
}
|
||||
|
||||
// HeartbeatSlot — per-replica slot fact. local_role_claim is the
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestBlockMetadata_DurableBeforeTail(t *testing.T) {
|
||||
}
|
||||
cp, tail := s.CheckpointLSN(), walLogicalTail(s)
|
||||
h.before = func(uint64) {
|
||||
if s.checkpointLSN != cp || s.wal.logicalTail != tail {
|
||||
if s.checkpointLSN != cp || s.v3.pub.current().RetainedTail != tail {
|
||||
t.Error("tail/checkpoint advanced before hook durability")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,13 +39,6 @@ func (l *chunkLayerImpl) holdBaseTransitionV3() (func(), error) {
|
||||
d := l.s.v3.pub.current()
|
||||
l.noteAllMutated()
|
||||
l.stMu.Lock()
|
||||
l.reconcileGen++
|
||||
if l.reconciled != nil {
|
||||
close(l.reconciled)
|
||||
l.reconciled = nil
|
||||
}
|
||||
l.reconcile = map[uint64]bool{}
|
||||
l.hashMode = false
|
||||
l.allDirty = true
|
||||
l.dirtyVer++
|
||||
switch d.BaseState {
|
||||
|
||||
@@ -9,11 +9,7 @@ func (l *chunkLayerImpl) captureBirths(candidates map[uint64]bool, frontier uint
|
||||
l.s.mu.RLock()
|
||||
defer l.s.mu.RUnlock()
|
||||
for idx := range candidates {
|
||||
birth := frontier
|
||||
if l.usesOwnedMapV3() {
|
||||
birth = min(l.s.v3.mapEntries[idx].LSN, frontier)
|
||||
}
|
||||
out[idx] = birth
|
||||
out[idx] = min(l.s.v3.mapEntries[idx].LSN, frontier)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -28,7 +28,7 @@ func BenchmarkCaptureBirthsMaxVolumeDefaultChunk(b *testing.B) {
|
||||
}
|
||||
}
|
||||
func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) {
|
||||
s := &WALStore{}
|
||||
s := &WALStore{v3: &walStoreV3State{mapEntries: []chunkLSNEntryV3{{LSN: 7}}, mapProof: newMapProofEpochV3()}}
|
||||
l := &chunkLayerImpl{s: s}
|
||||
candidates := map[uint64]bool{0: true}
|
||||
s.mu.Lock()
|
||||
@@ -57,7 +57,7 @@ func TestCaptureBirthsIncludesStoreLockWait(t *testing.T) {
|
||||
case out := <-done:
|
||||
done <- out
|
||||
if out[0] != 7 {
|
||||
t.Fatal("legacy frontier changed")
|
||||
t.Fatal("native image frontier changed")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("sampler did not finish after lock release")
|
||||
|
||||
@@ -2,77 +2,9 @@ package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChunkBirthMigrationCarriesImageFrontier(t *testing.T) {
|
||||
s, path := newChunkTestStore(t)
|
||||
d := s.v3.pub.current()
|
||||
mapPath := s.v3.ownedMap.fd.Name()
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := MigrationSourceV3{UUID: d.UUID, VolumeSize: d.VolumeSize, ExtentSize: d.ExtentSize, BlockSize: d.BlockSize, OldWALOffset: 4096, OldWALSize: d.WALSize + 4096, CreatedAt: d.CreatedAt, CheckpointLSN: 7, ChunkBlocks: ctChunkBlocks}
|
||||
plan, err := PrepareMigrationV3(mapPath, src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fd, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { fd.Close() })
|
||||
// Actual offline migration's map and slot encoder, on a small flushed
|
||||
// image. No legacy engine or fabricated in-memory owned-map entries.
|
||||
for _, part := range []struct {
|
||||
offset int64
|
||||
data []byte
|
||||
}{{MigrationSlotBOffset, plan.PreparedB}, {MigrationSlotAOffset, plan.CommittedA}, {MigrationSlotBOffset, plan.RolloverB}} {
|
||||
if _, err := fd.WriteAt(part.data, part.offset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want := makeBlock(ctBlockSize, 0x57)
|
||||
if _, err := fd.WriteAt(want, int64(d.WALOffset+d.WALSize)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := OpenWALStoreWithOptions(path, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { closeBounded(t, r) })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f := newFakeChunkRemote()
|
||||
l := mustAttach(t, r, f, ctConfig(1))
|
||||
newest, err := r.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x41))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cut.Head.Chunks[0].BirthLSN != 7 || cut.Head.Chunks[1].BirthLSN != newest {
|
||||
t.Fatalf("migrated image birth lost: %+v", cut.Head)
|
||||
}
|
||||
if !bytes.Equal(f.imageOf(t, cut.Head)[:ctBlockSize], want) {
|
||||
t.Fatal("migration cut changed inherited bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
if err := s.SeedChunkFrontier(7); err != nil {
|
||||
@@ -96,4 +28,9 @@ func TestChunkBirthSeededFrontierPreservesInheritedImage(t *testing.T) {
|
||||
if cut.Head.Chunks[1].BirthLSN != 7 || cut.Head.Chunks[0].BirthLSN != newest {
|
||||
t.Fatalf("seeded image birth lost: %+v", cut.Head)
|
||||
}
|
||||
want := bytes.Clone(image)
|
||||
copy(want, makeBlock(ctBlockSize, 0x41))
|
||||
if !bytes.Equal(f.imageOf(t, cut.Head), want) {
|
||||
t.Fatal("seeded cut changed inherited or appended bytes")
|
||||
}
|
||||
}
|
||||
@@ -8,33 +8,6 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestChunkBirthLegacyEngineUsesCutFrontierUpperBound(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
l := mustAttach(t, s, f, cfg)
|
||||
if _, err := s.Write(0, makeBlock(ctBlockSize, 0x41)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last, err := s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x42))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cut, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, idx := range []uint64{0, 1} {
|
||||
if cr := cut.Head.Chunks[idx]; cr.Encoding != "full" || cr.BirthLSN != last {
|
||||
t.Fatalf("legacy chunk %d metadata %+v, want frontier %d", idx, cr, last)
|
||||
}
|
||||
}
|
||||
want := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(want, makeBlock(ctBlockSize, 0x41))
|
||||
copy(want[ctChunkBlocks*ctBlockSize:], makeBlock(ctBlockSize, 0x42))
|
||||
assertImage(t, "legacy inherited image", f.imageOf(t, cut.Head), want)
|
||||
}
|
||||
|
||||
func TestChunkBirthBASEUsesInheritedFrontierIncludingZero(t *testing.T) {
|
||||
for _, frontier := range []uint64{0, 7} {
|
||||
t.Run(string(rune('0'+frontier)), func(t *testing.T) {
|
||||
|
||||
@@ -3,63 +3,10 @@ package storage
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLegacyC11FileCodec_RoundTripAndReopen(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "vol.chunkbitmap")
|
||||
b := newLegacyC11FileStore(path)
|
||||
if _, _, ok, err := b.Load(); ok || err != nil {
|
||||
t.Fatalf("empty store: ok %v err %v", ok, err)
|
||||
}
|
||||
if err := b.Save([]uint64{3, 7}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.WriteHeader(chunkBitmapHeader{Base: chunkBaseInstalling}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hdr, dirty, ok, err := b.Load()
|
||||
if !ok || err != nil || hdr.Base != chunkBaseInstalling || !reflect.DeepEqual(dirty, []uint64{3, 7}) {
|
||||
t.Fatalf("after Save+WriteHeader: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty)
|
||||
}
|
||||
want := chunkBitmapHeader{BaseLSN: 40, HeadGen: 3, Epoch: 2}
|
||||
delta := chunkDelta{FromLSN: 10, ToLSN: 40, Gen: 3, Dirty: []uint64{3}, NewKeys: map[uint64]string{3: "k3"}}
|
||||
if err := b.Reset(want, []uint64{7}, delta); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A new instance reads exactly the durable state.
|
||||
b2 := newLegacyC11FileStore(path)
|
||||
hdr, dirty, ok, err = b2.Load()
|
||||
if !ok || err != nil || hdr != want || !reflect.DeepEqual(dirty, []uint64{7}) {
|
||||
t.Fatalf("reopened: ok %v err %v hdr %+v dirty %v", ok, err, hdr, dirty)
|
||||
}
|
||||
deltas, err := b2.Deltas()
|
||||
if err != nil || len(deltas) != 1 || !reflect.DeepEqual(deltas[0], delta) {
|
||||
t.Fatalf("delta log: %v %+v", err, deltas)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyC11FileCodec_CorruptStateIsLost(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "vol.chunkbitmap")
|
||||
b := newLegacyC11FileStore(path)
|
||||
if err := b.Save([]uint64{1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw[len(raw)/2] ^= 0xFF // one flipped byte
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, ok, err := newLegacyC11FileStore(path).Load(); ok || err != nil {
|
||||
t.Fatalf("corrupt state: ok %v err %v, want ok=false (hash-compare fallback) and no error", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The mapped layer and the in-memory remote: after a crash the owned map
|
||||
// makes the first cut incremental and exact, without a C11 file sidecar.
|
||||
func TestChunkLayer_OwnedMapIncrementalAfterRestart(t *testing.T) {
|
||||
|
||||
@@ -439,12 +439,7 @@ func (l *chunkLayerImpl) readCOWChunk(w *cutCOWWindow, idx uint64) ([]byte, []ui
|
||||
// write of the block waits for the caller's COW entry.
|
||||
func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte) ([]byte, bool, error) {
|
||||
s := l.s
|
||||
if s.v3 != nil {
|
||||
if data, handled, err := s.readDirtyV3Into(uint32(lba), dst, func() { w.walReads.Add(1) }); handled {
|
||||
return data, err == nil, err
|
||||
}
|
||||
} else if walRelOff, dataOffset, _, _, ok := s.dm.get(lba); ok {
|
||||
data, err := s.readFromWAL(walRelOff, dataOffset)
|
||||
if data, handled, err := s.readDirtyV3Into(uint32(lba), dst, func() { w.walReads.Add(1) }); handled {
|
||||
return data, err == nil, err
|
||||
}
|
||||
idx := l.chunkOf(lba)
|
||||
|
||||
@@ -114,9 +114,7 @@ func (l *chunkLayerImpl) stagePayloadRound(ctx context.Context, batch []uint64,
|
||||
// This cache belongs to one layer/owner lifetime. Generation equality is not
|
||||
// a reuse proof across reopen or takeover; those require content-hash matching.
|
||||
func (l *chunkLayerImpl) rememberPayload(c capturedChunk, gen uint64) {
|
||||
if !l.usesOwnedMapV3() {
|
||||
return
|
||||
}
|
||||
|
||||
c.data = nil
|
||||
l.stMu.Lock()
|
||||
defer l.stMu.Unlock()
|
||||
|
||||
@@ -1133,67 +1133,3 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(format-v3 row 14a): explicit C11 bitmap-engine fixtures only.
|
||||
func newLegacyChunkTestStore(t *testing.T) (*WALStore, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "vol.bin")
|
||||
s, err := createLegacyWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { closeBounded(t, s) })
|
||||
return s, path
|
||||
}
|
||||
|
||||
// crashableStore is a store a test may crash; it is closed at cleanup only
|
||||
// if it was not crashed.
|
||||
func legacyCrashableStore(t *testing.T) (*WALStore, string, func()) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "vol.bin")
|
||||
s, err := createLegacyWALStoreWithOptions(path, ctNumBlocks, ctBlockSize, WALStoreOptions{ChunkBlocks: ctChunkBlocks})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
closeBounded(t, s)
|
||||
}
|
||||
})
|
||||
return s, path, func() {
|
||||
crashed = true
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reopen opens and recovers a crashed store; it may be crashed again.
|
||||
func legacyReopen(t *testing.T, path string) (*WALStore, func()) {
|
||||
t.Helper()
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
closeBounded(t, s)
|
||||
}
|
||||
})
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatalf("local recovery: %v", err)
|
||||
}
|
||||
return s, func() {
|
||||
crashed = true
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,49 +13,9 @@ import (
|
||||
// attaching the chunk layer or admitting writes. Repeating after failure is safe.
|
||||
// Order: captureMu -> lifecycleMu -> mu; no remote call or layer callback.
|
||||
func (s *WALStore) SeedChunkFrontier(lsn uint64) error {
|
||||
if s.v3 != nil {
|
||||
return s.seedChunkFrontierV3(lsn)
|
||||
}
|
||||
s.captureMu.Lock()
|
||||
defer s.captureMu.Unlock()
|
||||
s.lifecycleMu.RLock()
|
||||
defer s.lifecycleMu.RUnlock()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed || s.chunk.Load() != nil {
|
||||
return errors.New("storage: seed frontier requires an open, unattached store")
|
||||
}
|
||||
if err := s.stickyIOFault(); err != nil {
|
||||
return err
|
||||
}
|
||||
if lsn == ^uint64(0) || lsn < s.checkpointLSN || s.walHead > s.checkpointLSN || s.nextLSN > lsn+1 {
|
||||
return errors.New("storage: seed frontier cannot replace local writes or wrap LSN")
|
||||
}
|
||||
if s.checkpointLSN == lsn && s.syncedLSN >= lsn && s.nextLSN == lsn+1 {
|
||||
return nil
|
||||
}
|
||||
if err := s.syncCache(); err != nil {
|
||||
return fmt.Errorf("storage: seed data sync: %w", err)
|
||||
}
|
||||
if s.metadata != nil {
|
||||
if err := s.metadata.BeforeCheckpointAdvance(lsn); err != nil {
|
||||
return fmt.Errorf("storage: block metadata before seed frontier %d: %w", lsn, err)
|
||||
}
|
||||
}
|
||||
next := *s.sb
|
||||
next.WALCheckpointLSN = lsn
|
||||
next.WALHead = s.wal.logicalHeadValue()
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := next.writeTo(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.syncFile(nil, func() error { return s.syncDirectFrontierMetadata(buf.bytes()) }); err != nil {
|
||||
return fmt.Errorf("storage: seed metadata sync: %w", err)
|
||||
}
|
||||
*s.sb = next
|
||||
s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1
|
||||
s.pendingDirectFrontierLSN = 0
|
||||
return nil
|
||||
|
||||
return s.seedChunkFrontierV3(lsn)
|
||||
|
||||
}
|
||||
|
||||
// seedChunkFrontierV3 is SeedChunkFrontier on a dark v3 store (plan row 9):
|
||||
@@ -135,6 +95,5 @@ func (s *WALStore) seedChunkFrontierV3Locked(lsn uint64, t *seedTimes) (err erro
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.checkpointLSN, s.syncedLSN, s.walHead, s.nextLSN = lsn, lsn, lsn, lsn+1
|
||||
s.pendingDirectFrontierLSN = 0
|
||||
return nil
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSeedChunkFrontierMetadataFailureRetry(t *testing.T) {
|
||||
s, path := newLegacyChunkTestStore(t)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
syncMetadata := s.syncDirectFrontierMetadata
|
||||
s.syncDirectFrontierMetadata = func([]byte) error { return errors.New("injected metadata fsync failure") }
|
||||
if err := s.SeedChunkFrontier(7); err == nil {
|
||||
t.Fatal("failed metadata sync accepted")
|
||||
}
|
||||
if next := s.NextLSN(); next != 1 {
|
||||
t.Fatalf("failed seed advanced NextLSN to %d", next)
|
||||
}
|
||||
if r, _, h := s.Boundaries(); r != 0 || h != 0 {
|
||||
t.Fatal("failed seed published frontier", r, h)
|
||||
}
|
||||
// The failed fsync is sticky for this open store (ErrFsyncFailed):
|
||||
// neither a same-store Recover nor a seed retry may run on it.
|
||||
s.syncDirectFrontierMetadata = syncMetadata
|
||||
if _, err := s.Recover(); !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("same-store Recover after a failed fsync: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
if err := s.SeedChunkFrontier(7); !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("same-store seed retry after a failed fsync: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
_ = s.Close()
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopenedOpen := true
|
||||
t.Cleanup(func() {
|
||||
if reopenedOpen {
|
||||
_ = reopened.Close()
|
||||
}
|
||||
})
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reopened.SeedChunkFrontier(7); err != nil {
|
||||
t.Fatalf("seed after a reopen: %v", err)
|
||||
}
|
||||
if reopened.NextLSN() != 8 {
|
||||
t.Fatal("seed after a reopen not applied")
|
||||
}
|
||||
reopened.committer.Stop()
|
||||
_ = reopened.fd.Close() // crash
|
||||
reopenedOpen = false
|
||||
again, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer again.Close()
|
||||
if _, err := again.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, _, h := again.Boundaries(); again.CheckpointLSN() != 7 || r != 7 || h != 7 || again.NextLSN() != 8 {
|
||||
t.Fatalf("seed after a crash: checkpoint=%d R=%d H=%d next=%d want 7/7/7/8", again.CheckpointLSN(), r, h, again.NextLSN())
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ package storage
|
||||
//
|
||||
// installMu (BASE transitions only) -> capMu -> WALStore.captureMu -> WALStore.lifecycleMu -> WALStore.mu
|
||||
// extentMu[i] -> stMu
|
||||
// WALStore.mu -> bmMu -> stMu (BeforeCheckpointAdvance runs under mu)
|
||||
// WALStore.mu -> presMu -> stMu (BeforeCheckpointAdvance runs under mu)
|
||||
//
|
||||
// stMu guards the layer's in-memory state and is never held across a
|
||||
// WALStore call, a bitmap store call or a remote call.
|
||||
@@ -77,8 +77,8 @@ type chunkLayerImpl struct {
|
||||
cowTransitions int
|
||||
cowClosed bool
|
||||
|
||||
capMu sync.Mutex // serializes Capture, Evict, Begin/EndBaseInstall
|
||||
bmMu sync.Mutex // serializes bitmap store calls
|
||||
capMu sync.Mutex // serializes Capture, Evict, Begin/EndBaseInstall
|
||||
|
||||
presMu sync.Mutex // serializes a whole presence save: snapshot, fsync, replace, version
|
||||
|
||||
hydration map[uint64]*chunkHydrationFlight // under stMu
|
||||
@@ -116,18 +116,8 @@ type chunkLayerImpl struct {
|
||||
dirty map[uint64]bool // chunks dirtied since the cut in progress or the last HEAD
|
||||
inflight map[uint64]bool // chunks captured by a cut whose HEAD is not yet installed
|
||||
allDirty bool // a BASE block landed: every chunk is dirty
|
||||
hashMode bool // the dirty set is unknown: reconcile every chunk against HEAD before any cut
|
||||
// reconcile holds the chunks the reconciler has not compared yet;
|
||||
// reconcileTotal is the size of the current reconciliation, and
|
||||
// reconciled is closed when it is done or replaced (under stMu).
|
||||
// reconcileGen names the current reconciliation: every start and every
|
||||
// BeginBaseInstall bumps it, and a worker reads, updates and certifies
|
||||
// only while its own generation is current.
|
||||
reconcile map[uint64]bool
|
||||
reconcileTotal int
|
||||
reconciled chan struct{}
|
||||
reconcileGen uint64
|
||||
cutLSN uint64 // H of the latest cut taken (in flight or installed)
|
||||
|
||||
cutLSN uint64 // H of the latest cut taken (in flight or installed)
|
||||
// chunkMut counts the mutations of each chunk: every dirty-map insert
|
||||
// (any LSN, a replica apply's lower LSN included) and every BASE
|
||||
// block. Flushing moves bytes without changing them and never counts.
|
||||
@@ -152,19 +142,20 @@ type chunkLayerImpl struct {
|
||||
|
||||
// Absence: chunks whose local bytes are not authoritative (fresh host,
|
||||
// evicted), and blocks written locally inside such chunks since.
|
||||
absent map[uint64]bool
|
||||
absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation
|
||||
localBlocks map[uint64]bool
|
||||
presenceVer uint64
|
||||
savedPresVer uint64
|
||||
dirtyVer uint64
|
||||
savedDirtyVer uint64
|
||||
absent map[uint64]bool
|
||||
absentGen map[uint64]uint64 // bumped on every eviction; binds a fill to its generation
|
||||
localBlocks map[uint64]bool
|
||||
presenceVer uint64
|
||||
savedPresVer uint64
|
||||
dirtyVer uint64
|
||||
}
|
||||
|
||||
func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) (chunkLayer, error) {
|
||||
mapped := s.v3 != nil && s.v3.mapProof != nil
|
||||
if remote == nil || cfg.ChunkBlocks == 0 || (!mapped && cfg.Bitmap == nil) {
|
||||
return nil, errors.New("storage: chunk layer needs a remote, ChunkBlocks > 0 and a legacy bitmap unless the store owns an impl3 map")
|
||||
if s.v3 == nil || s.v3.mapProof == nil {
|
||||
return nil, fmt.Errorf("%w: chunk layer requires the native owned map", ErrMapInvalid)
|
||||
}
|
||||
if remote == nil || cfg.ChunkBlocks == 0 {
|
||||
return nil, errors.New("storage: chunk layer needs a remote and ChunkBlocks > 0")
|
||||
}
|
||||
var localBase bool
|
||||
s.captureMu.Lock()
|
||||
@@ -172,7 +163,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
if s.attachClosed {
|
||||
return nil, errChunkLayerClosed
|
||||
}
|
||||
if mapped {
|
||||
{
|
||||
|
||||
// Serialize hook publication with begin/complete. Their outer hook
|
||||
// snapshot is rechecked after taking this same barrier.
|
||||
d := s.v3.pub.current()
|
||||
@@ -184,7 +176,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
cfg.FreshFromHead = false
|
||||
}
|
||||
}
|
||||
if s.v3 != nil && s.v3.ownedMap != nil && uint64(cfg.ChunkBlocks) != s.v3.ownedMap.chunkBlocks {
|
||||
|
||||
if s.v3.ownedMap != nil && uint64(cfg.ChunkBlocks) != s.v3.ownedMap.chunkBlocks {
|
||||
return nil, fmt.Errorf("%w: chunk layer geometry differs from owned map", ErrMapInvalid)
|
||||
}
|
||||
if cfg.UploadConcurrency < 0 || cfg.UploadConcurrency > 64 {
|
||||
@@ -234,7 +227,6 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
absent: map[uint64]bool{},
|
||||
absentGen: map[uint64]uint64{},
|
||||
localBlocks: map[uint64]bool{},
|
||||
reconcile: map[uint64]bool{},
|
||||
closeDone: make(chan struct{}),
|
||||
syncDirFn: syncDir,
|
||||
}
|
||||
@@ -261,45 +253,9 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
// never used as this holder's publication guard.
|
||||
l.fenced = l.supersededBy(head)
|
||||
|
||||
if mapped {
|
||||
// Dirt is derived from the owned LSN map against the actual remote HEAD;
|
||||
// no local HEAD-period bitmap header is loaded or created for impl3.
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch}
|
||||
} else {
|
||||
hdr, saved, ok, err := cfg.Bitmap.Load()
|
||||
if err != nil {
|
||||
l.cancel()
|
||||
return nil, fmt.Errorf("storage: chunk layer attach: load bitmap: %w", err)
|
||||
}
|
||||
switch {
|
||||
case ok && hdr.Base == chunkBaseInstalling:
|
||||
l.hdr = hdr // an interrupted BASE install: cuts stay refused
|
||||
case ok && hdr.Base == chunkBaseInstalledAwaitingCut:
|
||||
l.hdr, l.hashMode = hdr, true
|
||||
case ok && hdr.BaseLSN == head.RemoteLSN && hdr.HeadGen == head.Gen && hdr.Epoch == head.Epoch:
|
||||
l.hdr = hdr
|
||||
for _, idx := range saved {
|
||||
l.dirty[idx] = true
|
||||
}
|
||||
case !ok && cfg.FreshFromHead:
|
||||
// A fresh local volume has taken no write yet (I/O waits for its
|
||||
// first attach): its image is HEAD's, so nothing is dirty. Start with
|
||||
// an empty bitmap bound to HEAD instead of hash mode, which stays for
|
||||
// an existing volume whose bitmap is lost (integration ruling F1).
|
||||
fresh := chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
|
||||
if err := cfg.Bitmap.WriteHeader(fresh); err != nil {
|
||||
l.hashMode = true // safe: compare every chunk on the first cut
|
||||
} else {
|
||||
l.hdr = fresh
|
||||
}
|
||||
default:
|
||||
if ok {
|
||||
l.hdr = hdr
|
||||
}
|
||||
l.hashMode = true
|
||||
}
|
||||
|
||||
}
|
||||
// Dirt is derived from the owned LSN map against the actual remote HEAD;
|
||||
// no local HEAD-period bitmap header is loaded or created for impl3.
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: head.Epoch}
|
||||
|
||||
if localBase {
|
||||
// The completed BASE image is local authority, including ZERO blocks.
|
||||
@@ -313,21 +269,8 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
// preserve ALL chunks as candidates for the first hash-comparing cut.
|
||||
// Persist that obligation before publishing hooks/readiness.
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch}
|
||||
var initialDirty []uint64
|
||||
l.dirty = map[uint64]bool{}
|
||||
l.hashMode = !mapped && head.Gen == 0 && s.NextLSN() > 1
|
||||
if l.hashMode {
|
||||
for idx := uint64(0); idx < l.numChunks; idx++ {
|
||||
l.dirty[idx] = true
|
||||
initialDirty = append(initialDirty, idx)
|
||||
}
|
||||
}
|
||||
if !mapped {
|
||||
if err := cfg.Bitmap.Reset(l.hdr, initialDirty, chunkDelta{}); err != nil {
|
||||
l.cancel()
|
||||
return nil, fmt.Errorf("storage: fresh bitmap reset: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
for idx := range head.Chunks {
|
||||
l.absent[idx] = true
|
||||
l.absentGen[idx]++
|
||||
@@ -338,11 +281,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
return nil, err
|
||||
}
|
||||
hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated}
|
||||
if mapped {
|
||||
hooks.baseTransitionV3 = l.holdBaseTransitionV3
|
||||
hooks.beforeMutation = l.beforeCOWMutation
|
||||
hooks.beforeDestructive = l.holdCOWDestructive
|
||||
}
|
||||
|
||||
hooks.baseTransitionV3 = l.holdBaseTransitionV3
|
||||
hooks.beforeMutation = l.beforeCOWMutation
|
||||
hooks.beforeDestructive = l.holdCOWDestructive
|
||||
|
||||
if !s.chunk.CompareAndSwap(nil, hooks) {
|
||||
l.cancel()
|
||||
return nil, errors.New("storage: a chunk layer is already attached")
|
||||
@@ -352,9 +295,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
|
||||
l.cancel()
|
||||
return nil, err
|
||||
}
|
||||
if l.hashMode {
|
||||
l.startReconcile()
|
||||
}
|
||||
|
||||
return l, nil
|
||||
}
|
||||
|
||||
@@ -439,21 +380,21 @@ func (l *chunkLayerImpl) noteAllMutated() {
|
||||
// after the WAL entry has checkpointed and the legacy bitmap says clean.
|
||||
func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
|
||||
out := map[uint64]bool{}
|
||||
mapped := l.usesOwnedMapV3()
|
||||
var base uint64
|
||||
if mapped {
|
||||
l.stMu.Lock()
|
||||
base = l.remoteLSN
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
|
||||
l.stMu.Lock()
|
||||
base = l.remoteLSN
|
||||
l.stMu.Unlock()
|
||||
|
||||
for _, e := range l.s.dm.snapshot() {
|
||||
// Retention in the local WAL is not dirt since HEAD. Lower-LSN
|
||||
// BASE/direct changes remain conservative through UNKNOWN below.
|
||||
if !mapped || e.LSN > base {
|
||||
if e.LSN > base {
|
||||
out[l.chunkOf(e.LBA)] = true
|
||||
}
|
||||
}
|
||||
if mapped {
|
||||
{
|
||||
|
||||
l.stMu.Lock()
|
||||
absent := map[uint64]bool{}
|
||||
for idx := range l.absent {
|
||||
@@ -471,6 +412,7 @@ func (l *chunkLayerImpl) captureCandidates() map[uint64]bool {
|
||||
}
|
||||
l.s.mu.RUnlock()
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -483,7 +425,7 @@ func (l *chunkLayerImpl) chunkVersion(idx uint64) uint64 {
|
||||
// frontier path, under WALStore.mu: it makes the dirty set (and any changed
|
||||
// absence state) durable before the checkpoint can pass the entries.
|
||||
func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error {
|
||||
if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling {
|
||||
if l.s.v3.pub.current().BaseState == BaseInstalling {
|
||||
// Serving/capture remain blocked by the installing descriptor. Settle
|
||||
// local BASE authority before the installed descriptor can publish;
|
||||
// a failure leaves the volume installing, never serving a partial image.
|
||||
@@ -493,68 +435,9 @@ func (l *chunkLayerImpl) BeforeCheckpointAdvance(lsn uint64) error {
|
||||
l.presenceVer++
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
if err := l.saveDirty(); err != nil {
|
||||
return err
|
||||
}
|
||||
return l.persistPresence()
|
||||
}
|
||||
|
||||
// saveDirty persists dirty ÃÆ’Æ’Ãâ€šÂ¢ÃÆ’‹â€ÂÂ ÃÆ’‚ª inflight ÃÆ’Æ’Ãâ€šÂ¢ÃÆ’‹â€ÂÂ ÃÆ’‚ª the chunks of WAL entries still in
|
||||
// the dirty map (all chunks when a BASE block landed or the set is unknown).
|
||||
func (l *chunkLayerImpl) saveDirty() error {
|
||||
// Impl3's actual checkpoint caller persists its owned map after this
|
||||
// callback. It already tracks WAL mutations independently of this layer;
|
||||
// making a second persistent C11 bitmap would add no coverage authority.
|
||||
if l.usesOwnedMapV3() {
|
||||
return nil
|
||||
}
|
||||
l.bmMu.Lock()
|
||||
defer l.bmMu.Unlock()
|
||||
set := l.dirtySetLocked(nil)
|
||||
l.stMu.Lock()
|
||||
ver := l.dirtyVer
|
||||
if ver == l.savedDirtyVer && ver != 0 {
|
||||
l.stMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
if err := l.cfg.Bitmap.Save(sortedKeys(set)); err != nil {
|
||||
return err
|
||||
}
|
||||
l.stMu.Lock()
|
||||
if ver > l.savedDirtyVer {
|
||||
l.savedDirtyVer = ver
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// dirtySetLocked returns the chunk set the persisted bitmap must cover.
|
||||
// Caller holds bmMu (or capMu); stMu is taken here.
|
||||
func (l *chunkLayerImpl) dirtySetLocked(extra map[uint64]bool) map[uint64]bool {
|
||||
set := map[uint64]bool{}
|
||||
for _, e := range l.s.dm.snapshot() {
|
||||
set[l.chunkOf(e.LBA)] = true
|
||||
}
|
||||
l.stMu.Lock()
|
||||
defer l.stMu.Unlock()
|
||||
if l.allDirty || l.hashMode {
|
||||
for i := uint64(0); i < l.numChunks; i++ {
|
||||
set[i] = true
|
||||
}
|
||||
}
|
||||
for idx := range l.dirty {
|
||||
set[idx] = true
|
||||
}
|
||||
for idx := range l.inflight {
|
||||
set[idx] = true
|
||||
}
|
||||
for idx := range extra {
|
||||
set[idx] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func sortedKeys(m map[uint64]bool) []uint64 {
|
||||
out := make([]uint64, 0, len(m))
|
||||
for k := range m {
|
||||
@@ -646,44 +529,15 @@ func (s *WALStore) installFetchedBlock(lba uint32, data []byte, stillAbsent func
|
||||
func (l *chunkLayerImpl) BeginBaseInstall() error {
|
||||
l.capMu.Lock()
|
||||
defer l.capMu.Unlock()
|
||||
// A running reconciliation is superseded: its worker can neither
|
||||
// certify a dirty set nor clear the install guard. EndBaseInstall
|
||||
// starts a new one.
|
||||
return l.writeBaseState(chunkBaseInstalling, func() { l.allDirty = true; l.reconcileGen++ })
|
||||
return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet)
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) EndBaseInstall(frontier uint64) error {
|
||||
l.capMu.Lock()
|
||||
defer l.capMu.Unlock()
|
||||
if cp := l.s.CheckpointLSN(); cp < frontier {
|
||||
return fmt.Errorf("storage: EndBaseInstall: frontier %d is not durable (checkpoint %d)", frontier, cp)
|
||||
}
|
||||
if err := l.writeBaseState(chunkBaseInstalledAwaitingCut, func() { l.hashMode = true }); err != nil {
|
||||
return err
|
||||
}
|
||||
l.startReconcile()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) writeBaseState(state chunkBaseState, apply func()) error {
|
||||
if l.usesOwnedMapV3() {
|
||||
return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet)
|
||||
}
|
||||
l.bmMu.Lock()
|
||||
defer l.bmMu.Unlock()
|
||||
l.stMu.Lock()
|
||||
hdr := l.hdr
|
||||
l.stMu.Unlock()
|
||||
hdr.Base = state
|
||||
if err := l.cfg.Bitmap.WriteHeader(hdr); err != nil {
|
||||
return err
|
||||
}
|
||||
l.stMu.Lock()
|
||||
l.hdr = hdr
|
||||
apply()
|
||||
l.dirtyVer++
|
||||
l.stMu.Unlock()
|
||||
return nil
|
||||
return fmt.Errorf("%w: BASE state must be published by the descriptor install protocol", errV3NotYet)
|
||||
}
|
||||
|
||||
// ---- capture ----
|
||||
@@ -712,7 +566,7 @@ func (l *chunkLayerImpl) admit() (err error) {
|
||||
l.abortCOW(err)
|
||||
}
|
||||
}()
|
||||
if l.usesOwnedMapV3() && l.s.v3.pub.current().BaseState == BaseInstalling {
|
||||
if l.s.v3.pub.current().BaseState == BaseInstalling {
|
||||
return fmt.Errorf("%w: %w", errChunkCaptureRefused, errChunkBaseInstalling)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
@@ -796,10 +650,6 @@ type stagedChunk struct {
|
||||
headGen uint64
|
||||
}
|
||||
|
||||
// chunkStageRounds bounds the pre-copy: after this many staging rounds the
|
||||
// barrier copies whatever remains (correctness over pause).
|
||||
const chunkStageRounds = 3
|
||||
|
||||
func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res chunkCutResult, err error) {
|
||||
done, err := l.register()
|
||||
if err != nil {
|
||||
@@ -842,12 +692,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
if hook := l.testAfterAdmitHook; hook != nil {
|
||||
hook()
|
||||
}
|
||||
l.stMu.Lock()
|
||||
reconciling := l.hashMode
|
||||
l.stMu.Unlock()
|
||||
if reconciling { // no HEAD moves until the dirty set is known
|
||||
return chunkCutResult{}, errChunkReconciling
|
||||
}
|
||||
|
||||
ctx, cancel := l.opCtx(ctx)
|
||||
defer cancel()
|
||||
var budget *cutBudgetReservation
|
||||
@@ -953,7 +798,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
candidates[idx] = true
|
||||
}
|
||||
l.stMu.Lock()
|
||||
all := l.hashMode || l.allDirty
|
||||
all := l.allDirty
|
||||
for idx := range l.dirty {
|
||||
candidates[idx] = true
|
||||
}
|
||||
@@ -972,9 +817,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
// was compared against.
|
||||
var captured []capturedChunk
|
||||
var capturedVersions map[uint64]uint64
|
||||
if l.usesOwnedMapV3() {
|
||||
capturedVersions = make(map[uint64]uint64, len(candidates))
|
||||
}
|
||||
|
||||
capturedVersions = make(map[uint64]uint64, len(candidates))
|
||||
|
||||
useStaged := map[uint64]bool{}
|
||||
for idx := range candidates {
|
||||
if capturedVersions != nil {
|
||||
@@ -1017,7 +862,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
var copyErr error
|
||||
copyStart := time.Now()
|
||||
bytesBeforeCopy := st.UploadedBytes
|
||||
if l.usesOwnedMapV3() {
|
||||
{
|
||||
var w *cutCOWWindow
|
||||
w, copyErr = l.installCOWWindow(candidates, useStaged, baseHead.Chunks)
|
||||
if copyErr == nil {
|
||||
@@ -1042,29 +887,13 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
|
||||
st.COWSavedChunks = int(w.saved.Load())
|
||||
st.COWSaveNs, st.COWWaitNs = w.saveNs.Load(), w.waitNs.Load()
|
||||
}
|
||||
} else {
|
||||
st.BarrierCopyChunks = len(candidates) - len(useStaged)
|
||||
for _, idx := range sortedKeys(candidates) {
|
||||
if useStaged[idx] {
|
||||
continue
|
||||
}
|
||||
buf, err := l.readChunk(idx)
|
||||
if err != nil {
|
||||
copyErr = err
|
||||
break
|
||||
}
|
||||
captured = append(captured, capturedChunk{idx: idx, data: buf, sum: sha256.Sum256(buf), zero: isAllZero(buf)})
|
||||
}
|
||||
unlockCapture()
|
||||
st.BarrierPauseNs = time.Since(pauseStart).Nanoseconds()
|
||||
}
|
||||
|
||||
st.CopyNs = time.Since(copyStart).Nanoseconds()
|
||||
if st.UploadedBytes > bytesBeforeCopy {
|
||||
st.PayloadNs += st.CopyNs
|
||||
}
|
||||
if l.usesOwnedMapV3() {
|
||||
st.UploadNs = st.CopyNs
|
||||
}
|
||||
st.UploadNs = st.CopyNs
|
||||
if copyErr != nil {
|
||||
l.abortCut(all)
|
||||
l.dropIntents(ctx, intents)
|
||||
@@ -1283,9 +1112,7 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) {
|
||||
if r, ok := l.storedDetach(); ok {
|
||||
return r, nil
|
||||
}
|
||||
if err := l.waitReconciled(ctx); err != nil {
|
||||
return chunkCutResult{}, err
|
||||
}
|
||||
|
||||
r, err := l.captureLocked(ctx, true)
|
||||
if errors.Is(err, errChunkLayerDetached) {
|
||||
if d, ok := l.storedDetach(); ok {
|
||||
@@ -1585,213 +1412,16 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats {
|
||||
}
|
||||
out.PendingUnresolved = l.pending != nil
|
||||
out.DirtyChunks = len(l.dirty)
|
||||
out.Reconciling = l.hashMode
|
||||
out.ReconcileTotal = l.reconcileTotal
|
||||
out.ReconcileDone = l.reconcileTotal - len(l.reconcile)
|
||||
out.Reconciling = false
|
||||
out.ReconcileTotal = 0
|
||||
out.ReconcileDone = 0
|
||||
l.stMu.Unlock()
|
||||
if l.usesOwnedMapV3() {
|
||||
out.DirtyChunks = len(l.captureCandidates())
|
||||
}
|
||||
|
||||
out.DirtyChunks = len(l.captureCandidates())
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- reconciliation (the dirty set is unknown) ----
|
||||
|
||||
// reconcileSlice bounds one reconciler step; between steps it yields.
|
||||
const reconcileSlice = 8
|
||||
|
||||
// startReconcile begins reconciling every chunk with a local copy against
|
||||
// HEAD. A chunk that is absent and was never written locally is HEAD's
|
||||
// content by definition and is skipped.
|
||||
func (l *chunkLayerImpl) startReconcile() {
|
||||
l.stMu.Lock()
|
||||
set := map[uint64]bool{}
|
||||
for i := uint64(0); i < l.numChunks; i++ {
|
||||
if l.absent[i] && !l.chunkHasLocalLocked(i) {
|
||||
continue
|
||||
}
|
||||
set[i] = true
|
||||
}
|
||||
l.reconcileGen++
|
||||
gen := l.reconcileGen
|
||||
if l.reconciled != nil {
|
||||
close(l.reconciled) // a waiter on the replaced run re-checks
|
||||
}
|
||||
l.reconcile, l.reconcileTotal, l.reconciled = set, len(set), make(chan struct{})
|
||||
l.stMu.Unlock()
|
||||
// Nothing to compare (a fresh host: every HEAD chunk is absent and no
|
||||
// block was written): the dirty set is known now, with no window in
|
||||
// which cuts are refused.
|
||||
if len(set) == 0 && l.cfg.testReconcileHold == nil && l.cfg.testReconcileHook == nil && l.finishReconcile(gen) {
|
||||
return
|
||||
}
|
||||
done, err := l.register()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go l.reconcileLoop(done, gen)
|
||||
}
|
||||
|
||||
// reconcileLoop compares the chunks in the reconcile set with HEAD outside
|
||||
// the capture barrier, a slice at a time: a chunk whose bytes differ from
|
||||
// HEAD's becomes dirty. A write racing the comparison marks its chunk
|
||||
// dirty anyway, so a chunk is never lost. When the set is empty the dirty
|
||||
// set is exact: it is persisted with a header naming HEAD, and cuts resume.
|
||||
func (l *chunkLayerImpl) reconcileLoop(done func(), gen uint64) {
|
||||
defer done()
|
||||
for {
|
||||
if l.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if hold := l.cfg.testReconcileHold; hold != nil {
|
||||
select {
|
||||
case <-hold:
|
||||
case <-l.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
if hook := l.cfg.testReconcileHook; hook != nil {
|
||||
hook("batch", gen)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
if l.reconcileGen != gen { // superseded
|
||||
l.stMu.Unlock()
|
||||
return
|
||||
}
|
||||
var batch []uint64
|
||||
for _, idx := range sortedKeys(l.reconcile) {
|
||||
if len(batch) == reconcileSlice {
|
||||
break
|
||||
}
|
||||
batch = append(batch, idx)
|
||||
}
|
||||
head := copyHead(l.head)
|
||||
l.stMu.Unlock()
|
||||
if len(batch) == 0 {
|
||||
if hook := l.cfg.testReconcileHook; hook != nil {
|
||||
hook("finish", gen)
|
||||
}
|
||||
if l.finishReconcile(gen) {
|
||||
return
|
||||
}
|
||||
if !l.sleep(100 * time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, idx := range batch {
|
||||
data, err := l.readChunk(idx)
|
||||
if err != nil {
|
||||
if !l.sleep(100 * time.Millisecond) { // retried; the set keeps it
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
ref, had := head.Chunks[idx]
|
||||
same := (!had && isAllZero(data)) || (had && sha256.Sum256(data) == ref.SHA256)
|
||||
if hook := l.cfg.testReconcileHook; hook != nil {
|
||||
hook("compared", gen)
|
||||
}
|
||||
l.stMu.Lock()
|
||||
if l.reconcileGen != gen { // superseded: the replacement owns the set
|
||||
l.stMu.Unlock()
|
||||
return
|
||||
}
|
||||
if !same {
|
||||
l.dirty[idx] = true
|
||||
l.dirtyVer++
|
||||
}
|
||||
delete(l.reconcile, idx)
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// finishReconcile persists reconciliation gen's dirty set and leaves hash
|
||||
// mode. It reports false when the bitmap could not be written (retried),
|
||||
// and true when done or when gen is no longer current: a superseded run
|
||||
// (replaced, or a BASE install began) writes nothing and certifies
|
||||
// nothing. bmMu is held throughout, so no BASE state change interleaves.
|
||||
func (l *chunkLayerImpl) finishReconcile(gen uint64) bool {
|
||||
l.bmMu.Lock()
|
||||
defer l.bmMu.Unlock()
|
||||
l.stMu.Lock()
|
||||
if l.reconcileGen != gen || len(l.reconcile) != 0 || l.hdr.Base == chunkBaseInstalling {
|
||||
l.stMu.Unlock()
|
||||
return true
|
||||
}
|
||||
still := map[uint64]bool{}
|
||||
for idx := range l.dirty {
|
||||
still[idx] = true
|
||||
}
|
||||
if l.allDirty {
|
||||
for i := uint64(0); i < l.numChunks; i++ {
|
||||
still[i] = true
|
||||
}
|
||||
}
|
||||
hdr := chunkBitmapHeader{BaseLSN: l.head.RemoteLSN, HeadGen: l.head.Gen, Epoch: l.head.Epoch, Base: chunkBaseNone}
|
||||
ver := l.dirtyVer
|
||||
l.stMu.Unlock()
|
||||
// The dirty set first, then the header naming HEAD: a crash between
|
||||
// the two leaves the old header, which mismatches HEAD, so the next
|
||||
// attach reconciles again instead of trusting an incomplete bitmap.
|
||||
if !l.usesOwnedMapV3() {
|
||||
if err := l.cfg.Bitmap.Save(sortedKeys(still)); err != nil {
|
||||
return false
|
||||
}
|
||||
if err := l.cfg.Bitmap.WriteHeader(hdr); err != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
l.stMu.Lock()
|
||||
defer l.stMu.Unlock()
|
||||
l.hdr, l.hashMode = hdr, false
|
||||
if ver > l.savedDirtyVer {
|
||||
l.savedDirtyVer = ver
|
||||
}
|
||||
if l.reconciled != nil {
|
||||
close(l.reconciled)
|
||||
l.reconciled = nil
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// waitReconciled returns once the layer is not reconciling, or
|
||||
// errChunkReconciling when ctx ends first. A replaced run wakes its
|
||||
// waiters, which re-check against the current one.
|
||||
func (l *chunkLayerImpl) waitReconciled(ctx context.Context) error {
|
||||
for {
|
||||
l.stMu.Lock()
|
||||
reconciling, ch := l.hashMode, l.reconciled
|
||||
l.stMu.Unlock()
|
||||
if !reconciling {
|
||||
return nil
|
||||
}
|
||||
if ch == nil {
|
||||
return errChunkReconciling
|
||||
}
|
||||
select {
|
||||
case <-ch:
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("%w: %w", errChunkReconciling, ctx.Err())
|
||||
case <-l.ctx.Done():
|
||||
return errors.New("storage: chunk layer closed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// sleep waits d unless the layer closes first.
|
||||
func (l *chunkLayerImpl) sleep(d time.Duration) bool {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return true
|
||||
case <-l.ctx.Done():
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// dropIntent deletes this layer's own intent id (none if empty) once its
|
||||
// cut is settled. A failed delete is kept and retried by the next cut; it
|
||||
// never fails a cut whose outcome is already settled.
|
||||
@@ -1852,17 +1482,11 @@ func (l *chunkLayerImpl) dropIntents(ctx context.Context, ids []string) {
|
||||
// stage uploads large native dirty sets through logical reads, before fixing H.
|
||||
// It stops when the spill-budget remainder is reached or a round makes no
|
||||
// progress. Versions/HEAD generation bind every reusable immutable result.
|
||||
// Legacy fixtures retain their bounded-count rounds.
|
||||
func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint64]stagedChunk, []string, error) {
|
||||
bound := l.cfg.BarrierBound
|
||||
native := l.usesOwnedMapV3()
|
||||
if native {
|
||||
// Leave at most half the side budget exposed at the barrier. Streaming
|
||||
// staging uses no local payload file, even for a much larger image.
|
||||
bound = int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks)))
|
||||
} else if bound <= 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
// Leave at most half the side budget exposed at the barrier. Streaming
|
||||
// staging uses no local payload file, even for a much larger image.
|
||||
bound := int(l.cfg.COWSpillLimit / (2 * int64(l.blockSize) * int64(l.chunkBlocks)))
|
||||
|
||||
staged := map[uint64]stagedChunk{}
|
||||
var intents []string
|
||||
l.stMu.Lock()
|
||||
@@ -1890,7 +1514,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
|
||||
for idx := range l.dirty {
|
||||
consider(idx)
|
||||
}
|
||||
if l.hashMode || l.allDirty {
|
||||
if l.allDirty {
|
||||
for i := uint64(0); i < l.numChunks; i++ {
|
||||
if l.absent[i] && !l.chunkHasLocalLocked(i) {
|
||||
continue
|
||||
@@ -1898,7 +1522,7 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
|
||||
consider(i)
|
||||
}
|
||||
}
|
||||
if len(need) <= bound || (native && len(need) >= previous) || (!native && round >= chunkStageRounds) {
|
||||
if len(need) <= bound || (len(need) >= previous) {
|
||||
l.stMu.Unlock()
|
||||
break
|
||||
}
|
||||
@@ -1907,17 +1531,15 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats) (map[uint
|
||||
// Release layer state before sampling the store; never invert store -> stMu.
|
||||
l.stMu.Unlock()
|
||||
l.s.mu.RLock()
|
||||
if l.usesOwnedMapV3() {
|
||||
for idx := range need {
|
||||
recent[idx] = l.s.v3.mapEntries[idx].LSN
|
||||
}
|
||||
|
||||
for idx := range need {
|
||||
recent[idx] = l.s.v3.mapEntries[idx].LSN
|
||||
}
|
||||
|
||||
l.s.mu.RUnlock()
|
||||
l.stMu.Lock()
|
||||
batch := hotChunkKeys(need, recent)
|
||||
if !native {
|
||||
batch = batch[:bound]
|
||||
}
|
||||
|
||||
vers := make(map[uint64]uint64, len(batch))
|
||||
for _, idx := range batch {
|
||||
vers[idx] = l.chunkVersion(idx) // before the read: a later mutation raises it
|
||||
@@ -1969,46 +1591,13 @@ func (l *chunkLayerImpl) abortCut(all bool) {
|
||||
// finishCut installs HEAD in memory and rolls the bitmap over: only chunks
|
||||
// dirtied after the cut (and WAL entries above it) stay set.
|
||||
func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) {
|
||||
l.bmMu.Lock()
|
||||
defer l.bmMu.Unlock()
|
||||
still := map[uint64]bool{}
|
||||
for _, e := range l.s.dm.snapshot() {
|
||||
if e.LSN > h {
|
||||
still[l.chunkOf(e.LBA)] = true
|
||||
}
|
||||
}
|
||||
l.stMu.Lock()
|
||||
for idx := range l.dirty {
|
||||
still[idx] = true
|
||||
}
|
||||
if l.allDirty {
|
||||
for i := uint64(0); i < l.numChunks; i++ {
|
||||
still[i] = true
|
||||
}
|
||||
}
|
||||
prevBase := l.hdr.BaseLSN
|
||||
defer l.stMu.Unlock()
|
||||
l.head, l.remoteLSN, l.pending = copyHead(head), h, nil
|
||||
l.reusable = nil
|
||||
l.inflight = map[uint64]bool{}
|
||||
l.hashMode = false
|
||||
hdr := chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
|
||||
l.hdr = hdr
|
||||
l.hdr = chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone}
|
||||
l.dirtyVer++
|
||||
ver := l.dirtyVer
|
||||
l.stMu.Unlock()
|
||||
sort.Slice(changed, func(i, j int) bool { return changed[i] < changed[j] })
|
||||
delta := chunkDelta{FromLSN: prevBase, ToLSN: h, Gen: head.Gen, Dirty: changed, NewKeys: newKeys}
|
||||
// HEAD is published; a failed Reset only leaves a stale header, which a
|
||||
// restart treats as a mismatch (hash compare): safe.
|
||||
if !l.usesOwnedMapV3() {
|
||||
if err := l.cfg.Bitmap.Reset(hdr, sortedKeys(still), delta); err == nil {
|
||||
l.stMu.Lock()
|
||||
if ver > l.savedDirtyVer {
|
||||
l.savedDirtyVer = ver
|
||||
}
|
||||
l.stMu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) newKey(idx uint64) string {
|
||||
@@ -2041,7 +1630,7 @@ func (l *chunkLayerImpl) EvictChunk(idx uint64) error {
|
||||
dirtyCandidate := l.captureCandidates()[idx]
|
||||
l.stMu.Lock()
|
||||
switch {
|
||||
case l.head.Gen == 0, l.hashMode, l.allDirty, l.hdr.Base != chunkBaseNone, l.dirty[idx], l.inflight[idx], dirtyCandidate:
|
||||
case l.head.Gen == 0, l.allDirty, l.hdr.Base != chunkBaseNone, l.dirty[idx], l.inflight[idx], dirtyCandidate:
|
||||
l.stMu.Unlock()
|
||||
return fmt.Errorf("%w: chunk %d is dirty since HEAD or HEAD is unknown", errChunkEvictRefused, idx)
|
||||
}
|
||||
|
||||
@@ -9,9 +9,6 @@ package storage
|
||||
// It may over-report, never under-report. RED until the layer exists.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -26,65 +23,8 @@ func extentBytes(t *testing.T, s *WALStore, lba uint32) []byte {
|
||||
return b
|
||||
}
|
||||
|
||||
// walLogicalTail is the WAL writer's physical recycling position.
|
||||
func walLogicalTail(s *WALStore) uint64 {
|
||||
if s.v3 != nil {
|
||||
return s.v3.pub.current().RetainedTail
|
||||
}
|
||||
s.wal.mu.Lock()
|
||||
defer s.wal.mu.Unlock()
|
||||
return s.wal.logicalTail
|
||||
}
|
||||
|
||||
// saveLog records, for every Save, the dirty set and the store's checkpoint
|
||||
// and WAL logical tail at that moment (inside Save, before it returns).
|
||||
type saveLog struct {
|
||||
mu sync.Mutex
|
||||
rows []savedRow
|
||||
}
|
||||
|
||||
type savedRow struct {
|
||||
checkpoint uint64
|
||||
walTail uint64
|
||||
dirty map[uint64]bool
|
||||
}
|
||||
|
||||
func recordSaves(s *WALStore, bm *fakeBitmapStore) *saveLog {
|
||||
l := &saveLog{}
|
||||
bm.mu.Lock()
|
||||
bm.onSave = func(dirty []uint64) {
|
||||
// Save runs inside persistCheckpoint, under the store's publication
|
||||
// lock: read the fields directly, never re-lock the store. Only the
|
||||
// flusher/Sync goroutine that holds that lock writes them.
|
||||
row := savedRow{checkpoint: s.checkpointLSN, walTail: s.wal.logicalTail, dirty: map[uint64]bool{}}
|
||||
for _, idx := range dirty {
|
||||
row.dirty[idx] = true
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.rows = append(l.rows, row)
|
||||
l.mu.Unlock()
|
||||
}
|
||||
bm.mu.Unlock()
|
||||
return l
|
||||
}
|
||||
|
||||
// firstSaveWith returns the first recorded Save whose dirty set holds idx.
|
||||
func (l *saveLog) firstSaveWith(idx uint64) (savedRow, bool) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
for _, r := range l.rows {
|
||||
if r.dirty[idx] {
|
||||
return r, true
|
||||
}
|
||||
}
|
||||
return savedRow{}, false
|
||||
}
|
||||
|
||||
func (l *saveLog) count() int {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.rows)
|
||||
}
|
||||
// walLogicalTail is the native retained cursor.
|
||||
func walLogicalTail(s *WALStore) uint64 { return s.v3.pub.current().RetainedTail }
|
||||
|
||||
func flushWithin(t *testing.T, s *WALStore, what string) error {
|
||||
t.Helper()
|
||||
@@ -92,509 +32,3 @@ func flushWithin(t *testing.T, s *WALStore, what string) error {
|
||||
within(t, what, func() error { ferr = s.flusher.flushOnce(); return nil })
|
||||
return ferr
|
||||
}
|
||||
|
||||
// C11 callbacks: OnExtentWrite, for a normal and a BASE block, returns at
|
||||
// once while bitmap persistence and the remote are held and the store's
|
||||
// publication lock is taken: no Load/Save/WriteHeader/Reset, no remote call,
|
||||
// no WALStore re-entry. (A BASE mark must also be a constant-time flag; that
|
||||
// cost bound is measured in the implementation PR, not proven here.)
|
||||
func TestChunkLayer_C11_ExtentCallbackIsPureInMemory(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
holdPuts(t, f)
|
||||
holdGets(t, f)
|
||||
block := make(chan struct{})
|
||||
var unblock sync.Once
|
||||
bm.mu.Lock()
|
||||
bm.block = block
|
||||
bm.mu.Unlock()
|
||||
release := func() { unblock.Do(func() { close(block) }) }
|
||||
t.Cleanup(release)
|
||||
onUnblock(t, release)
|
||||
callsBefore, remoteBefore := bm.callCount(), f.stats()
|
||||
|
||||
s.mu.Lock() // a callback that re-enters the store would block here
|
||||
var unlock sync.Once
|
||||
unlockStore := func() { unlock.Do(s.mu.Unlock) }
|
||||
t.Cleanup(unlockStore)
|
||||
onUnblock(t, unlockStore)
|
||||
within(t, "OnExtentWrite for a normal block and a BASE block", func() error {
|
||||
layer.OnExtentWrite(12, 7)
|
||||
layer.OnExtentWrite(13, 0)
|
||||
return nil
|
||||
})
|
||||
unlock.Do(s.mu.Unlock)
|
||||
|
||||
if n := bm.callCount() - callsBefore; n != 0 {
|
||||
t.Fatalf("OnExtentWrite made %d bitmap store calls", n)
|
||||
}
|
||||
after := f.stats()
|
||||
if after.puts != remoteBefore.puts || after.gets != remoteBefore.gets || after.getHeads != remoteBefore.getHeads || after.cas != remoteBefore.cas {
|
||||
t.Fatal("OnExtentWrite made remote calls")
|
||||
}
|
||||
}
|
||||
|
||||
// C11 ordering and period: writes never touch the bitmap; the flusher saves
|
||||
// a dirty set covering a chunk before the checkpoint or the physical WAL
|
||||
// tail passes that chunk's entries; a cut archives the closed period as a
|
||||
// delta and starts a new bitmap headed by the new HEAD; a failed save
|
||||
// refuses the advance (checkpoint and WAL tail unchanged), and a restart
|
||||
// still captures the chunk from the WAL.
|
||||
func TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle(t *testing.T) {
|
||||
s, path, crash := legacyCrashableStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
saves := recordSaves(s, bm)
|
||||
w := newWriteLog()
|
||||
|
||||
var lsn uint64
|
||||
within(t, "write and Sync to chunk 3 (the bitmap is off the write path)", func() error {
|
||||
var err error
|
||||
if lsn, err = s.Write(12, makeBlock(ctBlockSize, 0x3C)); err != nil {
|
||||
return err
|
||||
}
|
||||
w.record(lsn, 12, makeBlock(ctBlockSize, 0x3C))
|
||||
_, err = s.Sync()
|
||||
return err
|
||||
})
|
||||
if n := saves.count(); n != 0 {
|
||||
t.Fatalf("a write and Sync saved the bitmap %d times; it must stay off the write path", n)
|
||||
}
|
||||
tailBefore := walLogicalTail(s)
|
||||
if err := flushWithin(t, s, "flush of chunk 3"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row, ok := saves.firstSaveWith(3)
|
||||
if !ok {
|
||||
t.Fatal("the flusher recycled chunk 3's WAL entries without saving a bitmap that covers chunk 3")
|
||||
}
|
||||
if row.checkpoint >= lsn || row.walTail != tailBefore {
|
||||
t.Fatalf("chunk 3 saved at checkpoint %d / WAL tail %d; want checkpoint < %d and the tail still at %d", row.checkpoint, row.walTail, lsn, tailBefore)
|
||||
}
|
||||
if s.CheckpointLSN() < lsn || walLogicalTail(s) <= tailBefore || !bm.persisted(3) {
|
||||
t.Fatalf("after the flush: checkpoint %d (want >= %d), WAL tail %d (want > %d), chunk 3 persisted %v", s.CheckpointLSN(), lsn, walLogicalTail(s), tailBefore, bm.persisted(3))
|
||||
}
|
||||
|
||||
cut, err := layer.Capture(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
head := f.stats().head
|
||||
hdr, deltas, _ := bm.snapshot()
|
||||
if want := (chunkBitmapHeader{BaseLSN: cut, HeadGen: head.Gen, Epoch: 1}); hdr != want {
|
||||
t.Fatalf("bitmap header after the cut %+v, want %+v", hdr, want)
|
||||
}
|
||||
if len(deltas) != 1 {
|
||||
t.Fatalf("%d delta records archived, want 1", len(deltas))
|
||||
}
|
||||
d := deltas[0]
|
||||
if d.FromLSN != 0 || d.ToLSN != cut || d.Gen != head.Gen || len(d.Dirty) != 1 || d.Dirty[0] != 3 || d.NewKeys[3] != head.Chunks[3].Key {
|
||||
t.Fatalf("delta %+v, want {from 0 to %d gen %d dirty [3] key %q}", d, cut, head.Gen, head.Chunks[3].Key)
|
||||
}
|
||||
if bm.persisted(3) {
|
||||
t.Fatal("chunk 3 is still marked dirty in the new period although the cut captured it")
|
||||
}
|
||||
|
||||
// A failed save refuses the advance; the WAL keeps the entry.
|
||||
bm.mu.Lock()
|
||||
bm.failSave = errors.New("injected bitmap save failure")
|
||||
bm.mu.Unlock()
|
||||
lsn20 := w.write(t, s, 20, 0x50) // chunk 5
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cpBefore, tailBefore := s.CheckpointLSN(), walLogicalTail(s)
|
||||
if err := flushWithin(t, s, "flush with a failing bitmap save"); err == nil {
|
||||
t.Fatal("the flusher advanced although the bitmap could not be saved")
|
||||
}
|
||||
if cp, tail := s.CheckpointLSN(), walLogicalTail(s); cp != cpBefore || tail != tailBefore || cp >= lsn20 {
|
||||
t.Fatalf("failed save moved checkpoint %d -> %d or WAL tail %d -> %d (LSN %d unprotected)", cpBefore, cp, tailBefore, tail, lsn20)
|
||||
}
|
||||
bm.mu.Lock()
|
||||
bm.failSave = nil
|
||||
bm.mu.Unlock()
|
||||
crash()
|
||||
s2, _ := legacyReopen(t, path)
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
before := f.stats()
|
||||
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("capture after restart: %v", err)
|
||||
}
|
||||
if n := f.stats().puts - before.puts; n != 1 {
|
||||
t.Fatalf("capture after restart stored %d chunks, want 1 (chunk 5, known only from the WAL)", n)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
}
|
||||
|
||||
// C11 rollover: while a cut's upload is held, a post-cut write is flushed
|
||||
// and its WAL recycled (so only the bitmap remembers it). The cut's Reset
|
||||
// must keep that chunk dirty, and after a crash the next capture uploads it.
|
||||
func TestChunkLayer_C11_RolloverKeepsPostCutDirt(t *testing.T) {
|
||||
s, path, crash := legacyCrashableStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 4, 0x14) // chunk 1, captured by the held cut
|
||||
|
||||
entered, release := holdPuts(t, f)
|
||||
done := startCapture(t, layer)
|
||||
waitKey(t, entered, "held cut upload")
|
||||
within(t, "post-cut write, sync and flush while the cut is held", func() error {
|
||||
data := makeBlock(ctBlockSize, 0x26)
|
||||
lsn, err := s.Write(24, data) // chunk 6, after the cut
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.record(lsn, 24, data)
|
||||
if _, err := s.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.flusher.flushOnce()
|
||||
})
|
||||
release()
|
||||
if err := waitErr(t, done, "held cut"); err != nil {
|
||||
t.Fatalf("held cut: %v", err)
|
||||
}
|
||||
if !bm.persisted(6) {
|
||||
t.Fatal("the cut's Reset cleared chunk 6, dirtied after the cut with its WAL already recycled")
|
||||
}
|
||||
if bm.persisted(1) {
|
||||
t.Fatal("the cut's Reset kept chunk 1, which the cut captured")
|
||||
}
|
||||
crash()
|
||||
s2, _ := legacyReopen(t, path)
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
before := f.stats()
|
||||
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("capture after restart: %v", err)
|
||||
}
|
||||
if n := f.stats().puts - before.puts; n != 1 {
|
||||
t.Fatalf("capture after restart stored %d chunks, want 1 (chunk 6)", n)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
}
|
||||
|
||||
// c11BaseFixture: HEAD covers chunks 0 and 5; then a BASE rebuild rewrites
|
||||
// LBA 20 (chunk 5) and LBA 24 (chunk 6) through WriteExtentDirect, advances
|
||||
// the frontier and Syncs (the direct-frontier checkpoint path).
|
||||
// - failSave: the bitmap save on that path fails. Sync must return an
|
||||
// error and leave the checkpoint and the physical WAL tail unchanged,
|
||||
// and EndBaseInstall must refuse because the frontier is not durable.
|
||||
// - otherwise the checkpoint reaches the frontier; complete then also
|
||||
// calls EndBaseInstall(frontier), which must durably record the
|
||||
// completed install.
|
||||
//
|
||||
// Then the host crashes.
|
||||
func c11BaseFixture(t *testing.T, failSave, complete bool) (path string, f *fakeChunkRemote, cfg chunkLayerConfig, frontier uint64) {
|
||||
t.Helper()
|
||||
s, path, crash := legacyCrashableStore(t)
|
||||
f = newFakeChunkRemote()
|
||||
cfg = ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 1, 0x01) // chunk 0
|
||||
last := w.write(t, s, 21, 0x21) // chunk 5
|
||||
// Flush first: the direct-frontier checkpoint below covers every LSN up
|
||||
// to the frontier, so recovery would skip unflushed WAL entries (a real
|
||||
// rebuild installs the whole image).
|
||||
mustSyncFlush(t, s)
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := layer.BeginBaseInstall(); err != nil {
|
||||
t.Fatalf("BeginBaseInstall: %v", err)
|
||||
}
|
||||
if hdr, _, _ := bm.snapshot(); hdr.Base != chunkBaseInstalling {
|
||||
t.Fatalf("BeginBaseInstall returned before an installing header was durable (header %+v)", hdr)
|
||||
}
|
||||
if _, err := layer.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
|
||||
t.Fatalf("Capture during a BASE install: got %v, want errChunkCaptureRefused", err)
|
||||
}
|
||||
frontier = last + 10
|
||||
for lba, fill := range map[uint32]byte{20: 0xB5, 24: 0xB6} {
|
||||
if err := s.WriteExtentDirect(lba, makeBlock(ctBlockSize, fill)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := layer.EndBaseInstall(frontier); err == nil {
|
||||
t.Fatal("EndBaseInstall accepted a frontier that is not durable yet")
|
||||
}
|
||||
if failSave {
|
||||
bm.mu.Lock()
|
||||
bm.failSave = errors.New("injected bitmap save failure")
|
||||
bm.mu.Unlock()
|
||||
}
|
||||
s.AdvanceFrontier(frontier)
|
||||
cpBefore, tailBefore := s.CheckpointLSN(), walLogicalTail(s)
|
||||
_, syncErr := s.Sync() // persists the direct frontier as the checkpoint
|
||||
if failSave {
|
||||
if syncErr == nil {
|
||||
t.Fatal("BASE Sync succeeded although its bitmap save failed")
|
||||
}
|
||||
if cp, tail := s.CheckpointLSN(), walLogicalTail(s); cp != cpBefore || tail != tailBefore {
|
||||
t.Fatalf("failed bitmap save still moved checkpoint %d -> %d or WAL tail %d -> %d", cpBefore, cp, tailBefore, tail)
|
||||
}
|
||||
if err := layer.EndBaseInstall(frontier); err == nil {
|
||||
t.Fatal("EndBaseInstall accepted a frontier whose checkpoint was refused")
|
||||
}
|
||||
bm.mu.Lock()
|
||||
bm.failSave = nil
|
||||
bm.mu.Unlock()
|
||||
} else {
|
||||
if syncErr != nil {
|
||||
t.Fatalf("BASE Sync: %v", syncErr)
|
||||
}
|
||||
if cp := s.CheckpointLSN(); cp < frontier {
|
||||
t.Fatalf("BASE Sync returned nil but the checkpoint is %d < frontier %d", cp, frontier)
|
||||
}
|
||||
if complete {
|
||||
if err := layer.EndBaseInstall(frontier); err != nil {
|
||||
t.Fatalf("EndBaseInstall after the durable frontier: %v", err)
|
||||
}
|
||||
if hdr, _, _ := bm.snapshot(); hdr.Base != chunkBaseInstalledAwaitingCut {
|
||||
t.Fatalf("EndBaseInstall returned before the completed install was durable (header %+v)", hdr)
|
||||
}
|
||||
}
|
||||
}
|
||||
crash()
|
||||
return path, f, cfg, frontier
|
||||
}
|
||||
|
||||
// assertBaseCutUploadsChangedChunks runs the first cut after a BASE rebuild:
|
||||
// a full hash compare that stores exactly chunks 5 and 6, keeps chunk 0's
|
||||
// ref, publishes the BASE blocks, and leaves a normal header for the new HEAD.
|
||||
func assertBaseCutUploadsChangedChunks(t *testing.T, layer chunkLayer, f *fakeChunkRemote, cfg chunkLayerConfig) {
|
||||
t.Helper()
|
||||
before := f.stats()
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("first cut after the rebuild: %v", err)
|
||||
}
|
||||
after := f.stats()
|
||||
if n := after.puts - before.puts; n != 2 {
|
||||
t.Fatalf("first cut after the rebuild stored %d chunks, want 2 (chunks 5 and 6)", n)
|
||||
}
|
||||
if after.head.Chunks[0] != before.head.Chunks[0] {
|
||||
t.Fatal("unchanged chunk 0 was re-published")
|
||||
}
|
||||
for lba, fill := range map[uint32]byte{20: 0xB5, 24: 0xB6} {
|
||||
if got := blockOf(f.imageOf(t, after.head), lba); !bytes.Equal(got, makeBlock(ctBlockSize, fill)) {
|
||||
t.Fatalf("BASE block LBA %d missing from the post-rebuild HEAD", lba)
|
||||
}
|
||||
}
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
if hdr, _, _ := bm.snapshot(); hdr.Base != chunkBaseNone || hdr.HeadGen != after.head.Gen {
|
||||
t.Fatalf("header after the post-rebuild cut %+v, want a normal header for HEAD gen %d", hdr, after.head.Gen)
|
||||
}
|
||||
assertNoRemoteMisuse(t, f)
|
||||
}
|
||||
|
||||
// rerunBase repeats a complete BASE install of the same blocks after a
|
||||
// restart, as the owner must after an interrupted one.
|
||||
func rerunBase(t *testing.T, s *WALStore, layer chunkLayer, frontier uint64) {
|
||||
t.Helper()
|
||||
if err := layer.BeginBaseInstall(); err != nil {
|
||||
t.Fatalf("BeginBaseInstall after restart: %v", err)
|
||||
}
|
||||
for lba, fill := range map[uint32]byte{20: 0xB5, 24: 0xB6} {
|
||||
if err := s.WriteExtentDirect(lba, makeBlock(ctBlockSize, fill)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s.AdvanceFrontier(frontier)
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatalf("BASE Sync after restart: %v", err)
|
||||
}
|
||||
if err := layer.EndBaseInstall(frontier); err != nil {
|
||||
t.Fatalf("EndBaseInstall after restart: %v", err)
|
||||
}
|
||||
waitReconciledForTest(t, layer) // the BASE is reconciled against HEAD first
|
||||
}
|
||||
|
||||
// C11 BASE: recovery never infers that an install finished. An install
|
||||
// interrupted by a crash (header still installing) keeps cuts refused after
|
||||
// restart until the owner completes a new install; a completed install
|
||||
// (EndBaseInstall durable) allows the first cut, which hashes fully. With
|
||||
// the bitmap save failing on the direct-frontier path, Sync errors and
|
||||
// neither the checkpoint nor the WAL tail moves.
|
||||
func TestChunkLayer_C11_BaseRebuildRecovery(t *testing.T) {
|
||||
t.Run("interrupted install", func(t *testing.T) {
|
||||
path, f, cfg, frontier := c11BaseFixture(t, false, false)
|
||||
s2, _ := legacyReopen(t, path)
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
before := f.stats()
|
||||
if _, err := layer2.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
|
||||
t.Fatalf("cut after an interrupted install: got %v, want errChunkCaptureRefused", err)
|
||||
}
|
||||
if after := f.stats(); after.puts != before.puts || after.cas != before.cas {
|
||||
t.Fatal("refused cut made remote calls")
|
||||
}
|
||||
rerunBase(t, s2, layer2, frontier)
|
||||
assertBaseCutUploadsChangedChunks(t, layer2, f, cfg)
|
||||
})
|
||||
t.Run("completed install", func(t *testing.T) {
|
||||
path, f, cfg, _ := c11BaseFixture(t, false, true)
|
||||
s2, _ := legacyReopen(t, path)
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
assertBaseCutUploadsChangedChunks(t, layer2, f, cfg)
|
||||
})
|
||||
t.Run("bitmap save fails on the direct-frontier path", func(t *testing.T) {
|
||||
path, f, cfg, frontier := c11BaseFixture(t, true, false)
|
||||
s2, _ := legacyReopen(t, path)
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
if _, err := layer2.Capture(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) {
|
||||
t.Fatalf("cut after an install whose frontier never became durable: got %v, want errChunkCaptureRefused", err)
|
||||
}
|
||||
rerunBase(t, s2, layer2, frontier)
|
||||
assertBaseCutUploadsChangedChunks(t, layer2, f, cfg)
|
||||
})
|
||||
}
|
||||
|
||||
// C11 over-report only: the bitmap save succeeds but the checkpoint publish
|
||||
// then fails; after a crash the next capture may over-report, but its image
|
||||
// is exact and nothing is missed.
|
||||
func TestChunkLayer_C11_SaveThenCheckpointFailureOverReportsOnly(t *testing.T) {
|
||||
s, path, crash := legacyCrashableStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 1, 0x01)
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.write(t, s, 24, 0x24) // chunk 6
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.syncSuperblockMetadata = func() error { return errors.New("injected checkpoint sync failure") }
|
||||
if err := flushWithin(t, s, "flush whose checkpoint publish fails"); err == nil {
|
||||
t.Fatal("the flush succeeded although its checkpoint publish failed")
|
||||
}
|
||||
crash()
|
||||
s2, _ := legacyReopen(t, path)
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("capture after restart: %v", err)
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
}
|
||||
|
||||
// c11RestartFixture: HEAD covers chunks 0 and 5; then chunk 6 is written and
|
||||
// flushed (its WAL recycled, so only the persisted bitmap remembers it) and
|
||||
// chunk 7 is written and synced but not flushed (only the WAL remembers
|
||||
// it); then the host crashes and recovers. Whatever beforeReattach does to
|
||||
// the persisted bitmap, the next capture must upload exactly chunks 6 and 7
|
||||
// and keep the refs of the unchanged chunks.
|
||||
func c11RestartFixture(t *testing.T, beforeReattach func(bm *fakeBitmapStore)) {
|
||||
t.Helper()
|
||||
s, path, crash := legacyCrashableStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 1, 0x01) // chunk 0
|
||||
w.write(t, s, 21, 0x21) // chunk 5
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.write(t, s, 24, 0x24) // chunk 6: flushed, WAL recycled
|
||||
mustSyncFlush(t, s)
|
||||
w.write(t, s, 28, 0x28) // chunk 7: synced only
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crash()
|
||||
s2, _ := legacyReopen(t, path)
|
||||
if beforeReattach != nil {
|
||||
bm.mu.Lock()
|
||||
beforeReattach(bm)
|
||||
bm.mu.Unlock()
|
||||
}
|
||||
layer2 := mustAttach(t, s2, f, cfg)
|
||||
before := f.stats()
|
||||
if _, err := layer2.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("capture after restart: %v", err)
|
||||
}
|
||||
after := f.stats()
|
||||
if n := after.puts - before.puts; n != 2 {
|
||||
t.Fatalf("capture after restart stored %d chunks, want exactly 2 (chunks 6 and 7)", n)
|
||||
}
|
||||
for _, idx := range []uint64{0, 5} {
|
||||
if after.head.Chunks[idx] != before.head.Chunks[idx] {
|
||||
t.Fatalf("unchanged chunk %d was re-published under a new ref", idx)
|
||||
}
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
for _, h := range f.installedHeads() {
|
||||
for idx, ref := range h.Chunks {
|
||||
if ref.SHA256 == ([32]byte{}) {
|
||||
t.Fatalf("HEAD gen %d chunk %d carries no SHA-256", h.Gen, idx)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// C11 restart, header matches HEAD: incremental, dirty = persisted bitmap ∪
|
||||
// chunks of WAL entries above the checkpoint; nothing missed, nothing
|
||||
// unchanged re-sent.
|
||||
func TestChunkLayer_C11_IncrementalAfterRestart(t *testing.T) {
|
||||
c11RestartFixture(t, nil)
|
||||
}
|
||||
|
||||
// C11 fallback: a lost bitmap, or a header that differs from HEAD in any
|
||||
// field (including a completed BASE awaiting its first cut), falls back to a per-chunk SHA-256
|
||||
// compare and uploads only the chunks whose bytes differ.
|
||||
func TestChunkLayer_C11_LostOrMismatchedBitmapFallsBackToHashCompare(t *testing.T) {
|
||||
for name, mutate := range map[string]func(bm *fakeBitmapStore){
|
||||
"lost": func(bm *fakeBitmapStore) { bm.lostNext = true },
|
||||
"head gen mismatch": func(bm *fakeBitmapStore) { bm.hdr.HeadGen += 7; bm.dirty = map[uint64]bool{} },
|
||||
"epoch mismatch": func(bm *fakeBitmapStore) { bm.hdr.Epoch++; bm.dirty = map[uint64]bool{} },
|
||||
"base lsn mismatch": func(bm *fakeBitmapStore) { bm.hdr.BaseLSN += 3; bm.dirty = map[uint64]bool{} },
|
||||
"completed BASE awaiting its first cut": func(bm *fakeBitmapStore) { bm.hdr.Base = chunkBaseInstalledAwaitingCut; bm.dirty = map[uint64]bool{} },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) { c11RestartFixture(t, mutate) })
|
||||
}
|
||||
}
|
||||
|
||||
// C11 replica: the replica apply path goes through the same flusher, so a
|
||||
// promoted replica's bitmap covers its applied chunks before their WAL
|
||||
// entries are recycled.
|
||||
func TestChunkLayer_C11_ReplicaApplyKeepsBitmap(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
mustAttach(t, s, f, cfg)
|
||||
saves := recordSaves(s, bm)
|
||||
const applied = 5
|
||||
if err := s.ApplyEntry(16, makeBlock(ctBlockSize, 0x16), applied); err != nil { // chunk 4
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tailBefore := walLogicalTail(s)
|
||||
if err := flushWithin(t, s, "flush of the applied entry"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
row, ok := saves.firstSaveWith(4)
|
||||
if !ok {
|
||||
t.Fatal("replica apply: chunk 4's WAL entry was recycled without a bitmap save covering it")
|
||||
}
|
||||
if row.checkpoint >= applied || row.walTail != tailBefore {
|
||||
t.Fatalf("replica chunk 4 saved at checkpoint %d / WAL tail %d, after the advance (applied %d, tail before %d)", row.checkpoint, row.walTail, applied, tailBefore)
|
||||
}
|
||||
if got := extentBytes(t, s, 16); !bytes.Equal(got, makeBlock(ctBlockSize, 0x16)) {
|
||||
t.Fatal("applied entry did not reach the extent")
|
||||
}
|
||||
}
|
||||
@@ -44,25 +44,3 @@ func TestChunkLayer_FreshVolumeStartsWithEmptyBitmap(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Control: an existing volume (not fresh) without a bitmap reconciles its
|
||||
// local image against HEAD before it publishes, so a chunk that differs
|
||||
// from HEAD without a recorded write is still uploaded by its first cut.
|
||||
func TestChunkLayer_LostBitmapReconciles(t *testing.T) {
|
||||
src := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(src, makeBlock(ctBlockSize, 0x44)) // HEAD's block 0 differs from the local image
|
||||
f := newFakeChunkRemote()
|
||||
f.seedHead(t, src, 0, 0) // an older epoch: this holder may publish over it
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
layer := mustAttach(t, s, f, ctConfig(1)) // waits for reconciliation
|
||||
if st := layer.Stats(); st.Reconciling || st.ReconcileTotal == 0 || st.ReconcileDone != st.ReconcileTotal {
|
||||
t.Fatalf("an existing volume without a bitmap did not reconcile: reconciling=%v done=%d/%d", st.Reconciling, st.ReconcileDone, st.ReconcileTotal)
|
||||
}
|
||||
w := newWriteLog()
|
||||
w.write(t, s, ctNumBlocks-1, 0x33) // the last chunk, never HEAD's block 0 chunk
|
||||
r, err := layer.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertImage(t, "first cut after reconciliation vs the local image", f.imageOf(t, r.Head), w.imageAt(r.H))
|
||||
}
|
||||
@@ -6,41 +6,6 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// HEAD's remote_lsn never decreases (B9 W2 appendix): a
|
||||
// host whose log is behind HEAD (a fresh or migrated host before W4b carries
|
||||
// LSN continuity) cannot cut or detach; nothing is uploaded and no CAS is
|
||||
// sent. Once its log continues from HEAD's remote_lsn, it cuts.
|
||||
func TestChunkCut_RemoteLSNNeverDecreases(t *testing.T) {
|
||||
src := make([]byte, ctNumBlocks*ctBlockSize)
|
||||
copy(src, makeBlock(ctBlockSize, 0x44))
|
||||
f := newFakeChunkRemote()
|
||||
f.seedHead(t, src, 10, 1)
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 3, 0x33) // local LSN 1, HEAD remote_lsn 10
|
||||
before := f.stats()
|
||||
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errChunkLSNBehind) {
|
||||
t.Fatalf("cut behind HEAD's remote_lsn: %v; want refused with errChunkLSNBehind", err)
|
||||
}
|
||||
if _, err := layer.Detach(ctTimeout(t)); !errors.Is(err, errChunkLSNBehind) {
|
||||
t.Fatalf("detach behind HEAD's remote_lsn: %v; want errChunkLSNBehind", err)
|
||||
}
|
||||
after := f.stats()
|
||||
if after.cas != before.cas || after.puts != before.puts || after.head.Gen != before.head.Gen {
|
||||
t.Fatalf("a refused cut published: %d CAS, %d puts, HEAD gen %d -> %d", after.cas-before.cas, after.puts-before.puts, before.head.Gen, after.head.Gen)
|
||||
}
|
||||
|
||||
s.AdvanceFrontier(10) // continuity from HEAD (W4b's job in production)
|
||||
w.write(t, s, 4, 0x34)
|
||||
r, err := layer.Cut(ctTimeout(t))
|
||||
if err != nil || r.Head.RemoteLSN < 10 || r.Head.Gen != before.head.Gen+1 {
|
||||
t.Fatalf("cut once the log continues from HEAD: %+v %v", r.Head, err)
|
||||
}
|
||||
}
|
||||
|
||||
// MemChunkRemote refuses a proposal that lowers remote_lsn.
|
||||
func TestMemChunkRemote_RefusesLowerRemoteLSN(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -6,7 +6,7 @@ package storage
|
||||
func (l *chunkLayerImpl) usesOwnedMapV3() bool { return l.s.v3 != nil && l.s.v3.mapProof != nil }
|
||||
|
||||
// persistCapturedMapV3 is called only after HEAD's publication is definite
|
||||
// (or an authority-checked no-op), outside bmMu/stMu and the capture barrier.
|
||||
// (or an authority-checked no-op), outside stMu and the capture barrier.
|
||||
// The capture's mutation versions were sampled under the quiesced barrier.
|
||||
// Store.mu prevents a WAL append from slipping between the version check and
|
||||
// the UNKNOWN update. A later WAL append updates max LSN and stays retained;
|
||||
|
||||
@@ -6,12 +6,10 @@ package storage
|
||||
// write reached it since staging, so the image at H stays exact.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// precopyLayer attaches a fresh layer with the given barrier bound and
|
||||
@@ -203,63 +201,6 @@ func TestChunkPrecopy_WriteRightAfterStagingReadIsNotLost(t *testing.T) {
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
}
|
||||
|
||||
// A replica apply may land a block at an LSN below another block of the
|
||||
// same chunk (the highest LSN in the chunk does not move). It still makes
|
||||
// the staged copy stale: the barrier copies the chunk again and HEAD has
|
||||
// the applied bytes, whether the apply is still in the WAL or flushed.
|
||||
func TestChunkPrecopy_LowerLSNApplyAfterStagingIsNotLost(t *testing.T) {
|
||||
for _, flushed := range []bool{false, true} {
|
||||
name := map[bool]string{true: "flushed", false: "in the WAL"}[flushed]
|
||||
t.Run(name, func(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.BarrierBound = 1
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
a, b, b2, c := makeBlock(ctBlockSize, 0xa0), makeBlock(ctBlockSize, 0xb5), makeBlock(ctBlockSize, 0xb6), makeBlock(ctBlockSize, 0xc1)
|
||||
for _, e := range []struct {
|
||||
lba uint32
|
||||
data []byte
|
||||
lsn uint64
|
||||
}{{1, b, 5}, {0, a, 10}, {ctChunkBlocks, c, 11}} { // chunk 0 holds a@10 and b@5; chunk 1 c@11
|
||||
if err := s.ApplyEntry(e.lba, e.data, e.lsn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
applied := false
|
||||
l.testAfterStageReadHook = func(idx uint64) {
|
||||
if idx == 0 && !applied { // chunk 0 is staged with b@5
|
||||
applied = true
|
||||
if err := s.ApplyEntry(1, b2, 6); err != nil { // the production apply path
|
||||
t.Errorf("apply b@6: %v", err)
|
||||
}
|
||||
if flushed {
|
||||
mustSyncFlush(t, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !applied || r.Stats.StagedChunks == 0 {
|
||||
t.Fatalf("schedule did not run: applied=%v staged=%d", applied, r.Stats.StagedChunks)
|
||||
}
|
||||
img := f.imageOf(t, r.Head)
|
||||
for _, want := range []struct {
|
||||
lba int
|
||||
data []byte
|
||||
}{{0, a}, {1, b2}, {ctChunkBlocks, c}} {
|
||||
if got := img[want.lba*ctBlockSize : (want.lba+1)*ctBlockSize]; !bytes.Equal(got, want.data) {
|
||||
t.Fatalf("HEAD at H=%d: LBA %d is %#x..., want %#x... (the b@6 apply after staging lost)", r.H, want.lba, got[0], want.data[0])
|
||||
}
|
||||
}
|
||||
assertNoIntentsLeft(t, f)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A barrier Sync that fails after staging uploaded keys is a clean abort:
|
||||
// the cut's staging intents are deleted (a failed delete is kept and
|
||||
// retried by the next cut), and the next cut publishes the exact image.
|
||||
@@ -306,128 +247,3 @@ func TestChunkPrecopy_BarrierSyncFailureSettlesStagedIntents(t *testing.T) {
|
||||
assertEveryHeadIsPrefixImage(t, f, w)
|
||||
assertNoIntentsLeft(t, f)
|
||||
}
|
||||
|
||||
// Recover republishes the dirty map outside the write path: a complete newer
|
||||
// record past the head (what a failed append can leave) is published by a
|
||||
// same-open Recover. A chunk staged before it must not be reused:
|
||||
// HEAD at the recovered H has the recovered bytes.
|
||||
func TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage(t *testing.T) {
|
||||
s, f, l, _ := legacyPrecopyLayer(t, 1, 3) // chunk 0 staged in round 0; bound 1
|
||||
want := makeBlock(ctBlockSize, 0xa7)
|
||||
recovered := false
|
||||
l.testAfterStageHook = func(round int) {
|
||||
if round != 0 {
|
||||
return
|
||||
}
|
||||
plantRecordPastHead(t, s, 0, want)
|
||||
if _, err := s.Recover(); err != nil { // same open, before the barrier
|
||||
t.Errorf("same-open Recover: %v", err)
|
||||
return
|
||||
}
|
||||
if got, err := s.Read(0); err != nil || !bytes.Equal(got, want) {
|
||||
t.Errorf("valid prefix not recovered: err=%v", err)
|
||||
return
|
||||
}
|
||||
recovered = true
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !recovered || r.Stats.StagedChunks == 0 {
|
||||
t.Fatalf("schedule did not run: recovered=%v staged=%d", recovered, r.Stats.StagedChunks)
|
||||
}
|
||||
img := f.imageOf(t, r.Head)
|
||||
if got := img[:ctBlockSize]; !bytes.Equal(got, want) {
|
||||
t.Fatalf("HEAD at H=%d: LBA 0 is %#x..., want the recovered %#x... (a stage from before Recover reused)", r.H, got[0], want[0])
|
||||
}
|
||||
assertNoIntentsLeft(t, f)
|
||||
}
|
||||
|
||||
// partialBatchPrefix leaves a complete, CRC-valid record for want at the
|
||||
// next LSN past the head, the bytes a failed append can leave behind, without
|
||||
// failing an append (which latches the open store): same-open Recover
|
||||
// republishes it.
|
||||
func partialBatchPrefix(t *testing.T, s *WALStore, want []byte) {
|
||||
t.Helper()
|
||||
plantRecordPastHead(t, s, 0, want)
|
||||
}
|
||||
|
||||
// plantRecordPastHead writes a complete write record for lba at the next LSN
|
||||
// at the WAL head, without publishing it.
|
||||
func plantRecordPastHead(t *testing.T, s *WALStore, lba uint64, data []byte) {
|
||||
t.Helper()
|
||||
e := walEntry{LSN: s.NextLSN(), Type: walEntryWrite, LBA: lba, Length: uint32(len(data)), Data: data}
|
||||
buf, err := e.encode()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
off := int64(s.sb.WALOffset + s.wal.physicalPos(s.wal.logicalHeadValue()))
|
||||
if _, err := s.fd.WriteAt(buf, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A cut parked right after its barrier Sync fixed H: a same-open Recover
|
||||
// that would republish a newer complete record (H+1) waits for the
|
||||
// barrier, so the cut's HEAD at H never holds post-H bytes; the recovered
|
||||
// bytes are published by the next cut.
|
||||
func TestChunkCut_RecoverWaitsForTheCaptureBarrier(t *testing.T) {
|
||||
s, f, l, w := legacyPrecopyLayer(t, 0, 2) // no bound: the barrier copies all
|
||||
newer := makeBlock(ctBlockSize, 0xa7)
|
||||
partialBatchPrefix(t, s, newer)
|
||||
recovered := make(chan error, 1)
|
||||
parked := false
|
||||
l.testAfterBarrierSyncHook = func(h uint64) {
|
||||
parked = true
|
||||
go func() { _, err := s.Recover(); recovered <- err }()
|
||||
select {
|
||||
case err := <-recovered:
|
||||
t.Errorf("Recover ran inside the capture barrier after Sync fixed H=%d (err %v)", h, err)
|
||||
case <-time.After(300 * time.Millisecond): // held: it waits for the barrier
|
||||
}
|
||||
}
|
||||
r, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !parked {
|
||||
t.Fatal("the cut never reached the post-Sync hook")
|
||||
}
|
||||
assertEveryHeadIsPrefixImage(t, f, w) // HEAD at H is the image at H: no 0xa7
|
||||
if got := f.imageOf(t, r.Head)[:ctBlockSize]; bytes.Equal(got, newer) {
|
||||
t.Fatalf("HEAD at H=%d holds the post-H recovered bytes", r.H)
|
||||
}
|
||||
select {
|
||||
case err := <-recovered:
|
||||
if err != nil {
|
||||
t.Fatalf("Recover after the barrier: %v", err)
|
||||
}
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("Recover never ran after the barrier was released")
|
||||
}
|
||||
l.testAfterBarrierSyncHook = nil
|
||||
r2, err := l.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := f.imageOf(t, r2.Head)[:ctBlockSize]; !bytes.Equal(got, newer) || r2.H <= r.H {
|
||||
t.Fatalf("next cut H=%d (prev %d): LBA 0 %#x..., want the recovered %#x...", r2.H, r.H, got[0], newer[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TODO(format-v3 row 14a): raw v2 surgery/nonmonotone fixture only.
|
||||
func legacyPrecopyLayer(t *testing.T, bound, n int) (*WALStore, *fakeChunkRemote, *chunkLayerImpl, *writeLog) {
|
||||
t.Helper()
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
cfg.FreshFromHead = true
|
||||
cfg.BarrierBound = bound
|
||||
l := mustAttach(t, s, f, cfg).(*chunkLayerImpl)
|
||||
w := newWriteLog()
|
||||
for c := 0; c < n; c++ {
|
||||
w.write(t, s, uint32(c*ctChunkBlocks+1), byte(0x10+c))
|
||||
}
|
||||
return s, f, l, w
|
||||
}
|
||||
@@ -5,10 +5,6 @@ package storage
|
||||
// outside the capture barrier. No HEAD moves until it is done.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -23,235 +19,8 @@ type reconcileFixture struct {
|
||||
path string
|
||||
}
|
||||
|
||||
// newReconcileFixture publishes chunks 0 and 5, leaves chunk 6 flushed and
|
||||
// chunk 7 synced only, crashes, loses the bitmap and reattaches. With hold
|
||||
// the reconciler is held before its first slice.
|
||||
func newReconcileFixture(t *testing.T, hold bool) *reconcileFixture {
|
||||
return newReconcileFixtureWith(t, hold, func(bm *fakeBitmapStore) { bm.lostNext = true })
|
||||
}
|
||||
|
||||
// newReconcileFixtureWith reattaches after mutate damaged the bitmap.
|
||||
func newReconcileFixtureWith(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore)) *reconcileFixture {
|
||||
t.Helper()
|
||||
return newReconcileFixtureOpts(t, hold, mutate, nil)
|
||||
}
|
||||
|
||||
// newReconcileFixtureOpts also lets mutateCfg adjust the reattach config.
|
||||
func newReconcileFixtureOpts(t *testing.T, hold bool, mutate func(bm *fakeBitmapStore), mutateCfg func(cfg *chunkLayerConfig)) *reconcileFixture {
|
||||
t.Helper()
|
||||
s, path, crash := legacyCrashableStore(t)
|
||||
f := newFakeChunkRemote()
|
||||
cfg := ctConfig(1)
|
||||
bm := cfg.Bitmap.(*fakeBitmapStore)
|
||||
layer := mustAttach(t, s, f, cfg)
|
||||
w := newWriteLog()
|
||||
w.write(t, s, 1, 0x01) // chunk 0
|
||||
w.write(t, s, 21, 0x21) // chunk 5
|
||||
if _, err := layer.Capture(ctTimeout(t)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w.write(t, s, 24, 0x24) // chunk 6: flushed
|
||||
mustSyncFlush(t, s)
|
||||
w.write(t, s, 28, 0x28) // chunk 7: synced only
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crash()
|
||||
s2, _ := legacyReopen(t, path)
|
||||
bm.mu.Lock()
|
||||
mutate(bm)
|
||||
bm.mu.Unlock()
|
||||
fx := &reconcileFixture{s: s2, f: f, bm: bm, cfg: cfg, path: path}
|
||||
if hold {
|
||||
fx.hold = make(chan struct{})
|
||||
fx.cfg.testReconcileHold = fx.hold
|
||||
}
|
||||
if mutateCfg != nil {
|
||||
mutateCfg(&fx.cfg)
|
||||
}
|
||||
l, err := attachChunkLayer(s2, f, fx.cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if fx.hold != nil {
|
||||
select {
|
||||
case <-fx.hold:
|
||||
default:
|
||||
close(fx.hold)
|
||||
}
|
||||
}
|
||||
_ = l.Close()
|
||||
})
|
||||
fx.layer = l
|
||||
return fx
|
||||
}
|
||||
|
||||
func (fx *reconcileFixture) release() { close(fx.hold) }
|
||||
|
||||
func TestChunkReconcile_NoHeadMovesWhileReconciling(t *testing.T) {
|
||||
fx := newReconcileFixture(t, true)
|
||||
st := fx.layer.Stats()
|
||||
if !st.Reconciling || st.ReconcileTotal == 0 || st.ReconcileDone != 0 {
|
||||
t.Fatalf("stats while held: reconciling=%v done=%d/%d", st.Reconciling, st.ReconcileDone, st.ReconcileTotal)
|
||||
}
|
||||
if st.DirtyChunks != 0 {
|
||||
t.Fatalf("the reconcile obligation counted as %d dirty chunks", st.DirtyChunks)
|
||||
}
|
||||
before := fx.f.stats()
|
||||
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
|
||||
t.Fatalf("Cut while reconciling: %v", err)
|
||||
}
|
||||
if err := fx.layer.MakeRemoteDurable(ctTimeout(t), 1); !errors.Is(err, errChunkReconciling) {
|
||||
t.Fatalf("MakeRemoteDurable while reconciling: %v", err)
|
||||
}
|
||||
if after := fx.f.stats(); after.puts != before.puts || after.cas != before.cas || after.getHeads != before.getHeads {
|
||||
t.Fatalf("refused cuts made remote calls: %+v -> %+v", before, after)
|
||||
}
|
||||
if got := fx.layer.Stats().CutsRefused["reconciling"]; got != 2 {
|
||||
t.Fatalf("reconciling refusals %d, want 2", got)
|
||||
}
|
||||
fx.release()
|
||||
waitReconciledForTest(t, fx.layer)
|
||||
if d := fx.layer.Stats().DirtyChunks; d != 2 {
|
||||
t.Fatalf("dirty chunks after reconciliation: %d, want 2 (chunks 6 and 7)", d)
|
||||
}
|
||||
before = fx.f.stats()
|
||||
r, err := fx.layer.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatalf("Cut after reconciliation: %v", err)
|
||||
}
|
||||
if n := fx.f.stats().puts - before.puts; n != 2 || r.FullHash {
|
||||
t.Fatalf("first cut after reconciliation stored %d chunks (fullHash=%v), want exactly 2 and no full hash", n, r.FullHash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkReconcile_WritesProceedWhileReconciling(t *testing.T) {
|
||||
fx := newReconcileFixture(t, true)
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := fx.s.Write(9, makeBlock(ctBlockSize, 0x09)); done <- err }() // chunk 2
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("a write blocked behind the reconciliation")
|
||||
}
|
||||
if _, err := fx.s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fx.release()
|
||||
waitReconciledForTest(t, fx.layer)
|
||||
r, err := fx.layer.Cut(ctTimeout(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := r.Head.Chunks[2]; !ok {
|
||||
t.Fatal("the write made during reconciliation is missing from the next HEAD")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkReconcile_DetachWaitsForReconciliation(t *testing.T) {
|
||||
fx := newReconcileFixture(t, true)
|
||||
errc := make(chan error, 1)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_, err := fx.layer.Detach(ctx)
|
||||
errc <- err
|
||||
}()
|
||||
select {
|
||||
case err := <-errc:
|
||||
t.Fatalf("Detach returned while reconciling: %v", err)
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
fx.release()
|
||||
select {
|
||||
case err := <-errc:
|
||||
if err != nil {
|
||||
t.Fatalf("Detach after reconciliation: %v", err)
|
||||
}
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("Detach never returned after reconciliation")
|
||||
}
|
||||
if !chunkHeadIsDetached(fx.f.stats().head) {
|
||||
t.Fatal("HEAD not detached after the waited Detach")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkReconcile_DetachDeadlineWhileReconciling(t *testing.T) {
|
||||
fx := newReconcileFixture(t, true)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||
defer cancel()
|
||||
before := fx.f.stats()
|
||||
errc := make(chan error, 1)
|
||||
go func() { _, err := fx.layer.Detach(ctx); errc <- err }()
|
||||
select {
|
||||
case err := <-errc:
|
||||
if !errors.Is(err, errChunkReconciling) {
|
||||
t.Fatalf("Detach past its deadline while reconciling: %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Detach ignored its deadline while reconciling")
|
||||
}
|
||||
if after := fx.f.stats(); after.cas != before.cas {
|
||||
t.Fatal("a refused Detach issued a CAS")
|
||||
}
|
||||
}
|
||||
|
||||
// The reconciled dirty set is persisted with a header naming HEAD: a
|
||||
// restart trusts it and does not reconcile again.
|
||||
func TestChunkReconcile_ResultPersisted(t *testing.T) {
|
||||
// A header naming another HEAD generation: the reconciled result must
|
||||
// rewrite it, or the next attach mismatches and reconciles again.
|
||||
fx := newReconcileFixtureWith(t, false, func(bm *fakeBitmapStore) {
|
||||
bm.hdr.HeadGen += 7
|
||||
bm.dirty = map[uint64]bool{}
|
||||
})
|
||||
waitReconciledForTest(t, fx.layer)
|
||||
head := fx.f.stats().head
|
||||
fx.bm.mu.Lock()
|
||||
hdr, dirty := fx.bm.hdr, len(fx.bm.dirty)
|
||||
fx.bm.mu.Unlock()
|
||||
if hdr.HeadGen != head.Gen || hdr.Epoch != head.Epoch || hdr.BaseLSN != head.RemoteLSN || hdr.Base != chunkBaseNone || dirty != 2 {
|
||||
t.Fatalf("persisted header %+v with %d dirty chunks; want HEAD gen %d epoch %d lsn %d and 2 dirty", hdr, dirty, head.Gen, head.Epoch, head.RemoteLSN)
|
||||
}
|
||||
if err := fx.s.Close(); err != nil { // closes the layer too
|
||||
t.Fatal(err)
|
||||
}
|
||||
s3, _ := legacyReopen(t, fx.path)
|
||||
l2, err := attachChunkLayer(s3, fx.f, fx.cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l2.Close()
|
||||
if st := l2.Stats(); st.Reconciling || st.DirtyChunks != 2 {
|
||||
t.Fatalf("reattach after a persisted reconciliation: reconciling=%v dirty=%d", st.Reconciling, st.DirtyChunks)
|
||||
}
|
||||
}
|
||||
|
||||
// A failed bitmap save keeps the layer reconciling (and cuts refused) until
|
||||
// the result is persisted.
|
||||
func TestChunkReconcile_UnpersistedResultKeepsReconciling(t *testing.T) {
|
||||
fx := newReconcileFixture(t, true)
|
||||
fx.bm.mu.Lock()
|
||||
fx.bm.failSave = errors.New("injected save failure")
|
||||
fx.bm.mu.Unlock()
|
||||
fx.release()
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if st := fx.layer.Stats(); !st.Reconciling || st.ReconcileDone != st.ReconcileTotal {
|
||||
t.Fatalf("with the save failing: reconciling=%v done=%d/%d; want every chunk compared and still reconciling", st.Reconciling, st.ReconcileDone, st.ReconcileTotal)
|
||||
}
|
||||
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
|
||||
t.Fatalf("Cut with an unpersisted reconciliation: %v", err)
|
||||
}
|
||||
fx.bm.mu.Lock()
|
||||
fx.bm.failSave = nil
|
||||
fx.bm.mu.Unlock()
|
||||
waitReconciledForTest(t, fx.layer)
|
||||
}
|
||||
|
||||
// refusedOver asserts check() holds at every poll for d: a negative
|
||||
// invariant is checked over an interval, not once.
|
||||
func refusedOver(t *testing.T, d time.Duration, what string, check func() error) {
|
||||
@@ -264,154 +33,3 @@ func refusedOver(t *testing.T, d time.Duration, what string, check func() error)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// A worker reconciling a lost bitmap when a BASE install begins must not
|
||||
// finish over it: the install guard (Base=Installing) stays in force, in
|
||||
// memory and on disk, until the install itself completes.
|
||||
func TestChunkReconcile_BaseInstallSupersedesRunningReconciliation(t *testing.T) {
|
||||
fx := newReconcileFixture(t, true) // the worker is held before its first slice
|
||||
if err := fx.layer.BeginBaseInstall(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fx.release() // the old worker runs on
|
||||
refusedOver(t, 300*time.Millisecond, "after BeginBaseInstall", func() error {
|
||||
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkBaseInstalling) {
|
||||
return fmt.Errorf("Cut admitted or refused for another cause during an incomplete BASE install: %v", err)
|
||||
}
|
||||
fx.bm.mu.Lock()
|
||||
base := fx.bm.hdr.Base
|
||||
fx.bm.mu.Unlock()
|
||||
if base != chunkBaseInstalling {
|
||||
return fmt.Errorf("persisted Base=%v, want the install guard (installing)", base)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
// A restart still sees the incomplete install and refuses cuts.
|
||||
if err := fx.s.Close(); err != nil { // closes the layer too
|
||||
t.Fatal(err)
|
||||
}
|
||||
s3, _ := legacyReopen(t, fx.path)
|
||||
defer s3.Close()
|
||||
cfg := fx.cfg
|
||||
cfg.testReconcileHold = nil
|
||||
l2, err := attachChunkLayer(s3, fx.f, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l2.Close()
|
||||
if _, err := l2.Cut(ctTimeout(t)); !errors.Is(err, errChunkBaseInstalling) {
|
||||
t.Fatalf("Cut after restart during an incomplete BASE install: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An old worker that saw its set empty and paused before certifying must
|
||||
// not certify (or touch) the replacement reconciliation that a BASE
|
||||
// install started meanwhile: cuts stay refused until the replacement is
|
||||
// done.
|
||||
func TestChunkReconcile_OldCompletionCannotCertifyReplacement(t *testing.T) {
|
||||
var oldGen atomic.Uint64
|
||||
atFinish, releaseFinish, replHold := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
hook := func(stage string, gen uint64) {
|
||||
switch {
|
||||
case stage == "finish" && oldGen.CompareAndSwap(0, gen):
|
||||
close(atFinish)
|
||||
<-releaseFinish
|
||||
case stage == "batch" && oldGen.Load() != 0 && gen != oldGen.Load():
|
||||
<-replHold
|
||||
}
|
||||
}
|
||||
fx := newReconcileFixtureOpts(t, false, func(bm *fakeBitmapStore) { bm.lostNext = true },
|
||||
func(cfg *chunkLayerConfig) { cfg.testReconcileHook = hook })
|
||||
// Registered after the fixture: cleanups run last-in first-out, so the
|
||||
// workers are released before the layer closes and waits for them.
|
||||
t.Cleanup(func() {
|
||||
for _, ch := range []chan struct{}{releaseFinish, replHold} {
|
||||
select {
|
||||
case <-ch:
|
||||
default:
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-atFinish:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("the first reconciliation never reached certification")
|
||||
}
|
||||
if err := fx.layer.BeginBaseInstall(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fx.layer.EndBaseInstall(fx.s.CheckpointLSN()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total := fx.layer.Stats().ReconcileTotal
|
||||
if total == 0 {
|
||||
t.Fatal("the replacement reconciliation has nothing to compare; the schedule needs local chunks")
|
||||
}
|
||||
close(releaseFinish) // the old worker resumes into certification
|
||||
refusedOver(t, 300*time.Millisecond, "after the old worker resumed", func() error {
|
||||
st := fx.layer.Stats()
|
||||
if !st.Reconciling || st.ReconcileTotal != total || st.ReconcileDone != 0 {
|
||||
return fmt.Errorf("replacement certified or modified by the old worker: reconciling=%v done=%d/%d (total was %d)", st.Reconciling, st.ReconcileDone, st.ReconcileTotal, total)
|
||||
}
|
||||
if _, err := fx.layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkReconciling) {
|
||||
return fmt.Errorf("Cut admitted while the replacement reconciles: %v", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
close(replHold)
|
||||
waitReconciledForTest(t, fx.layer)
|
||||
if _, err := fx.layer.Cut(ctTimeout(t)); err != nil {
|
||||
t.Fatalf("Cut after the replacement reconciled: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// An old worker paused between comparing a chunk and recording it must not
|
||||
// record into (or delete from) the replacement reconciliation's set.
|
||||
func TestChunkReconcile_OldWorkerCannotModifyReplacementSet(t *testing.T) {
|
||||
var oldGen atomic.Uint64
|
||||
atCompared, releaseOld, replHold := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
hook := func(stage string, gen uint64) {
|
||||
switch {
|
||||
case stage == "compared" && oldGen.CompareAndSwap(0, gen):
|
||||
close(atCompared)
|
||||
<-releaseOld
|
||||
case stage == "batch" && oldGen.Load() != 0 && gen != oldGen.Load():
|
||||
<-replHold
|
||||
}
|
||||
}
|
||||
fx := newReconcileFixtureOpts(t, false, func(bm *fakeBitmapStore) { bm.lostNext = true },
|
||||
func(cfg *chunkLayerConfig) { cfg.testReconcileHook = hook })
|
||||
// Registered after the fixture: cleanups run last-in first-out, so the
|
||||
// workers are released before the layer closes and waits for them.
|
||||
t.Cleanup(func() {
|
||||
for _, ch := range []chan struct{}{releaseOld, replHold} {
|
||||
select {
|
||||
case <-ch:
|
||||
default:
|
||||
close(ch)
|
||||
}
|
||||
}
|
||||
})
|
||||
select {
|
||||
case <-atCompared:
|
||||
case <-time.After(ctLocalBound):
|
||||
t.Fatal("the first reconciliation never compared a chunk")
|
||||
}
|
||||
if err := fx.layer.BeginBaseInstall(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fx.layer.EndBaseInstall(fx.s.CheckpointLSN()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total := fx.layer.Stats().ReconcileTotal
|
||||
close(releaseOld)
|
||||
refusedOver(t, 300*time.Millisecond, "after the paused old worker resumed", func() error {
|
||||
if st := fx.layer.Stats(); st.ReconcileTotal != total || st.ReconcileDone != 0 {
|
||||
return fmt.Errorf("old worker modified the replacement set: done=%d/%d (total was %d)", st.ReconcileDone, st.ReconcileTotal, total)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
close(replHold)
|
||||
waitReconciledForTest(t, fx.layer)
|
||||
}
|
||||
@@ -5,21 +5,6 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The causes a control plane reports as typed codes (B9 W2 §2.2) stay
|
||||
// reachable with errors.Is through the layer's errors.
|
||||
|
||||
func TestChunkCut_BaseInstallRefusalIsTyped(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
layer := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1))
|
||||
newWriteLog().write(t, s, 2, 0x22)
|
||||
if err := layer.BeginBaseInstall(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := layer.Cut(ctTimeout(t)); !errors.Is(err, errChunkCaptureRefused) || !errors.Is(err, errChunkBaseInstalling) {
|
||||
t.Fatalf("cut during a BASE install: %v; want refused with errChunkBaseInstalling", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChunkCut_UploadFailureIsRemoteUnavailable(t *testing.T) {
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
f := newFakeChunkRemote()
|
||||
|
||||
@@ -1,41 +1,11 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestClaimChunkHeadClearsProductionDetachProof(t *testing.T) {
|
||||
s, _ := newChunkTestStore(t)
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remote := NewMemChunkRemote()
|
||||
layer, err := AttachChunkLayer(s, remote, ChunkLayerConfig{ChunkBlocks: 4, Epoch: 1, Holder: "old"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = s.Write(0, bytes.Repeat([]byte{0xD7}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detached, err := layer.Detach(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if detached.Head.State != chunkHeadDetached || detached.Head.DetachedBy == nil {
|
||||
t.Fatal("producer did not detach", detached.Head)
|
||||
}
|
||||
claimed, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 2, Holder: "new"})
|
||||
if err != nil {
|
||||
t.Fatal("takeover of production detached HEAD", err)
|
||||
}
|
||||
if claimed.State != chunkHeadActive || claimed.DetachedBy != nil || claimed.RemoteLSN != detached.H {
|
||||
t.Fatalf("takeover retained detached proof or changed frontier: %+v", claimed)
|
||||
}
|
||||
}
|
||||
|
||||
type claimFaultRemote struct {
|
||||
ChunkRemote
|
||||
applied, failRead, called bool
|
||||
@@ -136,21 +106,6 @@ func TestClaimChunkHeadFencesNoopCut(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreshRestoreBitmapStartsAtClaimedHEAD(t *testing.T) {
|
||||
s, _ := newLegacyChunkTestStore(t)
|
||||
r := NewMemChunkRemote()
|
||||
if _, err := r.CASHead(ctTimeout(t), ChunkHeadVersion{}, ChunkHead{Epoch: 2, Holder: "host-a", RemoteLSN: 42}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := ctConfig(2)
|
||||
cfg.FreshFromHead = true
|
||||
mustAttach(t, s, r, cfg)
|
||||
hdr, dirty, ok, err := cfg.Bitmap.Load()
|
||||
if err != nil || !ok || hdr.BaseLSN != 42 || hdr.HeadGen != 1 || hdr.Epoch != 2 || hdr.Base != chunkBaseNone || len(dirty) != 0 {
|
||||
t.Fatalf("fresh bitmap not at HEAD: hdr=%+v dirty=%v ok=%v err=%v", hdr, dirty, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A no-op cut still consults remote authority. An outage there is retryable
|
||||
// remote unavailability, not an untyped failure or an ownership fence.
|
||||
func TestClaimChunkHeadNoopCutClassifiesRemoteReadFailure(t *testing.T) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
@@ -163,13 +162,11 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
if err := store.stickyIOFault(); err != nil {
|
||||
return err // no checkpoint advance after a failed fsync
|
||||
}
|
||||
// Do not acquire lifecycleMu here: Close holds it while joining Stop.
|
||||
// The pressure leader is released before snapshot/materialization/checkpoint.
|
||||
if store.v3 != nil {
|
||||
if err := store.syncWALPressureV3(); err != nil {
|
||||
return fmt.Errorf("flusher: pressure WAL sync: %w", err)
|
||||
}
|
||||
|
||||
if err := store.syncWALPressureV3(); err != nil {
|
||||
return fmt.Errorf("flusher: pressure WAL sync: %w", err)
|
||||
}
|
||||
|
||||
store.mu.RLock()
|
||||
if store.closed && !allowClosed {
|
||||
store.mu.RUnlock()
|
||||
@@ -182,16 +179,15 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
// Bind materialization to the same Recover lifetime as this snapshot.
|
||||
// Recover holds store.mu at both generation boundaries.
|
||||
var recoveryGen uint64
|
||||
if store.v3 != nil {
|
||||
recoveryGen = store.v3.recoverGen.Load()
|
||||
}
|
||||
|
||||
recoveryGen = store.v3.recoverGen.Load()
|
||||
|
||||
entries := store.dm.snapshot()
|
||||
store.mu.RUnlock()
|
||||
if len(entries) == 0 {
|
||||
if store.v3 != nil {
|
||||
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
|
||||
}
|
||||
return nil
|
||||
|
||||
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
|
||||
|
||||
}
|
||||
if f.afterSnapshotForTest != nil {
|
||||
f.afterSnapshotForTest()
|
||||
@@ -205,8 +201,6 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
// checkpoint progress. Partial extent writes are safe because checkpoint
|
||||
// publication happens only after the whole snapshot and fsync succeed.
|
||||
var maxLSN uint64
|
||||
var maxLSNPhys uint64
|
||||
var maxLSNEntrySize uint64
|
||||
writtenEntries := make([]snapshotEntry, 0, len(entries))
|
||||
defer func() {
|
||||
f.instr.recordWrittenOpportunity(writtenEntries, store.sb.BlockSize)
|
||||
@@ -214,25 +208,17 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
|
||||
// Adjacent blocks of a native batch share one immutable, validated record.
|
||||
// Keep only one record (at most WALSize bytes), scoped to this Recover lifetime.
|
||||
var recordCache *flushRecordCacheV3
|
||||
if store.v3 != nil {
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
if entries[i].WALOffset == entries[j].WALOffset {
|
||||
return entries[i].DataOffset < entries[j].DataOffset
|
||||
}
|
||||
return entries[i].WALOffset < entries[j].WALOffset
|
||||
})
|
||||
recordCache = &flushRecordCacheV3{recoveryGen: recoveryGen}
|
||||
}
|
||||
for _, e := range entries {
|
||||
var data []byte
|
||||
var entrySize uint64
|
||||
var err error
|
||||
if recordCache != nil {
|
||||
data, entrySize, err = f.readDirtyRecordV3Cached(e, recordCache)
|
||||
} else {
|
||||
data, entrySize, err = f.readDirtyRecord(e)
|
||||
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
if entries[i].WALOffset == entries[j].WALOffset {
|
||||
return entries[i].DataOffset < entries[j].DataOffset
|
||||
}
|
||||
return entries[i].WALOffset < entries[j].WALOffset
|
||||
})
|
||||
recordCache := &flushRecordCacheV3{recoveryGen: recoveryGen}
|
||||
|
||||
for _, e := range entries {
|
||||
data, _, err := f.readDirtyRecordV3Cached(e, recordCache)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -252,8 +238,6 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
}
|
||||
if e.LSN > maxLSN {
|
||||
maxLSN = e.LSN
|
||||
maxLSNPhys = e.WALOffset
|
||||
maxLSNEntrySize = entrySize
|
||||
}
|
||||
}
|
||||
// Step 2: one fsync covers all extent writes in this batch
|
||||
@@ -279,22 +263,14 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
// writer may reuse those bytes.
|
||||
var publishErr error
|
||||
cpBefore := store.CheckpointLSN()
|
||||
if store.v3 != nil {
|
||||
publishErr = store.persistCheckpointV3(maxLSN, recoveryGen)
|
||||
} else {
|
||||
publishErr = store.persistCheckpointAndRelease(maxLSN, maxLSNPhys, maxLSNEntrySize)
|
||||
}
|
||||
|
||||
publishErr = store.persistCheckpointV3(maxLSN, recoveryGen)
|
||||
|
||||
f.instr.recordCheckpoint(publishErr, cpBefore, store.CheckpointLSN(), time.Now())
|
||||
if err := publishErr; err != nil {
|
||||
return fmt.Errorf("flusher: persist checkpoint %d: %w", maxLSN, err)
|
||||
}
|
||||
if store.v3 == nil && store.CheckpointLSN() >= maxLSN {
|
||||
store.mu.Lock()
|
||||
if maxLSN+1 > store.walTail {
|
||||
store.walTail = maxLSN + 1
|
||||
}
|
||||
store.mu.Unlock()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if f.afterCheckpointForTest != nil {
|
||||
@@ -308,210 +284,36 @@ func (f *flusher) flushOnceInternal(allowClosed bool) (err error) {
|
||||
// Keep the uncovered entries as retry work even though their extent
|
||||
// bytes were fsynced: a later Sync plus cycle must advance checkpoint
|
||||
// AND coverage, rather than merely refreshing W on an empty dirty map.
|
||||
checkpoint := maxLSN // legacy behavior: remove the whole flushed snapshot
|
||||
if store.v3 != nil {
|
||||
// Serialize validation and LSN-only retirement with Recover. A new
|
||||
// lifetime can reuse the same LBA, physical offset and LSN.
|
||||
store.mu.Lock()
|
||||
if !store.v3.flushLifetimeValidV3(recoveryGen) {
|
||||
store.mu.Unlock()
|
||||
return mapCoverageRefusal("recovery_lifetime_changed")
|
||||
}
|
||||
checkpoint = store.checkpointLSN
|
||||
if checkpoint >= maxLSN && maxLSN+1 > store.walTail {
|
||||
store.walTail = maxLSN + 1
|
||||
}
|
||||
|
||||
// Serialize validation and LSN-only retirement with Recover. A new
|
||||
// lifetime can reuse the same LBA, physical offset and LSN.
|
||||
store.mu.Lock()
|
||||
if !store.v3.flushLifetimeValidV3(recoveryGen) {
|
||||
store.mu.Unlock()
|
||||
return mapCoverageRefusal("recovery_lifetime_changed")
|
||||
}
|
||||
checkpoint := store.checkpointLSN
|
||||
if checkpoint >= maxLSN && maxLSN+1 > store.walTail {
|
||||
store.walTail = maxLSN + 1
|
||||
}
|
||||
|
||||
for _, e := range entries {
|
||||
if e.LSN > checkpoint {
|
||||
continue
|
||||
}
|
||||
store.dm.compareAndDelete(e.LBA, e.LSN)
|
||||
}
|
||||
if store.v3 != nil {
|
||||
store.mu.Unlock()
|
||||
}
|
||||
|
||||
store.mu.Unlock()
|
||||
|
||||
f.flushes.Add(1)
|
||||
if store.v3 != nil {
|
||||
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
|
||||
}
|
||||
return nil
|
||||
|
||||
return store.refreshW() // the mode-C idle refresh (DESIGN 6.2)
|
||||
|
||||
}
|
||||
|
||||
func (f *flusher) readDirtyRecord(e snapshotEntry) (data []byte, entrySize uint64, err error) {
|
||||
if f.store.v3 != nil {
|
||||
return f.readDirtyRecordV3(e)
|
||||
}
|
||||
store := f.store
|
||||
readFailed := false
|
||||
defer func() {
|
||||
switch {
|
||||
case err == nil:
|
||||
f.instr.recordValidatedRecord()
|
||||
case !readFailed:
|
||||
f.instr.recordValidationFailure()
|
||||
}
|
||||
}()
|
||||
|
||||
absOff := int64(store.sb.WALOffset + e.WALOffset)
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
headerStart := time.Now()
|
||||
n, readErr := store.fd.ReadAt(header, absOff)
|
||||
f.instr.recordWALHeaderRead(n, time.Since(headerStart), readErr)
|
||||
if readErr != nil {
|
||||
readFailed = true
|
||||
return nil, 0, fmt.Errorf("flusher: read WAL header at %d: %w", e.WALOffset, readErr)
|
||||
}
|
||||
return f.readDirtyRecordV3(e)
|
||||
|
||||
entryLSN := binary.LittleEndian.Uint64(header[0:8])
|
||||
entryType := header[16]
|
||||
if entryType != walEntryWriteBatch && entryLSN != e.LSN {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entryLSN)
|
||||
}
|
||||
if entryType != walEntryWrite && entryType != walEntryWriteBatch && entryType != walEntryTrim {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d type %d",
|
||||
e.LBA, e.WALOffset, entryType)
|
||||
}
|
||||
|
||||
payloadLen := uint64(0)
|
||||
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
|
||||
payloadLen = uint64(parseLengthFromHeader(header))
|
||||
if payloadLen == 0 {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d with zero payload",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
}
|
||||
entrySize = uint64(walEntryHeaderSize) + payloadLen
|
||||
if entrySize > store.sb.WALSize || e.WALOffset+entrySize > store.sb.WALSize {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d size %d WAL size %d",
|
||||
e.LBA, e.WALOffset, entrySize, store.sb.WALSize)
|
||||
}
|
||||
|
||||
full := make([]byte, entrySize)
|
||||
recordStart := time.Now()
|
||||
n, readErr = store.fd.ReadAt(full, absOff)
|
||||
f.instr.recordWALRecordRead(n, time.Since(recordStart), readErr)
|
||||
if readErr != nil {
|
||||
readFailed = true
|
||||
return nil, 0, fmt.Errorf("flusher: read WAL record at %d: %w", e.WALOffset, readErr)
|
||||
}
|
||||
|
||||
entryLSN = binary.LittleEndian.Uint64(full[0:8])
|
||||
entryType = full[16]
|
||||
if entryType != walEntryWriteBatch && entryLSN != e.LSN {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entryLSN)
|
||||
}
|
||||
if entryType != walEntryWrite && entryType != walEntryWriteBatch && entryType != walEntryTrim {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d type %d",
|
||||
e.LBA, e.WALOffset, entryType)
|
||||
}
|
||||
expectedRecordSize := uint64(walEntryHeaderSize)
|
||||
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
|
||||
payloadLen := uint64(parseLengthFromHeader(full))
|
||||
if payloadLen == 0 {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d with zero payload",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
expectedRecordSize += payloadLen
|
||||
}
|
||||
if expectedRecordSize != entrySize || uint64(len(full)) != entrySize {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d record size %d expected %d",
|
||||
e.LBA, e.WALOffset, entrySize, expectedRecordSize)
|
||||
}
|
||||
decodeStart := time.Now()
|
||||
entry, err := decodeWALEntry(full)
|
||||
f.instr.recordWALRecordDecode(len(full), time.Since(decodeStart), err)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d: %w",
|
||||
e.LBA, e.WALOffset, err)
|
||||
}
|
||||
if entry.Flags != 0 {
|
||||
return nil, 0, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL record LBA %d offset %d flags %d",
|
||||
e.LBA, e.WALOffset, entry.Flags)
|
||||
}
|
||||
data, err = f.validateMaterializedDirtyEntry(e, &entry)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return data, entrySize, nil
|
||||
}
|
||||
|
||||
func (f *flusher) validateMaterializedDirtyEntry(e snapshotEntry, entry *walEntry) ([]byte, error) {
|
||||
blockSize := f.store.sb.BlockSize
|
||||
switch entry.Type {
|
||||
case walEntryWrite:
|
||||
if entry.LSN != e.LSN || entry.LBA != e.LBA || e.DataOffset != 0 ||
|
||||
entry.Length != blockSize || e.Length != blockSize {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN)
|
||||
}
|
||||
return entry.Data, nil
|
||||
case walEntryWriteBatch:
|
||||
maxBlocks := uint64(^uint32(0)) / uint64(blockSize)
|
||||
if entry.Reserved == 0 || entry.Reserved > maxBlocks {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL batch LBA %d offset %d",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
expectedLength := entry.Reserved * uint64(blockSize)
|
||||
if uint64(entry.Length) != expectedLength ||
|
||||
e.DataOffset%blockSize != 0 || e.Length != blockSize {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL batch LBA %d offset %d",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
blockIndex := uint64(e.DataOffset / blockSize)
|
||||
if blockIndex >= entry.Reserved || entry.LSN+blockIndex != e.LSN ||
|
||||
entry.LBA+blockIndex != e.LBA {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch LBA %d offset %d dirty LSN %d batch base %d block %d count %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN, blockIndex, entry.Reserved)
|
||||
}
|
||||
start := uint64(e.DataOffset)
|
||||
end := start + uint64(blockSize)
|
||||
if end > uint64(len(entry.Data)) {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL batch LBA %d offset %d data range [%d,%d)",
|
||||
e.LBA, e.WALOffset, start, end)
|
||||
}
|
||||
return entry.Data[start:end], nil
|
||||
case walEntryTrim:
|
||||
trimBlocks := uint64(1)
|
||||
if entry.Length > 0 {
|
||||
if entry.Length%blockSize != 0 {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL trim LBA %d offset %d length %d",
|
||||
e.LBA, e.WALOffset, entry.Length)
|
||||
}
|
||||
trimBlocks = uint64(entry.Length / blockSize)
|
||||
}
|
||||
if e.DataOffset%blockSize != 0 || e.Length != blockSize {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: invalid dirty WAL trim LBA %d offset %d",
|
||||
e.LBA, e.WALOffset)
|
||||
}
|
||||
blockIndex := uint64(e.DataOffset / blockSize)
|
||||
if entry.LSN != e.LSN || blockIndex >= trimBlocks ||
|
||||
entry.LBA+blockIndex != e.LBA {
|
||||
return nil, fmt.Errorf(
|
||||
"flusher: WAL slot mismatch trim LBA %d offset %d dirty LSN %d record LSN %d",
|
||||
e.LBA, e.WALOffset, e.LSN, entry.LSN)
|
||||
}
|
||||
return make([]byte, blockSize), nil
|
||||
default:
|
||||
panic("validated dirty WAL type became unsupported")
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -33,97 +33,6 @@ func TestBoundedExtentWriteOpportunity(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherInstrumentationCountsCompleteCycle(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
block := makeBlock(4096, 0x41)
|
||||
if _, err := s.WriteBatch(0, [][]byte{block, block, block, block}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := s.FlusherInstrumentation()
|
||||
if got.CyclesStarted != 1 || got.CyclesSucceeded != 1 || got.CyclesFailed != 0 {
|
||||
t.Fatalf("cycles started/succeeded/failed=%d/%d/%d want 1/1/0",
|
||||
got.CyclesStarted, got.CyclesSucceeded, got.CyclesFailed)
|
||||
}
|
||||
if got.SnapshotEntries != 4 || got.ValidatedRecords != 4 || got.SupersededEntries != 0 {
|
||||
t.Fatalf("snapshot/validated/superseded=%d/%d/%d want 4/4/0",
|
||||
got.SnapshotEntries, got.ValidatedRecords, got.SupersededEntries)
|
||||
}
|
||||
wantRecords := uint64(4)
|
||||
if s.FormatV3() {
|
||||
wantRecords = 1
|
||||
} // one full native batch decode, four validated blocks
|
||||
if got.WALHeaderReadOps != wantRecords || got.WALRecordReadOps != wantRecords ||
|
||||
got.WALRecordDecodeOps != wantRecords || got.WALRecordDecodeBytes == 0 ||
|
||||
got.WALRecordDecodeDurationNanos == 0 {
|
||||
t.Fatalf("header/record reads and decode ops/bytes/ns=%d/%d %d/%d/%d want actual unique-record counts/nonzero bytes and duration",
|
||||
got.WALHeaderReadOps, got.WALRecordReadOps,
|
||||
got.WALRecordDecodeOps, got.WALRecordDecodeBytes,
|
||||
got.WALRecordDecodeDurationNanos)
|
||||
}
|
||||
if got.ExtentWriteOps != 4 || got.ExtentWriteBytes != 4*4096 ||
|
||||
got.ExtentWriteMaxBytes != 4096 || got.ExtentWriteFailures != 0 {
|
||||
t.Fatalf("extent ops/bytes/max/failures=%d/%d/%d/%d want 4/%d/4096/0",
|
||||
got.ExtentWriteOps, got.ExtentWriteBytes, got.ExtentWriteMaxBytes,
|
||||
got.ExtentWriteFailures, 4*4096)
|
||||
}
|
||||
if got.SnapshotBoundedWriteMinimum != 1 || got.SnapshotRunCount != 1 ||
|
||||
got.SnapshotSingletonRuns != 0 || got.SnapshotCoalescibleEntries != 4 ||
|
||||
got.SnapshotMaxContiguousRunBlocks != 4 {
|
||||
t.Fatalf("opportunity minimum/runs/singletons/coalescible/max=%d/%d/%d/%d/%d want 1/1/0/4/4",
|
||||
got.SnapshotBoundedWriteMinimum, got.SnapshotRunCount,
|
||||
got.SnapshotSingletonRuns, got.SnapshotCoalescibleEntries,
|
||||
got.SnapshotMaxContiguousRunBlocks)
|
||||
}
|
||||
if got.WrittenBoundedWriteMinimum != 1 || got.WrittenRunCount != 1 ||
|
||||
got.WrittenSingletonRuns != 0 || got.WrittenCoalescibleEntries != 4 ||
|
||||
got.WrittenMaxContiguousRunBlocks != 4 {
|
||||
t.Fatalf("written opportunity minimum/runs/singletons/coalescible/max=%d/%d/%d/%d/%d want 1/1/0/4/4",
|
||||
got.WrittenBoundedWriteMinimum, got.WrittenRunCount,
|
||||
got.WrittenSingletonRuns, got.WrittenCoalescibleEntries,
|
||||
got.WrittenMaxContiguousRunBlocks)
|
||||
}
|
||||
if got.ValidationFailures != 0 ||
|
||||
got.WALHeaderReadFailures != 0 ||
|
||||
got.WALRecordReadFailures != 0 {
|
||||
t.Fatalf("validation/header-read/record-read failures=%d/%d/%d want 0/0/0",
|
||||
got.ValidationFailures, got.WALHeaderReadFailures,
|
||||
got.WALRecordReadFailures)
|
||||
}
|
||||
if got.ExtentSyncOps != 1 || got.ExtentSyncFailures != 0 ||
|
||||
got.CheckpointMetadataWriteOps != 1 ||
|
||||
got.CheckpointMetadataSyncOps != 1 {
|
||||
t.Fatalf("extent-sync/failures/checkpoint-write/checkpoint-sync=%d/%d/%d/%d want 1/0/1/1",
|
||||
got.ExtentSyncOps, got.ExtentSyncFailures,
|
||||
got.CheckpointMetadataWriteOps, got.CheckpointMetadataSyncOps)
|
||||
}
|
||||
if got.CheckpointMetadataWriteFailures != 0 ||
|
||||
got.CheckpointMetadataSyncFailures != 0 {
|
||||
t.Fatalf("checkpoint write/sync failures=%d/%d want 0/0",
|
||||
got.CheckpointMetadataWriteFailures, got.CheckpointMetadataSyncFailures)
|
||||
}
|
||||
if got.CycleDurationNanos == 0 || got.CycleMaxDurationNanos == 0 {
|
||||
t.Fatal("cycle timing evidence is zero")
|
||||
}
|
||||
if got.CycleDurationNanos < got.SnapshotDurationNanos+got.OpportunityAnalysisNanos {
|
||||
t.Fatalf("cycle duration=%d excludes snapshot+opportunity=%d",
|
||||
got.CycleDurationNanos,
|
||||
got.SnapshotDurationNanos+got.OpportunityAnalysisNanos)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherInstrumentationSeparatesSnapshotAndWrittenOpportunity(t *testing.T) {
|
||||
entries := []snapshotEntry{{LBA: 0}, {LBA: 1}, {LBA: 2}}
|
||||
var instr flusherInstrumentation
|
||||
@@ -147,90 +56,6 @@ func TestFlusherInstrumentationSeparatesSnapshotAndWrittenOpportunity(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherInstrumentationCountsCheckpointFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
wantWriteFailure uint64
|
||||
wantWriteBytes uint64
|
||||
wantSyncOps uint64
|
||||
wantSyncFailure uint64
|
||||
}{
|
||||
{
|
||||
name: "write",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected checkpoint write failure")
|
||||
}
|
||||
},
|
||||
wantWriteFailure: 1,
|
||||
},
|
||||
{
|
||||
name: "sync",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected checkpoint sync failure")
|
||||
}
|
||||
},
|
||||
wantWriteBytes: superblockSize,
|
||||
wantSyncOps: 1,
|
||||
wantSyncFailure: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
if err := s.flusher.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x52)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
savedWrite := s.writeSuperblockMetadata
|
||||
savedSync := s.syncSuperblockMetadata
|
||||
tt.inject(s)
|
||||
err = s.flusher.flushOnce()
|
||||
s.writeSuperblockMetadata = savedWrite
|
||||
s.syncSuperblockMetadata = savedSync
|
||||
if err == nil {
|
||||
t.Fatal("flush succeeded despite checkpoint failure")
|
||||
}
|
||||
|
||||
got := s.FlusherInstrumentation()
|
||||
if got.CyclesStarted != 1 || got.CyclesSucceeded != 0 || got.CyclesFailed != 1 {
|
||||
t.Fatalf("cycles started/succeeded/failed=%d/%d/%d want 1/0/1",
|
||||
got.CyclesStarted, got.CyclesSucceeded, got.CyclesFailed)
|
||||
}
|
||||
if got.ExtentWriteOps != 1 || got.ExtentWriteFailures != 0 ||
|
||||
got.ExtentSyncOps != 1 || got.ExtentSyncFailures != 0 {
|
||||
t.Fatalf("extent writes/failures/syncs/failures=%d/%d/%d/%d want 1/0/1/0",
|
||||
got.ExtentWriteOps, got.ExtentWriteFailures,
|
||||
got.ExtentSyncOps, got.ExtentSyncFailures)
|
||||
}
|
||||
if got.CheckpointMetadataWriteOps != 1 ||
|
||||
got.CheckpointMetadataWriteFailures != tt.wantWriteFailure ||
|
||||
got.CheckpointMetadataWriteBytes != tt.wantWriteBytes ||
|
||||
got.CheckpointMetadataSyncOps != tt.wantSyncOps ||
|
||||
got.CheckpointMetadataSyncFailures != tt.wantSyncFailure {
|
||||
t.Fatalf("checkpoint write ops/failures/bytes/sync ops/failures=%d/%d/%d/%d/%d want 1/%d/%d/%d/%d",
|
||||
got.CheckpointMetadataWriteOps, got.CheckpointMetadataWriteFailures,
|
||||
got.CheckpointMetadataWriteBytes, got.CheckpointMetadataSyncOps,
|
||||
got.CheckpointMetadataSyncFailures, tt.wantWriteFailure,
|
||||
tt.wantWriteBytes, tt.wantSyncOps, tt.wantSyncFailure)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherInstrumentationCountsExtentFailures(t *testing.T) {
|
||||
var instr flusherInstrumentation
|
||||
injected := errors.New("injected extent failure")
|
||||
@@ -263,77 +88,3 @@ func TestFlusherInstrumentationCountsExtentFailures(t *testing.T) {
|
||||
got.WALRecordDecodeOps, got.WALRecordDecodeFailures, got.WALRecordDecodeBytes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherInstrumentationCountsWALReadFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
breakFile func(*testing.T, *WALStore, int64)
|
||||
wantHeaderReadFailures uint64
|
||||
wantRecordReadFailures uint64
|
||||
}{
|
||||
{
|
||||
name: "header",
|
||||
breakFile: func(t *testing.T, s *WALStore, _ int64) {
|
||||
t.Helper()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
wantHeaderReadFailures: 1,
|
||||
},
|
||||
{
|
||||
name: "record",
|
||||
breakFile: func(t *testing.T, s *WALStore, absoluteOffset int64) {
|
||||
t.Helper()
|
||||
if err := s.fd.Truncate(absoluteOffset + walEntryHeaderSize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
wantRecordReadFailures: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.Stop(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x63)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walOffset, _, _, _, ok := s.dm.get(0)
|
||||
if !ok {
|
||||
t.Fatal("dirty entry missing")
|
||||
}
|
||||
s.committer.Stop()
|
||||
absoluteOffset := int64(s.sb.WALOffset + walOffset)
|
||||
tt.breakFile(t, s, absoluteOffset)
|
||||
|
||||
if err := s.flusher.flushOnce(); err == nil {
|
||||
t.Fatal("flush succeeded despite WAL read failure")
|
||||
}
|
||||
got := s.FlusherInstrumentation()
|
||||
if got.WALHeaderReadFailures != tt.wantHeaderReadFailures ||
|
||||
got.WALRecordReadFailures != tt.wantRecordReadFailures ||
|
||||
got.ValidationFailures != 0 ||
|
||||
got.CyclesFailed != 1 {
|
||||
t.Fatalf("header/record/validation/cycle failures=%d/%d/%d/%d want %d/%d/0/1",
|
||||
got.WALHeaderReadFailures, got.WALRecordReadFailures,
|
||||
got.ValidationFailures, got.CyclesFailed,
|
||||
tt.wantHeaderReadFailures, tt.wantRecordReadFailures)
|
||||
}
|
||||
if tt.name == "record" {
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Force a Write+Sync between scans of shard 0 and shard 5. The older
|
||||
// snapshot entry is also superseded, so it cannot cover the omitted write.
|
||||
func TestFlusherSnapshotCutPreservesSyncedWrites(t *testing.T) {
|
||||
for _, replicated := range []bool{false, true} {
|
||||
mode := "write"
|
||||
if replicated {
|
||||
mode = "supplied-lsn"
|
||||
}
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
for _, finishFlush := range []bool{false, true} {
|
||||
name := "crash-after-first-cycle"
|
||||
if finishFlush {
|
||||
name = "next-cycle-makes-progress"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 128, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
if _, err := s.Write(0, bytes.Repeat([]byte{0x11}, 4096)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := bytes.Repeat([]byte{0xAA}, 4096)
|
||||
b := bytes.Repeat([]byte{0xBB}, 4096)
|
||||
fired := false
|
||||
var low, high uint64
|
||||
done := make(chan error, 1)
|
||||
waitWriter := func() {
|
||||
t.Helper()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("writer blocked after snapshot")
|
||||
}
|
||||
}
|
||||
waited := false
|
||||
s.dm.afterSnapshotShard = func(shard int) {
|
||||
if shard != 0 || fired {
|
||||
return
|
||||
}
|
||||
fired = true
|
||||
// No timing race: if publication is excluded by the snapshot,
|
||||
// let the real writer finish after it. Otherwise force completion
|
||||
// before shard 5 is copied (the broken implementation).
|
||||
canPublish := s.mu.TryLock()
|
||||
if canPublish {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
go func() {
|
||||
var err error
|
||||
if replicated {
|
||||
low, high = 20, 30
|
||||
err = s.ApplyEntry(0, a, low)
|
||||
if err == nil {
|
||||
err = s.ApplyEntry(5, b, high)
|
||||
}
|
||||
} else {
|
||||
low, err = s.Write(0, a)
|
||||
if err == nil {
|
||||
high, err = s.Write(5, b)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
var acked uint64
|
||||
acked, err = s.Sync()
|
||||
if err == nil && acked < high {
|
||||
err = fmt.Errorf("Sync=%d below %d", acked, high)
|
||||
}
|
||||
}
|
||||
done <- err
|
||||
}()
|
||||
if canPublish {
|
||||
waitWriter()
|
||||
waited = true
|
||||
}
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.dm.afterSnapshotShard = nil
|
||||
if !waited {
|
||||
waitWriter()
|
||||
}
|
||||
wantLow, wantHigh := uint64(2), uint64(3)
|
||||
if replicated {
|
||||
wantLow, wantHigh = 20, 30
|
||||
}
|
||||
if !fired || low != wantLow || high != wantHigh {
|
||||
t.Fatalf("interleaving not reached: fired=%v LSNs=%d/%d", fired, low, high)
|
||||
}
|
||||
t.Logf("first-cycle checkpoint=%d omitted-synced-LSN=%d tail=%d", s.CheckpointLSN(), low, s.wal.logicalTailValue())
|
||||
if finishFlush {
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.CheckpointLSN() < high || s.dm.len() != 0 {
|
||||
t.Fatalf("next flush did not drain: checkpoint=%d dirty=%d", s.CheckpointLSN(), s.dm.len())
|
||||
}
|
||||
}
|
||||
// Close only the committer and descriptor: normal Close would flush.
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashed = true
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba, want := range map[uint32][]byte{0: a, 5: b} {
|
||||
got, err := reopened.Read(lba)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Errorf("Sync-acked LBA %d lost after crash: got first byte %#x, want %#x", lba, got[0], want[0])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,599 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestFlusher_AdvancesCheckpointBeforeReadFromExtent proves the
|
||||
// flusher actually drains dirty entries to extent and advances the
|
||||
// on-disk checkpoint LSN. After a few flush cycles, reads of those
|
||||
// LBAs come from the extent (not the WAL via dirty map).
|
||||
func TestFlusher_AdvancesCheckpointBeforeReadFromExtent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
|
||||
// Write some blocks and Sync to make them durable in the WAL.
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
if _, err := s.Write(i, makeBlock(4096, byte(0xA0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for the flusher to drain — default interval 50ms; allow
|
||||
// generous slack for slow CI.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= 4 {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if s.CheckpointLSN() < 4 {
|
||||
t.Fatalf("flusher never advanced checkpoint: got %d, want >= 4", s.CheckpointLSN())
|
||||
}
|
||||
|
||||
// Reads should still return correct bytes (whether from WAL or
|
||||
// extent — caller doesn't care).
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
got, err := s.Read(i)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := makeBlock(4096, byte(0xA0+i))
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("LBA %d: bytes wrong after flush: got[0]=%02x want[0]=%02x",
|
||||
i, got[0], want[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlusher_ReleasesWALPressureAfterCheckpoint pins the pressure
|
||||
// feedback loop: after dirty entries are flushed and checkpointed, the
|
||||
// circular WAL tail must advance so admission sees free space again.
|
||||
// Without this, long-running writers eventually hit "WAL region full"
|
||||
// even though the flusher is successfully writing data to the extent.
|
||||
func TestFlusher_ReleasesWALPressureAfterCheckpoint(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 128, 4096, 256*1024)
|
||||
defer s.Close()
|
||||
|
||||
for i := uint32(0); i < 32; i++ {
|
||||
if _, err := s.Write(i, makeBlock(4096, byte(0x80+i))); err != nil {
|
||||
t.Fatalf("Write(%d): %v", i, err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatalf("Sync: %v", err)
|
||||
}
|
||||
if got := s.wal.usedFraction(); got == 0 {
|
||||
t.Fatal("test setup did not create WAL pressure")
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= 32 && s.wal.usedFraction() == 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got < 32 {
|
||||
t.Fatalf("flusher never checkpointed writes: got %d, want >= 32", got)
|
||||
}
|
||||
if used := s.wal.usedFraction(); used != 0 {
|
||||
t.Fatalf("WAL pressure after checkpoint = %.3f, want 0", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALWriter_AdvanceTailPastEntryIsIdempotent(t *testing.T) {
|
||||
w := &walWriter{
|
||||
walSize: 64,
|
||||
logicalHead: 40,
|
||||
logicalTail: 0,
|
||||
}
|
||||
|
||||
w.advanceTailPastEntry(0, 10)
|
||||
if got := w.logicalTailValue(); got != 10 {
|
||||
t.Fatalf("first advance tail=%d, want 10", got)
|
||||
}
|
||||
|
||||
w.advanceTailPastEntry(0, 10)
|
||||
if got := w.logicalTailValue(); got != 10 {
|
||||
t.Fatalf("repeated advance tail=%d, want still 10", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALWriter_AdvanceTailPastWrappedEntry(t *testing.T) {
|
||||
w := &walWriter{
|
||||
walSize: 64,
|
||||
logicalHead: 80,
|
||||
logicalTail: 60,
|
||||
}
|
||||
|
||||
w.advanceTailPastEntry(0, 10)
|
||||
if got := w.logicalTailValue(); got != 74 {
|
||||
t.Fatalf("wrapped advance tail=%d, want 74", got)
|
||||
}
|
||||
}
|
||||
|
||||
func createLegacyWALStoreWithWALSizeForTest(t *testing.T, path string, numBlocks uint32, blockSize int, walSize uint64) *WALStore {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
sb, err := newSuperblock(uint64(numBlocks)*uint64(blockSize), createOptions{
|
||||
BlockSize: uint32(blockSize),
|
||||
ExtentSize: uint32(blockSize),
|
||||
WALSize: walSize,
|
||||
ImplKind: ImplKindWALStore,
|
||||
ImplVersion: 1, // frozen v2 engine fixture, not the production selector
|
||||
})
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
t.Fatalf("newSuperblock: %v", err)
|
||||
}
|
||||
totalSize := int64(superblockSize) + int64(sb.WALSize) + int64(sb.VolumeSize)
|
||||
if err := f.Truncate(totalSize); err != nil {
|
||||
_ = f.Close()
|
||||
t.Fatalf("truncate: %v", err)
|
||||
}
|
||||
if _, err := sb.writeTo(f); err != nil {
|
||||
_ = f.Close()
|
||||
t.Fatalf("write superblock: %v", err)
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
_ = f.Close()
|
||||
t.Fatalf("sync superblock: %v", err)
|
||||
}
|
||||
s, err := openInitialized(path, f, &sb)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
t.Fatalf("openInitialized: %v", err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// TestFlusher_RecoveryHonorsCheckpoint: after the flusher has
|
||||
// advanced the checkpoint and written through the superblock, a
|
||||
// subsequent reopen+Recover skips the checkpointed records (they're
|
||||
// already in extent) and the data is still readable.
|
||||
func TestFlusher_RecoveryHonorsCheckpoint(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
{
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
_, _ = s.Write(i, makeBlock(4096, byte(0xA0+i)))
|
||||
}
|
||||
_, _ = s.Sync()
|
||||
// Wait for flush to advance checkpoint.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= 4 {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if s.CheckpointLSN() < 4 {
|
||||
t.Fatal("flusher never advanced checkpoint pre-close")
|
||||
}
|
||||
_ = s.Close() // clean close — superblock fully persisted
|
||||
}
|
||||
|
||||
// Reopen + Recover. The checkpointed records should be skipped;
|
||||
// extent should serve all reads.
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := uint32(0); i < 4; i++ {
|
||||
got, _ := s.Read(i)
|
||||
want := makeBlock(4096, byte(0xA0+i))
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("LBA %d: bytes did not survive checkpointed restart", i)
|
||||
}
|
||||
}
|
||||
if s.CheckpointLSN() < 4 {
|
||||
t.Fatalf("Recover did not load checkpoint from superblock: got %d", s.CheckpointLSN())
|
||||
}
|
||||
}
|
||||
|
||||
// TestCrashFamily_AbruptKillAtMultipleWindows is the Phase 08 crash
|
||||
// proof family. Each subtest simulates an abrupt kill at a different
|
||||
// point in the local data process and verifies:
|
||||
//
|
||||
// - acked writes (covered by a successful Sync) survive the kill
|
||||
// - unacked writes may be lost but never corrupt acked data
|
||||
// - recovery is deterministic
|
||||
//
|
||||
// The "abrupt kill" is simulated by stopping background goroutines
|
||||
// then dropping the file handle without going through Close —
|
||||
// no implicit fsync, no superblock update.
|
||||
func TestCrashFamily_AbruptKillAtMultipleWindows(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
nBefore int // writes (each followed by Sync) before the danger zone
|
||||
nDuring int // writes during the danger zone (no Sync)
|
||||
waitFlush bool // give the flusher a chance to advance checkpoint before the kill
|
||||
}{
|
||||
{
|
||||
name: "kill_pre_sync",
|
||||
nBefore: 0,
|
||||
nDuring: 3, // 3 writes, no Sync, then kill
|
||||
},
|
||||
{
|
||||
name: "kill_post_sync_pre_flush",
|
||||
nBefore: 3, // 3 writes + Sync, then immediate kill
|
||||
nDuring: 0,
|
||||
},
|
||||
{
|
||||
name: "kill_post_flush",
|
||||
nBefore: 3, // 3 writes + Sync, wait for flush, then kill
|
||||
nDuring: 0,
|
||||
waitFlush: true,
|
||||
},
|
||||
{
|
||||
name: "kill_post_flush_then_more_unacked_writes",
|
||||
nBefore: 3, // first batch acked + flushed
|
||||
nDuring: 2, // second batch unacked
|
||||
waitFlush: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
c := c
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
func() {
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Acked writes: those covered by Sync.
|
||||
for i := 0; i < c.nBefore; i++ {
|
||||
if _, err := s.Write(uint32(i), makeBlock(4096, byte(0xA0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if c.nBefore > 0 {
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if c.waitFlush {
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= uint64(c.nBefore) {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
// Unacked writes: NOT followed by Sync.
|
||||
for i := 0; i < c.nDuring; i++ {
|
||||
if _, err := s.Write(uint32(c.nBefore+i), makeBlock(4096, byte(0xB0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// Abrupt kill: stop background goroutines so they
|
||||
// don't race the file close, then drop fd directly
|
||||
// without going through Close().
|
||||
s.flusher.Stop()
|
||||
s.committer.Stop()
|
||||
_ = s.fd.Close()
|
||||
}()
|
||||
|
||||
// Reopen + Recover. Verify acked survives, unacked
|
||||
// is either present-as-written or absent, never corrupt.
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen after %s: %v", c.name, err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatalf("recover after %s: %v", c.name, err)
|
||||
}
|
||||
|
||||
for i := 0; i < c.nBefore; i++ {
|
||||
got, err := s.Read(uint32(i))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := makeBlock(4096, byte(0xA0+i))
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("ACKED LBA %d did not survive %s: got[0]=%02x want[0]=%02x",
|
||||
i, c.name, got[0], want[0])
|
||||
}
|
||||
}
|
||||
zero := make([]byte, 4096)
|
||||
for i := 0; i < c.nDuring; i++ {
|
||||
got, err := s.Read(uint32(c.nBefore + i))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := makeBlock(4096, byte(0xB0+i))
|
||||
if !bytes.Equal(got, want) && !bytes.Equal(got, zero) {
|
||||
t.Fatalf("UNACKED LBA %d under %s: got neither write nor zero — corruption: got[0]=%02x",
|
||||
c.nBefore+i, c.name, got[0])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect is the
|
||||
// regression test for the architect-flagged "checkpoint can advance
|
||||
// past unflushed records" bug.
|
||||
//
|
||||
// The earlier flusher truncated the dirty snapshot to maxBatch
|
||||
// entries (in arbitrary map order), then advanced the checkpoint to
|
||||
// the highest LSN in that PARTIAL batch. If the truncated portion
|
||||
// contained entries with smaller LSNs, the checkpoint would jump
|
||||
// past them and recovery would later skip records that hadn't been
|
||||
// flushed → data loss.
|
||||
//
|
||||
// The fix removed the maxBatch cutoff (V2 has no such cutoff). This
|
||||
// test writes many entries, forces flush, then crashes-without-Close
|
||||
// and verifies all blocks are recoverable via the extent. If a
|
||||
// checkpoint ever jumps past an unflushed entry again, this test
|
||||
// will catch it because that LBA's read will return zeros instead
|
||||
// of the written bytes.
|
||||
func TestFlusher_ManyDirtyEntriesCheckpointStaysCorrect(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
const n = 300 // > any plausible old maxBatch (which was 256)
|
||||
|
||||
{
|
||||
s, err := createLegacyWALStoreForTest(path, n+10, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := uint32(0); i < n; i++ {
|
||||
if _, err := s.Write(i, makeBlock(4096, byte(i%256))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Wait for the flusher to drain enough that the checkpoint
|
||||
// has advanced. With 300 entries and the V2-faithful
|
||||
// "process whole snapshot in one cycle" rule, one flush
|
||||
// cycle should drain all of them.
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= uint64(n) {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if s.CheckpointLSN() < uint64(n) {
|
||||
t.Fatalf("flusher did not drain all %d entries: checkpoint=%d", n, s.CheckpointLSN())
|
||||
}
|
||||
// Abrupt kill: bypass Close so we exercise recovery from the
|
||||
// post-flush state, not a clean-shutdown path.
|
||||
s.flusher.Stop()
|
||||
s.committer.Stop()
|
||||
_ = s.fd.Close()
|
||||
}
|
||||
|
||||
// Reopen + Recover. Every LBA must be readable with the bytes
|
||||
// we wrote — the checkpoint advance must have only covered
|
||||
// LBAs whose data is actually in the extent.
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if _, err := s.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := uint32(0); i < n; i++ {
|
||||
got, _ := s.Read(i)
|
||||
want := makeBlock(4096, byte(i%256))
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("LBA %d: bytes lost — checkpoint advanced past unflushed record",
|
||||
i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFlusher_ConcurrentWriteRaceLBAStaysFresh is the regression
|
||||
// test for the architect-flagged "flusher deletes newer concurrent
|
||||
// write" bug.
|
||||
//
|
||||
// The earlier flusher snapshotted {LBA, oldLSN}, wrote oldLSN's
|
||||
// data to extent, and unconditionally deleted the dirty map entry
|
||||
// by LBA. If a concurrent Write() updated that LBA to {LBA, newLSN}
|
||||
// after the snapshot, the unconditional delete would also drop the
|
||||
// newer entry, and reads would fall back to the stale extent bytes.
|
||||
//
|
||||
// The fix uses compareAndDelete(LBA, expectedLSN) — only delete if
|
||||
// the entry's LSN still matches the snapshot LSN. Newer entries are
|
||||
// left in place.
|
||||
//
|
||||
// We construct the race deterministically: write a value, sneak in a
|
||||
// second write to the same LBA before the flusher cycle, then read
|
||||
// back. The read must reflect the SECOND write, not the first.
|
||||
func TestFlusher_ConcurrentWriteRaceLBAStaysFresh(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
|
||||
first := makeBlock(4096, 0xAA)
|
||||
second := makeBlock(4096, 0xBB)
|
||||
|
||||
// First write to LBA 5.
|
||||
if _, err := s.Write(5, first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Hammer the LBA with the SECOND write in a loop while the
|
||||
// background flusher (interval 100ms) ticks. Each iteration
|
||||
// could land in a different position relative to the flusher's
|
||||
// snapshot/cleanup. Across ~50 iterations there is high
|
||||
// probability that at least one iteration interleaves the
|
||||
// write between the flusher's snapshot and its cleanup. With
|
||||
// the bug, that interleaving causes the dirty entry to be
|
||||
// dropped and the next read to return `first` (from extent)
|
||||
// instead of `second`.
|
||||
for iter := 0; iter < 50; iter++ {
|
||||
if _, err := s.Write(5, second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Give the flusher a tick or two to potentially race.
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
got, err := s.Read(5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, second) {
|
||||
t.Fatalf("iter %d: LBA 5 reads %02x, want second-write byte %02x — flusher ate the newer entry",
|
||||
iter, got[0], second[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAllBlocks_ReturnsBlocksAfterFlush is the regression test for
|
||||
// the architect-flagged "AllBlocks contract violation" bug. The
|
||||
// LogicalStorage contract says AllBlocks() returns every WRITTEN
|
||||
// LBA's current bytes. The earlier WALStore.AllBlocks() returned
|
||||
// only the dirty-map entries, which means flushed blocks would
|
||||
// disappear from the result.
|
||||
//
|
||||
// The fix reads every LBA via Read() (which falls back to extent
|
||||
// for non-dirty LBAs) and filters zeros. After the flusher drains
|
||||
// every entry, all written LBAs are still returned.
|
||||
func TestAllBlocks_ReturnsBlocksAfterFlush(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(7, makeBlock(4096, 0x77)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Wait for the flusher to drain — both LBAs out of the dirty
|
||||
// map and into the extent.
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= 2 {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if s.CheckpointLSN() < 2 {
|
||||
t.Fatal("flusher did not advance checkpoint")
|
||||
}
|
||||
|
||||
// AllBlocks must still return both written LBAs even though
|
||||
// they're no longer in the dirty map.
|
||||
all, snapshotErr := s.AllBlocks()
|
||||
if snapshotErr != nil {
|
||||
t.Fatal(snapshotErr)
|
||||
}
|
||||
if len(all) != 2 {
|
||||
t.Fatalf("AllBlocks after flush returned %d entries, want 2", len(all))
|
||||
}
|
||||
if all[1][0] != 0x11 {
|
||||
t.Fatalf("AllBlocks LBA 1: got %02x, want 11", all[1][0])
|
||||
}
|
||||
if all[7][0] != 0x77 {
|
||||
t.Fatalf("AllBlocks LBA 7: got %02x, want 77", all[7][0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecovery_DeterministicAcrossMultipleOpens: after a crash + a
|
||||
// recovered open, calling Recover again on the same on-disk state
|
||||
// yields exactly the same in-memory state.
|
||||
func TestRecovery_DeterministicAcrossMultipleOpens(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "store.bin")
|
||||
|
||||
{
|
||||
s, _ := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
for i := uint32(0); i < 5; i++ {
|
||||
_, _ = s.Write(i, makeBlock(4096, byte(0x10+i)))
|
||||
}
|
||||
_, _ = s.Sync()
|
||||
// Skip Close — simulate crash.
|
||||
s.flusher.Stop()
|
||||
s.committer.Stop()
|
||||
_ = s.fd.Close()
|
||||
}
|
||||
|
||||
// First reopen + Recover.
|
||||
s1, _ := openLegacyWALStoreForTest(path)
|
||||
r1, err := s1.Recover()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
contents1 := make([][]byte, 5)
|
||||
for i := uint32(0); i < 5; i++ {
|
||||
contents1[i], _ = s1.Read(i)
|
||||
}
|
||||
_ = s1.Close()
|
||||
|
||||
// Second reopen + Recover on the same file.
|
||||
s2, _ := openLegacyWALStoreForTest(path)
|
||||
r2, err := s2.Recover()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := uint32(0); i < 5; i++ {
|
||||
got, _ := s2.Read(i)
|
||||
if !bytes.Equal(got, contents1[i]) {
|
||||
t.Fatalf("LBA %d differs across two open+recover cycles", i)
|
||||
}
|
||||
}
|
||||
_ = s2.Close()
|
||||
|
||||
if r1 != r2 {
|
||||
t.Fatalf("Recover frontier not deterministic across reopens: r1=%d r2=%d", r1, r2)
|
||||
}
|
||||
}
|
||||
@@ -125,12 +125,3 @@ func DamageV3RecordTest(path string, lsn uint64) error {
|
||||
}
|
||||
return fmt.Errorf("no v3 record with LSN %d", lsn)
|
||||
}
|
||||
|
||||
// Legacy fixtures only; unavailable in production builds.
|
||||
// TODO(format-v3 row 14a): replace with captured migration fixtures.
|
||||
func CreateLegacyWALStoreTest(path string, blocks uint32, blockSize int) (*WALStore, error) {
|
||||
return createLegacyWALStoreWithOptions(path, blocks, blockSize, WALStoreOptions{})
|
||||
}
|
||||
func OpenLegacyWALStoreTest(path string) (*WALStore, error) {
|
||||
return openLegacyWALStoreWithOptions(path, WALStoreOptions{})
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
package storage
|
||||
|
||||
// legacyC11FileStore preserves the retired C11 file codec for historical tests.
|
||||
// It is compiled only into this package's tests: one state file
|
||||
// (header + dirty-since-HEAD chunks, with a SHA-256 over its body) replaced
|
||||
// atomically on every change, plus an append-only delta log with one JSON
|
||||
// record per closed HEAD period. Every method is durable on return.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type legacyC11FileStore struct {
|
||||
path string
|
||||
|
||||
mu sync.Mutex
|
||||
loaded bool
|
||||
stored bool
|
||||
hdr chunkBitmapHeader
|
||||
dirty []uint64
|
||||
}
|
||||
|
||||
// newLegacyC11FileStore returns a store at path (the delta log is
|
||||
// path + ".deltas").
|
||||
func newLegacyC11FileStore(path string) *legacyC11FileStore {
|
||||
return &legacyC11FileStore{path: path}
|
||||
}
|
||||
|
||||
type chunkBitmapFile struct {
|
||||
Version int `json:"version"`
|
||||
Header chunkBitmapHeader `json:"header"`
|
||||
Dirty []uint64 `json:"dirty"`
|
||||
}
|
||||
|
||||
type chunkBitmapEnvelope struct {
|
||||
Body json.RawMessage `json:"body"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
func (b *legacyC11FileStore) loadLocked() error {
|
||||
if b.loaded {
|
||||
return nil
|
||||
}
|
||||
b.loaded = true
|
||||
raw, err := os.ReadFile(b.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("storage: chunk bitmap read: %w", err)
|
||||
}
|
||||
var env chunkBitmapEnvelope
|
||||
if json.Unmarshal(raw, &env) != nil {
|
||||
return nil // corrupt: treated as lost (hash-compare fallback)
|
||||
}
|
||||
sum := sha256.Sum256(env.Body)
|
||||
if hex.EncodeToString(sum[:]) != env.SHA256 {
|
||||
return nil
|
||||
}
|
||||
var f chunkBitmapFile
|
||||
if json.Unmarshal(env.Body, &f) != nil || f.Version != 1 {
|
||||
return nil
|
||||
}
|
||||
b.stored, b.hdr, b.dirty = true, f.Header, f.Dirty
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *legacyC11FileStore) writeLocked(hdr chunkBitmapHeader, dirty []uint64) error {
|
||||
body, err := json.Marshal(chunkBitmapFile{Version: 1, Header: hdr, Dirty: dirty})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
raw, err := json.Marshal(chunkBitmapEnvelope{Body: body, SHA256: hex.EncodeToString(sum[:])})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeFileDurable(b.path, raw); err != nil {
|
||||
return fmt.Errorf("storage: chunk bitmap write: %w", err)
|
||||
}
|
||||
// Durable on return includes the rename itself.
|
||||
if err := syncDir(filepath.Dir(b.path)); err != nil {
|
||||
return fmt.Errorf("storage: chunk bitmap: fsync directory: %w", err)
|
||||
}
|
||||
b.stored, b.hdr, b.dirty = true, hdr, append([]uint64(nil), dirty...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *legacyC11FileStore) Load() (chunkBitmapHeader, []uint64, bool, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if err := b.loadLocked(); err != nil {
|
||||
return chunkBitmapHeader{}, nil, false, err
|
||||
}
|
||||
if !b.stored {
|
||||
return chunkBitmapHeader{}, nil, false, nil
|
||||
}
|
||||
return b.hdr, append([]uint64(nil), b.dirty...), true, nil
|
||||
}
|
||||
|
||||
func (b *legacyC11FileStore) Save(dirty []uint64) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if err := b.loadLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
return b.writeLocked(b.hdr, dirty)
|
||||
}
|
||||
|
||||
func (b *legacyC11FileStore) WriteHeader(hdr chunkBitmapHeader) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if err := b.loadLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
return b.writeLocked(hdr, b.dirty)
|
||||
}
|
||||
|
||||
func (b *legacyC11FileStore) Reset(hdr chunkBitmapHeader, stillDirty []uint64, delta chunkDelta) error {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if err := b.loadLocked(); err != nil {
|
||||
return err
|
||||
}
|
||||
rec, err := json.Marshal(delta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.OpenFile(b.path+".deltas", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("storage: chunk delta log: %w", err)
|
||||
}
|
||||
if _, err := f.Write(append(rec, '\n')); err != nil {
|
||||
f.Close()
|
||||
return fmt.Errorf("storage: chunk delta log: %w", err)
|
||||
}
|
||||
if err := f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return fmt.Errorf("storage: chunk delta log: %w", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return b.writeLocked(hdr, stillDirty)
|
||||
}
|
||||
|
||||
// Deltas returns the archived delta records, oldest first.
|
||||
func (b *legacyC11FileStore) Deltas() ([]chunkDelta, error) {
|
||||
raw, err := os.ReadFile(b.path + ".deltas")
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []chunkDelta
|
||||
for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) {
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
var d chunkDelta
|
||||
if err := json.Unmarshal(line, &d); err != nil {
|
||||
return nil, fmt.Errorf("storage: chunk delta log: %w", err)
|
||||
}
|
||||
out = append(out, d)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var _ chunkBitmapStore = (*legacyC11FileStore)(nil)
|
||||
@@ -0,0 +1,110 @@
|
||||
//go:build linux
|
||||
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNativeReplacementCheckpointSIGKILL(t *testing.T) {
|
||||
const phaseEnv, pathEnv = "SW_BLOCK_NATIVE_CHECKPOINT_KILL", "SW_BLOCK_NATIVE_CHECKPOINT_PATH"
|
||||
const skipHookEnv = "SW_BLOCK_NATIVE_CHECKPOINT_SKIP_HOOK"
|
||||
if phase := os.Getenv(phaseEnv); phase != "" {
|
||||
s, err := createMappedWALStoreV3ForTest(os.Getenv(pathEnv), 16, 4096, 64*1024, WModeStrict, 4)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(3, blk(0x7C)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kill := func() error { return syscall.Kill(os.Getpid(), syscall.SIGKILL) }
|
||||
switch phase {
|
||||
case "extent_sync":
|
||||
s.flusher.afterExtentSyncForTest = func() { _ = kill() }
|
||||
case "slot_pwrite":
|
||||
if os.Getenv(skipHookEnv) != phase {
|
||||
s.v3.pub.io.fsync = kill
|
||||
}
|
||||
case "slot_sync":
|
||||
real := s.v3.pub.io.fsync
|
||||
if os.Getenv(skipHookEnv) != phase {
|
||||
s.v3.pub.io.fsync = func() error {
|
||||
if err := real(); err != nil {
|
||||
return err
|
||||
}
|
||||
return kill()
|
||||
}
|
||||
}
|
||||
case "tail_publication":
|
||||
default:
|
||||
t.Fatal("unknown native checkpoint crash phase", phase)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if phase == "tail_publication" {
|
||||
_ = kill()
|
||||
t.Fatal("SIGKILL returned")
|
||||
}
|
||||
t.Fatal("flush returned without reaching crash hook", phase)
|
||||
}
|
||||
for _, phase := range []string{"extent_sync", "slot_pwrite", "slot_sync", "tail_publication"} {
|
||||
t.Run(phase, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "volume")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeReplacementCheckpointSIGKILL$")
|
||||
cmd.Env = append(os.Environ(), phaseEnv+"="+phase, pathEnv+"="+path)
|
||||
out, err := cmd.CombinedOutput()
|
||||
var exited *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(err, &exited) || exited.ProcessState.Sys().(syscall.WaitStatus).Signal() != syscall.SIGKILL {
|
||||
t.Fatalf("helper did not reach its own crash hook: %v ctx=%v output=%s", err, ctx.Err(), out)
|
||||
}
|
||||
r, err := OpenWALStore(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
cp := r.CheckpointLSN()
|
||||
if cp > 1 || (phase == "extent_sync" && cp != 0) || ((phase == "slot_sync" || phase == "tail_publication") && cp != 1) {
|
||||
t.Fatalf("%s checkpoint=%d", phase, cp)
|
||||
}
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := r.Read(3); err != nil || !bytes.Equal(got, blk(0x7C)) {
|
||||
t.Fatalf("acknowledged bytes lost at %s: %v", phase, err)
|
||||
}
|
||||
if r.NextLSN() != 2 {
|
||||
t.Fatalf("recovered allocator=%d", r.NextLSN())
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, phase := range []string{"slot_pwrite", "slot_sync"} {
|
||||
t.Run("missing_hook_"+phase, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "volume")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeReplacementCheckpointSIGKILL$")
|
||||
cmd.Env = append(os.Environ(), phaseEnv+"="+phase, pathEnv+"="+path, skipHookEnv+"="+phase)
|
||||
out, err := cmd.CombinedOutput()
|
||||
var exited *exec.ExitError
|
||||
if ctx.Err() != nil || !errors.As(err, &exited) || exited.ProcessState.Sys().(syscall.WaitStatus).Signaled() || !bytes.Contains(out, []byte("flush returned without reaching crash hook")) {
|
||||
t.Fatalf("missing %s hook was not detected: %v ctx=%v output=%s", phase, err, ctx.Err(), out)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// The old engine remains only for explicit fixtures until row 14a. The
|
||||
// production import closure must not bring in its frozen tool/test package,
|
||||
// and no production source may call the legacy constructor chain.
|
||||
// The retired engine must not return through constructors or import aliases.
|
||||
func TestLegacyFixtureIsolation(t *testing.T) {
|
||||
entries, err := os.ReadDir(".")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
forbidden := map[string]bool{"createLegacyWALStoreWithOptions": true, "openLegacyWALStoreWithOptions": true, "openLegacyReadOnlyWithOptions": true}
|
||||
forbidden := map[string]bool{"createLegacyWALStoreWithOptions": true, "openLegacyWALStoreWithOptions": true, "openLegacyReadOnlyWithOptions": true, "newWALWriter": true, "decodeWALEntry": true, "encodeWALPadding": true, "recoverWAL": true, "walEntry": true}
|
||||
for _, e := range entries {
|
||||
n := e.Name()
|
||||
if e.IsDir() || !strings.HasSuffix(n, ".go") || strings.HasSuffix(n, "_test.go") || n == "format_v3_test_support.go" {
|
||||
@@ -74,16 +72,8 @@ func TestLegacyFixtureIsolation(t *testing.T) {
|
||||
|
||||
func legacyConstructorReferences(f *ast.File, forbidden map[string]bool) []string {
|
||||
var refs []string
|
||||
// A constructor declaration is retained for test linking, but every use
|
||||
// (including function values, aliases and arguments) is forbidden.
|
||||
declarations := map[*ast.Ident]bool{}
|
||||
for _, decl := range f.Decls {
|
||||
if fn, ok := decl.(*ast.FuncDecl); ok {
|
||||
declarations[fn.Name] = true
|
||||
}
|
||||
}
|
||||
ast.Inspect(f, func(n ast.Node) bool {
|
||||
if id, ok := n.(*ast.Ident); ok && forbidden[id.Name] && !declarations[id] {
|
||||
if id, ok := n.(*ast.Ident); ok && forbidden[id.Name] {
|
||||
refs = append(refs, id.Name)
|
||||
}
|
||||
return true
|
||||
@@ -95,6 +85,7 @@ func TestLegacyFixtureIsolationRejectsFunctionValues(t *testing.T) {
|
||||
const name = "createLegacyWALStoreWithOptions"
|
||||
for _, body := range []string{
|
||||
"func use() { createLegacyWALStoreWithOptions() }",
|
||||
"func createLegacyWALStoreWithOptions() {}",
|
||||
"var constructor = createLegacyWALStoreWithOptions",
|
||||
"func use() { constructor := createLegacyWALStoreWithOptions; constructor() }",
|
||||
"func use() { accept(createLegacyWALStoreWithOptions) }",
|
||||
@@ -109,11 +100,4 @@ func TestLegacyFixtureIsolationRejectsFunctionValues(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
f, err := parser.ParseFile(token.NewFileSet(), "legacy.go", "package storage\nfunc createLegacyWALStoreWithOptions() {}", 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if refs := legacyConstructorReferences(f, map[string]bool{name: true}); len(refs) != 0 {
|
||||
t.Fatalf("declaration is not a use: %v", refs)
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package storage
|
||||
|
||||
// TODO(format-v3 row 14a): relocate or retire only the inventory-listed v2
|
||||
// engine controls after the named v3 replacements and migration receipts pass.
|
||||
// These explicit fixture constructors are never production selectors.
|
||||
func createLegacyWALStoreForTest(path string, blocks uint32, blockSize int) (*WALStore, error) {
|
||||
return createLegacyWALStoreWithOptions(path, blocks, blockSize, WALStoreOptions{})
|
||||
}
|
||||
func openLegacyWALStoreForTest(path string) (*WALStore, error) {
|
||||
return openLegacyWALStoreWithOptions(path, WALStoreOptions{})
|
||||
}
|
||||
func openLegacyReadOnlyForTest(path string) (*WALStoreReader, error) {
|
||||
return openLegacyReadOnlyWithOptions(path, WALStoreOptions{})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+18
-22
@@ -10,10 +10,10 @@ import (
|
||||
|
||||
// Control the legal scheduler order between a completed physical callback and
|
||||
// its caller publishing/reading the global stable frontier in Sync.
|
||||
func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
|
||||
func TestNativeReplacementSyncCallerReturnOrdering(t *testing.T) {
|
||||
for _, laterPublishesFirst := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("later_publishes_first=%v", laterPublishesFirst), func(t *testing.T) {
|
||||
s := newLegacyGenerationStore(t)
|
||||
s, _ := newMappedCheckpointStoreV3(t)
|
||||
firstEntered, secondEntered, firstCacheReturned := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
releaseFirst, releaseSecond, publishFirst := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
var workers sync.WaitGroup
|
||||
@@ -68,13 +68,18 @@ func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
|
||||
return err
|
||||
}
|
||||
type result struct {
|
||||
frontier uint64
|
||||
err error
|
||||
frontier uint64
|
||||
completed int32
|
||||
err error
|
||||
}
|
||||
leader, followers := make(chan result, 1), make(chan result, 1)
|
||||
start := func(out chan<- result) {
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); n, err := s.Sync(); out <- result{n, err} }()
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
n, err := s.Sync()
|
||||
out <- result{frontier: n, completed: completed.Load(), err: err}
|
||||
}()
|
||||
}
|
||||
await := func(ch <-chan struct{}, label string) {
|
||||
t.Helper()
|
||||
@@ -133,27 +138,18 @@ func TestWALGenerationFirstCallerReturnOrdering(t *testing.T) {
|
||||
} else {
|
||||
closeOnce(publishFirst)
|
||||
}
|
||||
first := receive(leader)
|
||||
// Sync returns the current global stable frontier, not its own cut.
|
||||
// A later return may include a newer independently completed fsync.
|
||||
wantFirst := uint64(1)
|
||||
if laterPublishesFirst {
|
||||
wantFirst = 2
|
||||
}
|
||||
if first.frontier != wantFirst {
|
||||
t.Fatalf("first batch frontier=%d want %d (completed physical syncs=%d laterPublishesFirst=%v)", first.frontier, wantFirst, completed.Load(), laterPublishesFirst)
|
||||
}
|
||||
// Strict v3 may wait for the shared-file sync before publishing
|
||||
// its descriptor. It need not return before the second caller.
|
||||
if !laterPublishesFirst {
|
||||
if completed.Load() != 1 {
|
||||
t.Fatal("held second fsync unexpectedly completed")
|
||||
}
|
||||
closeOnce(releaseSecond)
|
||||
for i := 0; i < 1; i++ {
|
||||
if r := receive(followers); r.frontier != 2 {
|
||||
t.Fatal("follower frontier", r)
|
||||
}
|
||||
if r := receive(followers); r.frontier != 2 || r.completed < 2 {
|
||||
t.Fatal("follower frontier without completed physical sync", r)
|
||||
}
|
||||
}
|
||||
first := receive(leader)
|
||||
if first.frontier < 1 || first.frontier > uint64(first.completed) {
|
||||
t.Fatalf("first frontier exceeds completed physical syncs: %+v", first)
|
||||
}
|
||||
if completed.Load() != 2 || s.WALSyncCount() != 2 {
|
||||
t.Fatalf("physical counts completed=%d attempts=%d", completed.Load(), s.WALSyncCount())
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Tool-only exports for the offline migration `sw-block migrate-v3` (format
|
||||
// bump v3, DESIGN r17.4 section 10.1; plan row 13b). They reuse the row-1
|
||||
// slot codec and the row-6 map codec; there is no second encoder. Nothing
|
||||
// here opens, recovers or serves a store, and the v3 open code calls none of
|
||||
// it.
|
||||
|
||||
var (
|
||||
// ErrMigrateGeometry: the v2 geometry cannot be expressed as v3 without
|
||||
// moving data (DESIGN 10.1 precondition 4).
|
||||
ErrMigrateGeometry = errors.New("storage: v2 geometry cannot be migrated in place to v3")
|
||||
)
|
||||
|
||||
// MigrationSlotAOffset and MigrationSlotBOffset are the v3 slot positions.
|
||||
const (
|
||||
MigrationSlotAOffset = slotAOffsetV3
|
||||
MigrationSlotBOffset = slotBOffsetV3
|
||||
MigrationSlotSize = slotSizeV3
|
||||
// migratedWALMinV3 is the provisional impl-3 minimum WAL size for a
|
||||
// migrated volume: at least 64 KiB and two single-block records.
|
||||
migratedWALMinV3 = 64 * 1024
|
||||
)
|
||||
|
||||
// MigrationSourceV3 is what the tool read from the v2 superblock.
|
||||
type MigrationSourceV3 struct {
|
||||
UUID [16]byte
|
||||
VolumeSize uint64
|
||||
ExtentSize uint32
|
||||
BlockSize uint32
|
||||
OldWALOffset uint64 // must be 4096
|
||||
OldWALSize uint64
|
||||
CreatedAt uint64
|
||||
CheckpointLSN uint64
|
||||
ChunkBlocks uint64 // the map's chunk geometry (the provider's)
|
||||
}
|
||||
|
||||
// MigrationPlanV3 is the v3 image of a migration: the descriptor slot
|
||||
// images in their write order and the new descriptor's hash.
|
||||
type MigrationPlanV3 struct {
|
||||
PreparedB []byte // step 4: slot B, slotGen 1, MigrationPhase prepared
|
||||
CommittedA []byte // step 5: slot A, slotGen 2, phase 0 (the commit point)
|
||||
RolloverB []byte // step 6: slot B, slotGen 3, phase 0
|
||||
// DescriptorHash is the SHA-256 of CommittedA, printed at step 8.
|
||||
DescriptorHash [32]byte
|
||||
}
|
||||
|
||||
// migrationDescriptorV3 is the v3 descriptor for src (DESIGN 10.1 step 4):
|
||||
// WALOffset 8192 and WALSize = old WALSize - 4096, so the extent base
|
||||
// WALOffset + WALSize is unchanged; CheckpointLSN = W = the v2 checkpoint;
|
||||
// an empty cursor space; BaseState none; WMode C.
|
||||
func migrationDescriptorV3(src MigrationSourceV3) (descriptorV3, error) {
|
||||
if src.OldWALOffset != superblockSize {
|
||||
return descriptorV3{}, fmt.Errorf("%w: v2 WALOffset %d, want %d", ErrMigrateGeometry, src.OldWALOffset, superblockSize)
|
||||
}
|
||||
if src.BlockSize == 0 || src.OldWALSize <= slotSizeV3 {
|
||||
return descriptorV3{}, fmt.Errorf("%w: v2 WAL size %d", ErrMigrateGeometry, src.OldWALSize)
|
||||
}
|
||||
walSize := src.OldWALSize - slotSizeV3
|
||||
if walSize%uint64(src.BlockSize) != 0 || walSize < migratedWALMinV3 ||
|
||||
walSize < 2*(walEntryHeaderSizeV3+uint64(src.BlockSize)) {
|
||||
return descriptorV3{}, fmt.Errorf("%w: v3 WAL size %d is not block aligned or below the minimum", ErrMigrateGeometry, walSize)
|
||||
}
|
||||
if src.CheckpointLSN > counterMaxV3 {
|
||||
return descriptorV3{}, fmt.Errorf("%w: checkpoint %d", ErrMigrateGeometry, src.CheckpointLSN)
|
||||
}
|
||||
// The checked extent end (codex01 row 13b P1): the same bounds the slot
|
||||
// validation applies, here, before any backup or sidecar write.
|
||||
if src.VolumeSize == 0 || src.ExtentSize == 0 || src.VolumeSize%uint64(src.BlockSize) != 0 {
|
||||
return descriptorV3{}, fmt.Errorf("%w: volume %d, extent %d, block %d", ErrMigrateGeometry, src.VolumeSize, src.ExtentSize, src.BlockSize)
|
||||
}
|
||||
if end, ok := checkedAddV3(walOffsetV3, walSize); !ok {
|
||||
return descriptorV3{}, fmt.Errorf("%w: the WAL region overflows", ErrMigrateGeometry)
|
||||
} else if fileEnd, ok := checkedAddV3(end, src.VolumeSize); !ok || fileEnd > math.MaxInt64 {
|
||||
return descriptorV3{}, fmt.Errorf("%w: the extent region overflows", ErrMigrateGeometry)
|
||||
}
|
||||
d := descriptorV3{
|
||||
ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, UUID: src.UUID,
|
||||
VolumeSize: src.VolumeSize, ExtentSize: src.ExtentSize, BlockSize: src.BlockSize,
|
||||
WALOffset: walOffsetV3, WALSize: walSize, CreatedAt: src.CreatedAt,
|
||||
CheckpointLSN: src.CheckpointLSN, W: src.CheckpointLSN, WMode: WModeLagged,
|
||||
MapFormatID: mapFormatIDV1, MapGeneration: 1, SlotGen: 1,
|
||||
}
|
||||
if walOffsetV3+walSize != src.OldWALOffset+src.OldWALSize {
|
||||
return descriptorV3{}, fmt.Errorf("%w: the extent base would move", ErrMigrateGeometry)
|
||||
}
|
||||
if _, err := mapShapeForV3(d, src.ChunkBlocks); err != nil {
|
||||
return descriptorV3{}, fmt.Errorf("%w: map geometry: %w", ErrMigrateGeometry, err)
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// ValidateMigrationV3 checks precondition 4 (geometry) without writing.
|
||||
func ValidateMigrationV3(src MigrationSourceV3) error {
|
||||
_, err := migrationDescriptorV3(src)
|
||||
return err
|
||||
}
|
||||
|
||||
// PrepareMigrationV3 runs DESIGN 10.1 step 3 and builds the slot images of
|
||||
// steps 4 to 6. It (re)creates the initial map sidecar at mapPath durably:
|
||||
// generation 1, every chunk UNKNOWN with its inherited checkpoint frontier,
|
||||
// coveredCheckpoint =
|
||||
// the v2 checkpoint (a fully flushed WAL is not remote-clean). The slots
|
||||
// carry a fresh random nonce and the map fields of that root. It writes
|
||||
// nothing to the store file.
|
||||
func PrepareMigrationV3(mapPath string, src MigrationSourceV3) (MigrationPlanV3, error) {
|
||||
d, err := migrationDescriptorV3(src)
|
||||
if err != nil {
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
for _, b := range [][]byte{d.Nonce[:], d.MapLineage[:]} {
|
||||
for b2 := b; ; {
|
||||
if _, err := rand.Read(b2); err != nil {
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
if !allZero(b2) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := os.Remove(mapPath); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return MigrationPlanV3{}, err // a rerun rewrites the map (10.1 rerun table)
|
||||
}
|
||||
m, err := createChunkLSNMapV3(mapPath, d, src.ChunkBlocks)
|
||||
if err != nil {
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
shape, err := mapShapeForV3(d, src.ChunkBlocks)
|
||||
if err != nil {
|
||||
_ = m.Close()
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
entries := make([]chunkLSNEntryV3, int(shape.chunks))
|
||||
for i := range entries {
|
||||
entries[i].Unknown = true
|
||||
entries[i].LSN = src.CheckpointLSN
|
||||
}
|
||||
c, err := m.Prepare(1, src.CheckpointLSN, entries, nil)
|
||||
if err = errors.Join(err, m.Close()); err != nil {
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
d = c.descriptor(d)
|
||||
d.SlotGen, d.MigrationPhase = 1, MigrationPrepared
|
||||
if err := d.validate(nil); err != nil {
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
var plan MigrationPlanV3
|
||||
plan.PreparedB = d.encode()
|
||||
d.SlotGen, d.MigrationPhase = 2, MigrationNormal
|
||||
if err := d.validate(nil); err != nil {
|
||||
return MigrationPlanV3{}, err
|
||||
}
|
||||
plan.CommittedA = d.encode()
|
||||
plan.DescriptorHash = sha256.Sum256(plan.CommittedA)
|
||||
d.SlotGen = 3
|
||||
plan.RolloverB = d.encode()
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// RolloverSlotV3 is step 6 for a rerun that finds a committed slot A of
|
||||
// slotGen 2: the same descriptor at slotGen 3, phase 0.
|
||||
func RolloverSlotV3(committedA []byte) ([]byte, error) {
|
||||
d, err := decodeSlotV3(committedA, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.MigrationPhase != MigrationNormal || d.SlotGen != 2 {
|
||||
return nil, fmt.Errorf("%w: slot A is not a fresh migration commit", errSuperblockInvalid)
|
||||
}
|
||||
d.SlotGen = 3
|
||||
return d.encode(), nil
|
||||
}
|
||||
|
||||
// MigrationSlotStateV3 classifies one raw v3 slot for the rerun table.
|
||||
type MigrationSlotStateV3 int
|
||||
|
||||
const (
|
||||
MigrationSlotInvalid MigrationSlotStateV3 = iota // not a valid v3 slot
|
||||
MigrationSlotPrepared // valid, MigrationPhase prepared
|
||||
MigrationSlotCommitted // valid and selectable (phase 0)
|
||||
)
|
||||
|
||||
// ClassifyMigrationSlotV3 reports a slot's state and slotGen.
|
||||
func ClassifyMigrationSlotV3(raw []byte) (MigrationSlotStateV3, uint64) {
|
||||
d, err := decodeSlotV3(raw, nil)
|
||||
if err != nil {
|
||||
return MigrationSlotInvalid, 0
|
||||
}
|
||||
if d.MigrationPhase == MigrationPrepared {
|
||||
return MigrationSlotPrepared, d.SlotGen
|
||||
}
|
||||
return MigrationSlotCommitted, d.SlotGen
|
||||
}
|
||||
|
||||
func allZero(b []byte) bool {
|
||||
for _, x := range b {
|
||||
if x != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMultiBlockRecordsRequireDistinctOnDiskImplVersion(t *testing.T) {
|
||||
if os.Getenv("SEAWEED_KNOWN_BUGS") != "1" {
|
||||
t.Skip("known bug #189 (open): reproduction runs with SEAWEED_KNOWN_BUGS=1; the fix PR removes this skip")
|
||||
}
|
||||
s, err := CreateWALStore(filepath.Join(t.TempDir(), "store"), 64, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
s.flusher.Stop()
|
||||
s.SetMultiBlockRecords(true)
|
||||
if _, err := s.WriteBatch(2, [][]byte{makeBlock(4096, 0x41), makeBlock(4096, 0x42)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if header[16] != walEntryWriteBatch {
|
||||
t.Fatalf("setup record type=%d, want batch", header[16])
|
||||
}
|
||||
disk, err := readSuperblock(io.NewSectionReader(s.fd, 0, superblockSize))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disk.ImplVersion == 1 {
|
||||
t.Fatal("synced type0x04 multi-block record still advertises legacy impl version1; a pre-multiblock opener cannot reject the incompatible file by version")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChunkAttachRefusesAnUnmappedNativeStore(t *testing.T) {
|
||||
s, _ := newStoreV3(t, WModeStrict)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
f := newFakeChunkRemote()
|
||||
l, err := attachChunkLayerImpl(s, f, ctConfig(1))
|
||||
if l != nil {
|
||||
defer l.Close()
|
||||
}
|
||||
if !errors.Is(err, ErrMapInvalid) {
|
||||
t.Fatalf("unmapped native store fell back to the retired bitmap engine: %v", err)
|
||||
}
|
||||
st := f.stats()
|
||||
if st.puts != 0 || st.gets != 0 || st.getHeads != 0 || st.cas != 0 {
|
||||
t.Fatal("map admission contacted remote before refusing")
|
||||
}
|
||||
}
|
||||
@@ -1,458 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// recoveryResult summarizes what RecoverWAL did on one open.
|
||||
type recoveryResult struct {
|
||||
EntriesReplayed int // valid entries past checkpoint that were replayed
|
||||
HighestLSN uint64 // highest LSN observed across the whole scan
|
||||
WALHead uint64 // reconstructed logical byte head of retained WAL
|
||||
WALTail uint64 // reconstructed logical byte tail of retained WAL
|
||||
TornEntries int // entries discarded due to CRC failure or truncation
|
||||
DefensiveScan bool // true when the superblock was empty and we scanned the whole region
|
||||
// HoleSuspected: a bad entry was followed by a valid later entry
|
||||
// (issue #51). Detection only: it changes nothing about what is
|
||||
// replayed. HoleDetail says where.
|
||||
HoleSuspected bool
|
||||
HoleDetail string
|
||||
}
|
||||
|
||||
// recoverWAL scans the WAL region and replays any entries that have
|
||||
// not yet been checkpointed into the extent. Replayed entries are
|
||||
// inserted into the dirty map so subsequent reads can find them and
|
||||
// the flusher can apply them to the extent.
|
||||
//
|
||||
// Recovery is deliberately defensive: even when the superblock says
|
||||
// WAL is empty, the scanner walks the whole region looking for valid
|
||||
// entries past the recorded head. CRC validation is the stop signal
|
||||
// — the first record that fails CRC marks where torn writes begin
|
||||
// and scanning halts.
|
||||
//
|
||||
// On a clean shutdown the first byte past head is zero or padding,
|
||||
// CRC fails immediately, and the defensive scan adds zero overhead.
|
||||
//
|
||||
// Side effects: if the extended scan finds entries past the
|
||||
// superblock's recorded head, sb.WALHead is bumped so the writer
|
||||
// resumes after them.
|
||||
func recoverWAL(fd *os.File, sb *superblock, dm *dirtyMap) (recoveryResult, error) {
|
||||
result := recoveryResult{}
|
||||
type retainedRecord struct {
|
||||
firstLSN uint64
|
||||
start uint64
|
||||
end uint64
|
||||
}
|
||||
var retainedRecords []retainedRecord
|
||||
|
||||
logicalHead := sb.WALHead
|
||||
logicalTail := sb.WALTail
|
||||
walOffset := sb.WALOffset
|
||||
walSize := sb.WALSize
|
||||
checkpointLSN := sb.WALCheckpointLSN
|
||||
|
||||
type scanRange = recoveryScanRange
|
||||
var ranges []scanRange
|
||||
// lastLSN is the highest LSN decoded so far (detection only).
|
||||
var lastLSN uint64
|
||||
|
||||
if logicalHead == logicalTail && logicalHead%walSize != 0 {
|
||||
// The superblock records an empty WAL at this position (a full
|
||||
// checkpoint persists head == tail). Sync does not persist the
|
||||
// head, so later appends continue contiguously from here: scan
|
||||
// from it. Scanning from offset 0 would let a torn record wrapped
|
||||
// there hide the synced run behind it.
|
||||
start := logicalHead % walSize
|
||||
ranges = append(ranges, scanRange{start, walSize}, scanRange{0, start})
|
||||
result.DefensiveScan = true
|
||||
log.Printf("storage: recovery from an empty superblock window (head==tail=%d checkpoint=%d)",
|
||||
logicalHead, checkpointLSN)
|
||||
} else if logicalHead == logicalTail {
|
||||
// A pre-boundary-persistence crash can leave a wrapped retained
|
||||
// window while the superblock still says empty. Find the high
|
||||
// physical run from record footers, then scan high and low as
|
||||
// disjoint ranges so neither side is hidden behind the gap.
|
||||
highStart, found := findDefensiveHighRunStart(fd, walOffset, walSize)
|
||||
if found && highStart > 0 {
|
||||
ranges = append(
|
||||
ranges,
|
||||
scanRange{highStart, walSize},
|
||||
scanRange{0, highStart},
|
||||
)
|
||||
} else {
|
||||
ranges = append(ranges, scanRange{0, walSize})
|
||||
}
|
||||
result.DefensiveScan = true
|
||||
log.Printf("storage: recovery defensive scan (head==tail=%d checkpoint=%d)",
|
||||
logicalHead, checkpointLSN)
|
||||
} else {
|
||||
physHead := logicalHead % walSize
|
||||
physTail := logicalTail % walSize
|
||||
if physHead > physTail {
|
||||
ranges = append(ranges, scanRange{physTail, physHead})
|
||||
ranges = append(ranges, scanRange{physHead, walSize})
|
||||
if physTail > 0 {
|
||||
ranges = append(ranges, scanRange{0, physTail})
|
||||
}
|
||||
} else {
|
||||
ranges = append(ranges, scanRange{physTail, walSize})
|
||||
if physHead > 0 {
|
||||
ranges = append(ranges, scanRange{0, physHead})
|
||||
}
|
||||
if physHead < physTail {
|
||||
ranges = append(ranges, scanRange{physHead, physTail})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ri, r := range ranges {
|
||||
pos := r.start
|
||||
for pos < r.end {
|
||||
remaining := r.end - pos
|
||||
if remaining < uint64(walEntryHeaderSize) {
|
||||
break
|
||||
}
|
||||
headerBuf := make([]byte, walEntryHeaderSize)
|
||||
absOff := int64(walOffset + pos)
|
||||
if _, err := fd.ReadAt(headerBuf, absOff); err != nil {
|
||||
return result, fmt.Errorf("storage: recovery read header at %d: %w", pos, err)
|
||||
}
|
||||
entryType := headerBuf[16]
|
||||
lengthField := parseLengthFromHeader(headerBuf)
|
||||
|
||||
if entryType == walEntryPadding {
|
||||
pos += uint64(walEntryHeaderSize) + uint64(lengthField)
|
||||
continue
|
||||
}
|
||||
var payloadLen uint64
|
||||
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
|
||||
payloadLen = uint64(lengthField)
|
||||
}
|
||||
entrySize := uint64(walEntryHeaderSize) + payloadLen
|
||||
if entrySize > remaining {
|
||||
result.TornEntries++
|
||||
if err := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, nil); err != nil {
|
||||
return result, err
|
||||
}
|
||||
break
|
||||
}
|
||||
fullBuf := make([]byte, entrySize)
|
||||
if _, err := fd.ReadAt(fullBuf, absOff); err != nil {
|
||||
return result, fmt.Errorf("storage: recovery read entry at %d: %w", pos, err)
|
||||
}
|
||||
entry, err := decodeWALEntry(fullBuf)
|
||||
if err != nil {
|
||||
// Torn write or trailing zeros — stop scanning this range.
|
||||
result.TornEntries++
|
||||
if herr := detectHole(&result, fd, walOffset, ranges, ri, pos, headerBuf, max(lastLSN, checkpointLSN), sb.BlockSize, err); herr != nil {
|
||||
return result, herr
|
||||
}
|
||||
break
|
||||
}
|
||||
highestEntryLSN := entry.LSN
|
||||
if entry.Type == walEntryWriteBatch {
|
||||
maxBlocks := uint64(^uint32(0)) / uint64(sb.BlockSize)
|
||||
if entry.Reserved == 0 ||
|
||||
entry.Reserved > maxBlocks ||
|
||||
entry.Reserved-1 > ^uint64(0)-entry.LSN ||
|
||||
uint64(entry.Length) != entry.Reserved*uint64(sb.BlockSize) {
|
||||
return result, NewWALIntegrityFailure(
|
||||
nil,
|
||||
fmt.Sprintf(
|
||||
"invalid walstore batch at offset=%d LSN=%d reserved=%d length=%d block_size=%d",
|
||||
pos, entry.LSN, entry.Reserved, entry.Length, sb.BlockSize,
|
||||
),
|
||||
)
|
||||
}
|
||||
highestEntryLSN = entry.LSN + entry.Reserved - 1
|
||||
}
|
||||
if highestEntryLSN > lastLSN {
|
||||
lastLSN = highestEntryLSN
|
||||
}
|
||||
if highestEntryLSN <= checkpointLSN {
|
||||
pos += entrySize
|
||||
continue
|
||||
}
|
||||
firstRetainedLSN := entry.LSN
|
||||
if firstRetainedLSN <= checkpointLSN {
|
||||
firstRetainedLSN = checkpointLSN + 1
|
||||
}
|
||||
retainedRecords = append(retainedRecords, retainedRecord{
|
||||
firstLSN: firstRetainedLSN,
|
||||
start: pos,
|
||||
end: pos + entrySize,
|
||||
})
|
||||
switch entry.Type {
|
||||
case walEntryWrite:
|
||||
blocks := entry.Length / sb.BlockSize
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
dm.putAtIfNewer(
|
||||
entry.LBA+uint64(i), pos, i*sb.BlockSize,
|
||||
entry.LSN, sb.BlockSize,
|
||||
)
|
||||
}
|
||||
result.EntriesReplayed++
|
||||
case walEntryWriteBatch:
|
||||
blocks := uint32(entry.Reserved)
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
lsn := entry.LSN + uint64(i)
|
||||
if lsn <= checkpointLSN {
|
||||
continue
|
||||
}
|
||||
dm.putAtIfNewer(
|
||||
entry.LBA+uint64(i), pos, i*sb.BlockSize,
|
||||
lsn, sb.BlockSize,
|
||||
)
|
||||
}
|
||||
result.EntriesReplayed++
|
||||
case walEntryTrim:
|
||||
blocks := entry.Length / sb.BlockSize
|
||||
if blocks == 0 {
|
||||
blocks = 1
|
||||
}
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
dm.putAtIfNewer(
|
||||
entry.LBA+uint64(i), pos, i*sb.BlockSize,
|
||||
entry.LSN, sb.BlockSize,
|
||||
)
|
||||
}
|
||||
result.EntriesReplayed++
|
||||
case walEntryBarrier:
|
||||
// no data; skip
|
||||
}
|
||||
if highestEntryLSN > result.HighestLSN {
|
||||
result.HighestLSN = highestEntryLSN
|
||||
}
|
||||
pos += entrySize
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(retainedRecords, func(left, right int) bool {
|
||||
return retainedRecords[left].firstLSN < retainedRecords[right].firstLSN
|
||||
})
|
||||
if len(retainedRecords) > 0 {
|
||||
result.WALTail = retainedRecords[0].start
|
||||
result.WALHead = retainedRecords[0].end
|
||||
previousStart := retainedRecords[0].start
|
||||
var wrapBase uint64
|
||||
for _, record := range retainedRecords[1:] {
|
||||
if record.start < previousStart {
|
||||
wrapBase += walSize
|
||||
}
|
||||
logicalStart := wrapBase + record.start
|
||||
logicalEnd := wrapBase + record.end
|
||||
if logicalStart < result.WALHead || logicalEnd-logicalStart > walSize {
|
||||
return result, NewWALIntegrityFailure(
|
||||
nil,
|
||||
fmt.Sprintf(
|
||||
"invalid walstore recovery order at LSN=%d offset=%d",
|
||||
record.firstLSN, record.start,
|
||||
),
|
||||
)
|
||||
}
|
||||
result.WALHead = logicalEnd
|
||||
previousStart = record.start
|
||||
}
|
||||
if result.WALHead < result.WALTail ||
|
||||
result.WALHead-result.WALTail > walSize {
|
||||
return result, NewWALIntegrityFailure(
|
||||
nil,
|
||||
fmt.Sprintf(
|
||||
"invalid walstore recovery bounds tail=%d head=%d size=%d",
|
||||
result.WALTail, result.WALHead, walSize,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
if result.DefensiveScan && result.EntriesReplayed > 0 {
|
||||
log.Printf(
|
||||
"storage: recovery reconstructed WAL bytes tail=%d head=%d frontier=%d (%d replayed)",
|
||||
result.WALTail, result.WALHead, result.HighestLSN, result.EntriesReplayed,
|
||||
)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func findDefensiveHighRunStart(
|
||||
fd *os.File,
|
||||
walOffset uint64,
|
||||
walSize uint64,
|
||||
) (uint64, bool) {
|
||||
maxGap := uint64(walEntryHeaderSize - 1)
|
||||
if maxGap >= walSize {
|
||||
maxGap = walSize - 1
|
||||
}
|
||||
for gap := uint64(0); gap <= maxGap; gap++ {
|
||||
cursor := walSize - gap
|
||||
start, entry, ok := previousValidWALRecord(fd, walOffset, cursor)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
earliest := start
|
||||
foundData := entry.Type != walEntryPadding
|
||||
cursor = start
|
||||
for cursor > 0 {
|
||||
previousStart, previous, ok := previousValidWALRecord(
|
||||
fd, walOffset, cursor,
|
||||
)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
earliest = previousStart
|
||||
if previous.Type != walEntryPadding {
|
||||
foundData = true
|
||||
}
|
||||
cursor = previousStart
|
||||
}
|
||||
if foundData {
|
||||
return earliest, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func previousValidWALRecord(
|
||||
fd *os.File,
|
||||
walOffset uint64,
|
||||
end uint64,
|
||||
) (uint64, walEntry, bool) {
|
||||
if end < 4 {
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
var sizeBytes [4]byte
|
||||
if _, err := fd.ReadAt(sizeBytes[:], int64(walOffset+end-4)); err != nil {
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
size := uint64(binary.LittleEndian.Uint32(sizeBytes[:]))
|
||||
if size < uint64(walEntryHeaderSize) || size > end {
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
start := end - size
|
||||
record := make([]byte, size)
|
||||
if _, err := fd.ReadAt(record, int64(walOffset+start)); err != nil {
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
entry, err := decodeWALEntry(record)
|
||||
if err != nil {
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
switch entry.Type {
|
||||
case walEntryWrite, walEntryWriteBatch, walEntryTrim,
|
||||
walEntryBarrier, walEntryPadding:
|
||||
return start, entry, true
|
||||
default:
|
||||
return 0, walEntry{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// recoveryScanRange is a physical [start, end) span of the WAL region.
|
||||
type recoveryScanRange struct {
|
||||
start, end uint64
|
||||
}
|
||||
|
||||
func allZeroBytes(b []byte) bool {
|
||||
for _, c := range b {
|
||||
if c != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// laterValidEntry looks, from pos in ranges[ri] through the later ranges,
|
||||
// for an offset holding a valid WAL entry (it decodes, CRC included) whose
|
||||
// LSN is above minLSN. It runs only after a bad entry, so a linear resync
|
||||
// over the remaining WAL is acceptable; a cheap header prefilter keeps the
|
||||
// full decodes to plausible candidates.
|
||||
func laterValidEntry(fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos, minLSN uint64, blockSize uint32) (bool, uint64, error) {
|
||||
const window = 1 << 20
|
||||
hdr := uint64(walEntryHeaderSize)
|
||||
for i := ri; i < len(ranges); i++ {
|
||||
start, end := ranges[i].start, ranges[i].end
|
||||
if i == ri {
|
||||
start = pos
|
||||
}
|
||||
for p := start; p+hdr <= end; p += window {
|
||||
n := min(window+hdr, end-p)
|
||||
buf := make([]byte, n)
|
||||
if _, err := fd.ReadAt(buf, int64(walOffset+p)); err != nil {
|
||||
return false, 0, fmt.Errorf("storage: recovery resync read at %d: %w", p, err)
|
||||
}
|
||||
for q := uint64(0); q+hdr <= n && q < window; q++ {
|
||||
size, ok := plausibleEntryHeader(buf[q:q+hdr], minLSN, end-(p+q), blockSize)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
full := make([]byte, size)
|
||||
if _, err := fd.ReadAt(full, int64(walOffset+p+q)); err != nil {
|
||||
return false, 0, fmt.Errorf("storage: recovery resync read entry at %d: %w", p+q, err)
|
||||
}
|
||||
if _, err := decodeWALEntry(full); err == nil {
|
||||
return true, p + q, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false, 0, nil
|
||||
}
|
||||
|
||||
// plausibleEntryHeader is the resync prefilter: a known record type, an
|
||||
// LSN above minLSN, and a length that fits in what remains.
|
||||
func plausibleEntryHeader(h []byte, minLSN, remaining uint64, blockSize uint32) (uint64, bool) {
|
||||
lsn := binary.LittleEndian.Uint64(h[0:8])
|
||||
if lsn <= minLSN {
|
||||
return 0, false
|
||||
}
|
||||
length := uint64(parseLengthFromHeader(h))
|
||||
size := uint64(walEntryHeaderSize)
|
||||
switch h[16] {
|
||||
case walEntryWrite, walEntryWriteBatch:
|
||||
if length == 0 || blockSize == 0 || length%uint64(blockSize) != 0 {
|
||||
return 0, false
|
||||
}
|
||||
size += length
|
||||
case walEntryTrim, walEntryBarrier:
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
if size > remaining {
|
||||
return 0, false
|
||||
}
|
||||
return size, true
|
||||
}
|
||||
|
||||
// detectHole notes a suspected WAL hole at a bad entry (issue #51;
|
||||
// detection only). An all-zero
|
||||
// header is just the end of what was written. Otherwise, if a valid entry
|
||||
// with an LSN above minLSN (the highest decoded so far, or the checkpoint)
|
||||
// follows it, the hole is recorded as the typed warning
|
||||
// WarningWALHoleSuspected and logged. Nothing about the replay changes:
|
||||
// the caller stops this range exactly as before. A torn tail and a
|
||||
// corrupted record cannot be told apart without a synced watermark, hence
|
||||
// "suspected".
|
||||
func detectHole(result *recoveryResult, fd *os.File, walOffset uint64, ranges []recoveryScanRange, ri int, pos uint64, header []byte, minLSN uint64, blockSize uint32, cause error) error {
|
||||
if allZeroBytes(header) || result.HoleSuspected {
|
||||
return nil
|
||||
}
|
||||
found, at, err := laterValidEntry(fd, walOffset, ranges, ri, pos+1, minLSN, blockSize)
|
||||
if err != nil {
|
||||
// Detection never changes the outcome: a failed look-ahead read
|
||||
// is logged, and recovery goes on exactly as before.
|
||||
log.Printf("storage: recovery hole detection at offset=%d skipped: %v", pos, err)
|
||||
return nil
|
||||
}
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
result.HoleSuspected = true
|
||||
result.HoleDetail = fmt.Sprintf("WAL entry at offset=%d fails its check and a valid later entry (LSN > %d) follows at offset=%d", pos, minLSN, at)
|
||||
if cause != nil {
|
||||
result.HoleDetail += " (" + cause.Error() + ")"
|
||||
}
|
||||
log.Printf("storage: recovery %s: %s", WarningWALHoleSuspected, result.HoleDetail)
|
||||
return nil
|
||||
}
|
||||
@@ -1,244 +1,19 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"time"
|
||||
)
|
||||
import "errors"
|
||||
|
||||
// WAL entry kinds.
|
||||
const (
|
||||
walEntryWrite = 0x01
|
||||
walEntryTrim = 0x02
|
||||
walEntryBarrier = 0x03
|
||||
walEntryWriteBatch = 0x04
|
||||
walEntryPadding = 0xFF
|
||||
|
||||
// walEntryHeaderSize is the TOTAL fixed overhead per record. Layout:
|
||||
// prefix (30 bytes):
|
||||
// LSN(8) + Reserved(8) + Type(1) + Flags(1) + LBA(8) + Length(4)
|
||||
// variable-length data
|
||||
// trailer (8 bytes):
|
||||
// CRC32(4) + EntrySize(4)
|
||||
// Total = 30 + len(Data) + 8. The constant captures the 30+8=38 of
|
||||
// fixed overhead so callers can compute total_size = header + data.
|
||||
//
|
||||
// Reserved holds 0 today. It exists to keep the on-disk layout
|
||||
// stable if a future implementation needs to attach an
|
||||
// implementation-private uint64 (e.g. a fencing token from the
|
||||
// engine) without a format version bump.
|
||||
walEntryHeaderSize = 38
|
||||
|
||||
// walEntryPrefixSize is the offset where data starts inside a
|
||||
// serialized record. Distinct from walEntryHeaderSize because the
|
||||
// 8-byte trailer (CRC + EntrySize) lives AFTER the data, not
|
||||
// before it. Readers fetching data slice from absOff +
|
||||
// walEntryPrefixSize, NOT walEntryHeaderSize.
|
||||
walEntryPrefixSize = 30
|
||||
)
|
||||
|
||||
var (
|
||||
errCRCMismatch = errors.New("storage: WAL entry CRC mismatch")
|
||||
errInvalidEntry = errors.New("storage: invalid WAL entry")
|
||||
errEntryTruncated = errors.New("storage: WAL entry truncated")
|
||||
errWALFull = errors.New("storage: WAL region full")
|
||||
errWALPwrite = errors.New("storage: WAL pwrite failed")
|
||||
)
|
||||
|
||||
// walEntry is one variable-size record in the WAL region of a store
|
||||
// file. Stored bytes are exactly walEntryHeaderSize + Length when Type
|
||||
// is Write/Padding, or walEntryHeaderSize when Type is Trim/Barrier.
|
||||
type walEntry struct {
|
||||
LSN uint64
|
||||
Reserved uint64 // see walEntryHeaderSize comment
|
||||
Type uint8
|
||||
Flags uint8
|
||||
LBA uint64 // in blocks
|
||||
Length uint32 // bytes — data length for Write/Padding, trim extent for Trim
|
||||
Data []byte // present only for Write
|
||||
}
|
||||
|
||||
// encode serializes the entry into a fresh byte slice. CRC32 covers
|
||||
// every byte from offset 0 through Data inclusive. The trailing 8
|
||||
// bytes are CRC32 + EntrySize so a reader can detect torn writes by
|
||||
// verifying both fields.
|
||||
func (e *walEntry) encode() ([]byte, error) {
|
||||
return e.encodeWithInstrumentation(nil)
|
||||
}
|
||||
|
||||
func (e *walEntry) encodeWithInstrumentation(instr *writeInstrumentation) ([]byte, error) {
|
||||
totalSize, err := e.encodedSize()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf := make([]byte, totalSize)
|
||||
if err := e.encodeInto(buf, instr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
func (e *walEntry) appendEncoded(dst []byte, instr *writeInstrumentation) ([]byte, error) {
|
||||
totalSize, err := e.encodedSize()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
start := len(dst)
|
||||
dst = growWALRecordBuffer(dst, totalSize)
|
||||
if err := e.encodeInto(dst[start:], instr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
func growWALRecordBuffer(dst []byte, n int) []byte {
|
||||
newLen := len(dst) + n
|
||||
if newLen <= cap(dst) {
|
||||
return dst[:newLen]
|
||||
}
|
||||
newCap := cap(dst) * 2
|
||||
if newCap < newLen {
|
||||
newCap = newLen
|
||||
}
|
||||
next := make([]byte, newLen, newCap)
|
||||
copy(next, dst)
|
||||
return next
|
||||
}
|
||||
|
||||
func (e *walEntry) encodedSize() (int, error) {
|
||||
switch e.Type {
|
||||
case walEntryWrite:
|
||||
if len(e.Data) == 0 {
|
||||
return 0, fmt.Errorf("%w: write entry with no data", errInvalidEntry)
|
||||
}
|
||||
if uint32(len(e.Data)) != e.Length {
|
||||
return 0, fmt.Errorf("%w: data len %d != Length %d", errInvalidEntry, len(e.Data), e.Length)
|
||||
}
|
||||
case walEntryWriteBatch:
|
||||
if e.Reserved == 0 {
|
||||
return 0, fmt.Errorf("%w: batch write entry with zero block count", errInvalidEntry)
|
||||
}
|
||||
if len(e.Data) == 0 {
|
||||
return 0, fmt.Errorf("%w: batch write entry with no data", errInvalidEntry)
|
||||
}
|
||||
if uint32(len(e.Data)) != e.Length {
|
||||
return 0, fmt.Errorf("%w: batch data len %d != Length %d", errInvalidEntry, len(e.Data), e.Length)
|
||||
}
|
||||
case walEntryTrim:
|
||||
if len(e.Data) != 0 {
|
||||
return 0, fmt.Errorf("%w: trim entry must have no data payload", errInvalidEntry)
|
||||
}
|
||||
case walEntryBarrier:
|
||||
if e.Length != 0 || len(e.Data) != 0 {
|
||||
return 0, fmt.Errorf("%w: barrier entry must have no data", errInvalidEntry)
|
||||
}
|
||||
}
|
||||
return walEntryHeaderSize + len(e.Data), nil
|
||||
}
|
||||
|
||||
func (e *walEntry) encodeInto(buf []byte, instr *writeInstrumentation) error {
|
||||
start := time.Now()
|
||||
totalSize, err := e.encodedSize()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(buf) < totalSize {
|
||||
return fmt.Errorf("%w: encode buffer size %d < entry size %d", errInvalidEntry, len(buf), totalSize)
|
||||
}
|
||||
buf = buf[:totalSize]
|
||||
le := binary.LittleEndian
|
||||
off := 0
|
||||
le.PutUint64(buf[off:], e.LSN)
|
||||
off += 8
|
||||
le.PutUint64(buf[off:], e.Reserved)
|
||||
off += 8
|
||||
buf[off] = e.Type
|
||||
off++
|
||||
buf[off] = e.Flags
|
||||
off++
|
||||
le.PutUint64(buf[off:], e.LBA)
|
||||
off += 8
|
||||
le.PutUint32(buf[off:], e.Length)
|
||||
off += 4
|
||||
if len(e.Data) > 0 {
|
||||
copyStart := time.Now()
|
||||
copy(buf[off:], e.Data)
|
||||
if instr != nil {
|
||||
instr.recordWALCopy(len(e.Data), time.Since(copyStart))
|
||||
}
|
||||
off += len(e.Data)
|
||||
}
|
||||
checksumStart := time.Now()
|
||||
checksum := crc32.ChecksumIEEE(buf[:off])
|
||||
if instr != nil {
|
||||
instr.recordWALChecksum(off, time.Since(checksumStart))
|
||||
}
|
||||
le.PutUint32(buf[off:], checksum)
|
||||
off += 4
|
||||
le.PutUint32(buf[off:], uint32(totalSize))
|
||||
if instr != nil {
|
||||
instr.recordWALEncode(len(buf), time.Since(start))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeWALEntry parses a record from buf and verifies its CRC and
|
||||
// declared size. Returns errEntryTruncated if buf is too short to
|
||||
// hold the declared entry, errCRCMismatch if the stored CRC does
|
||||
// not match the recomputed one.
|
||||
func decodeWALEntry(buf []byte) (walEntry, error) {
|
||||
if len(buf) < walEntryHeaderSize {
|
||||
return walEntry{}, fmt.Errorf("%w: need %d bytes, have %d",
|
||||
errEntryTruncated, walEntryHeaderSize, len(buf))
|
||||
}
|
||||
le := binary.LittleEndian
|
||||
var e walEntry
|
||||
off := 0
|
||||
e.LSN = le.Uint64(buf[off:])
|
||||
off += 8
|
||||
e.Reserved = le.Uint64(buf[off:])
|
||||
off += 8
|
||||
e.Type = buf[off]
|
||||
off++
|
||||
e.Flags = buf[off]
|
||||
off++
|
||||
e.LBA = le.Uint64(buf[off:])
|
||||
off += 8
|
||||
e.Length = le.Uint32(buf[off:])
|
||||
off += 4
|
||||
|
||||
var dataLen int
|
||||
if e.Type == walEntryWrite || e.Type == walEntryWriteBatch || e.Type == walEntryPadding {
|
||||
dataLen = int(e.Length)
|
||||
}
|
||||
dataEnd := off + dataLen
|
||||
if dataEnd+8 > len(buf) {
|
||||
return walEntry{}, fmt.Errorf("%w: need %d, have %d", errEntryTruncated, dataEnd+8, len(buf))
|
||||
}
|
||||
if dataLen > 0 {
|
||||
e.Data = make([]byte, dataLen)
|
||||
copy(e.Data, buf[off:dataEnd])
|
||||
}
|
||||
storedCRC := le.Uint32(buf[dataEnd:])
|
||||
storedSize := le.Uint32(buf[dataEnd+4:])
|
||||
|
||||
expectedCRC := crc32.ChecksumIEEE(buf[:dataEnd])
|
||||
if storedCRC != expectedCRC {
|
||||
return walEntry{}, fmt.Errorf("%w: stored=%08x computed=%08x",
|
||||
errCRCMismatch, storedCRC, expectedCRC)
|
||||
}
|
||||
expectedSize := uint32(walEntryHeaderSize + dataLen)
|
||||
if storedSize != expectedSize {
|
||||
return walEntry{}, fmt.Errorf("%w: EntrySize=%d, expected=%d",
|
||||
errInvalidEntry, storedSize, expectedSize)
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// parseLengthFromHeader reads the Length field from a header-only
|
||||
// buffer. Used by the recovery scanner to compute the full record
|
||||
// size before reading the rest. Length is at offset
|
||||
// 8(LSN) + 8(Reserved) + 1(Type) + 1(Flags) + 8(LBA) = 26.
|
||||
func parseLengthFromHeader(headerBuf []byte) uint32 {
|
||||
return binary.LittleEndian.Uint32(headerBuf[26:])
|
||||
}
|
||||
@@ -2,230 +2,37 @@ package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// walEntryFuzzSeeds are well-formed records of every kind the writers
|
||||
// produce, plus truncated and corrupted variants. Under `go test` (no
|
||||
// -fuzz) the fuzz targets below run exactly these seeds.
|
||||
func walEntryFuzzSeeds(t testing.TB) [][]byte {
|
||||
t.Helper()
|
||||
enc := func(e walEntry) []byte {
|
||||
b, err := e.encode()
|
||||
func FuzzDecodeWALEntryV3(f *testing.F) {
|
||||
for _, e := range []walEntryV3{
|
||||
{LSN: 1, Type: walEntryWrite, LBA: 2, Length: 4096, Data: bytes.Repeat([]byte{0x41}, 4096)},
|
||||
{LSN: 1, Type: walEntryWriteBatch, LBA: 2, BatchCount: 2, Length: 8192, Data: bytes.Repeat([]byte{0x42}, 8192)},
|
||||
{LSN: 1, Type: walEntryTrim, LBA: 2, Length: 8192},
|
||||
{LSN: 1, Type: walEntryBarrier},
|
||||
{Type: walEntryPadding, Length: 32, Data: make([]byte, 32)},
|
||||
} {
|
||||
e.Nonce[0] = 1
|
||||
b, err := encodeWALEntryV3(e, 4096, 64)
|
||||
if err != nil {
|
||||
t.Fatalf("seed %+v: %v", e, err)
|
||||
f.Fatal(err)
|
||||
}
|
||||
return b
|
||||
f.Add(b)
|
||||
f.Add(append(append([]byte(nil), b...), 0xA5))
|
||||
}
|
||||
pad, err := encodeWALPadding(walEntryHeaderSize + 16)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
block := bytes.Repeat([]byte{0xA5}, 512)
|
||||
seeds := [][]byte{
|
||||
enc(walEntry{LSN: 1, Type: walEntryWrite, LBA: 7, Length: uint32(len(block)), Data: block}),
|
||||
enc(walEntry{LSN: 9, Reserved: 2, Type: walEntryWriteBatch, LBA: 3, Length: 1024, Data: bytes.Repeat([]byte{0x5A}, 1024)}),
|
||||
enc(walEntry{LSN: 4, Type: walEntryTrim, LBA: 10, Length: 8192}),
|
||||
enc(walEntry{LSN: 5, Type: walEntryBarrier}),
|
||||
pad,
|
||||
{},
|
||||
make([]byte, walEntryHeaderSize),
|
||||
}
|
||||
good := seeds[0]
|
||||
seeds = append(seeds,
|
||||
good[:walEntryHeaderSize-1], // short header
|
||||
good[:len(good)-1], // short trailer
|
||||
append(append([]byte{}, good...), 0xFF), // trailing byte
|
||||
)
|
||||
flipped := append([]byte{}, good...)
|
||||
flipped[40] ^= 0x01 // data byte: CRC mismatch
|
||||
seeds = append(seeds, flipped)
|
||||
huge := append([]byte{}, good[:walEntryHeaderSize]...)
|
||||
binary.LittleEndian.PutUint32(huge[26:], ^uint32(0)) // Length claims 4 GiB
|
||||
seeds = append(seeds, huge)
|
||||
return seeds
|
||||
}
|
||||
|
||||
// FuzzDecodeWALEntry: decodeWALEntry never panics; an error comes with the
|
||||
// zero value; an accepted record is self-consistent and re-encodes to
|
||||
// exactly the bytes it was decoded from.
|
||||
func FuzzDecodeWALEntry(f *testing.F) {
|
||||
for _, s := range walEntryFuzzSeeds(f) {
|
||||
f.Add(s)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
e, err := decodeWALEntry(data)
|
||||
if err != nil {
|
||||
if !reflect.DeepEqual(e, walEntry{}) {
|
||||
t.Fatalf("error %v with a partial value %+v", err, e)
|
||||
}
|
||||
return
|
||||
f.Add([]byte{})
|
||||
f.Fuzz(func(t *testing.T, b []byte) {
|
||||
if len(b) > 1<<20 {
|
||||
t.Skip()
|
||||
}
|
||||
size := walEntryHeaderSize + len(e.Data)
|
||||
if size > len(data) {
|
||||
t.Fatalf("decoded %d bytes from a %d-byte buffer", size, len(data))
|
||||
}
|
||||
if got := binary.LittleEndian.Uint32(data[size-4:]); got != uint32(size) {
|
||||
t.Fatalf("EntrySize field %d, record is %d bytes", got, size)
|
||||
}
|
||||
switch e.Type {
|
||||
case walEntryWrite, walEntryWriteBatch, walEntryPadding:
|
||||
if uint32(len(e.Data)) != e.Length {
|
||||
t.Fatalf("type %d: %d data bytes, Length %d", e.Type, len(e.Data), e.Length)
|
||||
}
|
||||
default:
|
||||
if e.Data != nil {
|
||||
t.Fatalf("type %d decoded with a payload", e.Type)
|
||||
}
|
||||
}
|
||||
if gap := knownWALDecodeGap(e); gap != "" {
|
||||
return // pinned below; see knownWALDecodeGap
|
||||
}
|
||||
if reason := walEntryEncoderRefuses(e); reason != "" {
|
||||
t.Fatalf("decoder accepted a record the encoder refuses (%s): %+v", reason, e)
|
||||
}
|
||||
re, err := e.encode()
|
||||
if err != nil {
|
||||
t.Fatalf("re-encode of an accepted record: %v", err)
|
||||
}
|
||||
if !bytes.Equal(re, data[:size]) {
|
||||
t.Fatalf("re-encode differs from the decoded bytes")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// FuzzWALEntryRoundTrip: every entry the encoder accepts decodes back to
|
||||
// itself.
|
||||
func FuzzWALEntryRoundTrip(f *testing.F) {
|
||||
f.Add(uint64(1), uint64(0), uint8(walEntryWrite), uint8(0), uint64(7), uint32(4), []byte("abcd"))
|
||||
f.Add(uint64(9), uint64(2), uint8(walEntryWriteBatch), uint8(0), uint64(3), uint32(2), []byte("xy"))
|
||||
f.Add(uint64(4), uint64(0), uint8(walEntryTrim), uint8(0), uint64(10), uint32(8192), []byte(nil))
|
||||
f.Add(uint64(5), uint64(0), uint8(walEntryBarrier), uint8(0), uint64(0), uint32(0), []byte(nil))
|
||||
f.Add(uint64(6), uint64(0), uint8(walEntryPadding), uint8(0), uint64(0), uint32(3), []byte{0, 0, 0})
|
||||
f.Fuzz(func(t *testing.T, lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, data []byte) {
|
||||
e := walEntry{LSN: lsn, Reserved: reserved, Type: typ, Flags: flags, LBA: lba, Length: length, Data: data}
|
||||
if len(e.Data) == 0 {
|
||||
e.Data = nil
|
||||
}
|
||||
buf, err := e.encode()
|
||||
e, err := decodeWALEntryV3(b, 4096, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if gap := knownWALEncodeGap(e); gap != "" {
|
||||
return // pinned below; see knownWALEncodeGap
|
||||
}
|
||||
got, err := decodeWALEntry(buf)
|
||||
if err != nil {
|
||||
t.Fatalf("encoder accepted %+v but its bytes do not decode: %v", e, err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, e) {
|
||||
t.Fatalf("round trip: got %+v, want %+v", got, e)
|
||||
encoded, err := encodeWALEntryV3(e, 4096, 64)
|
||||
if err != nil || len(encoded) > len(b) || !bytes.Equal(encoded, b[:len(encoded)]) {
|
||||
t.Fatalf("accepted native record does not roundtrip: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// walEntryEncoderRefuses mirrors encodedSize's checks for a decoded entry
|
||||
// ("" when the encoder accepts it).
|
||||
func walEntryEncoderRefuses(e walEntry) string {
|
||||
if _, err := e.encodedSize(); err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// rawWALEntry lays out header fields, payload and a valid CRC/EntrySize
|
||||
// exactly as the on-disk format does, without the encoder's checks, so the
|
||||
// fuzzer reaches the decoder's acceptance rules instead of the CRC.
|
||||
func rawWALEntry(lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, payload []byte) []byte {
|
||||
le := binary.LittleEndian
|
||||
buf := make([]byte, 30+len(payload)+8)
|
||||
le.PutUint64(buf[0:], lsn)
|
||||
le.PutUint64(buf[8:], reserved)
|
||||
buf[16] = typ
|
||||
buf[17] = flags
|
||||
le.PutUint64(buf[18:], lba)
|
||||
le.PutUint32(buf[26:], length)
|
||||
copy(buf[30:], payload)
|
||||
end := 30 + len(payload)
|
||||
le.PutUint32(buf[end:], crc32.ChecksumIEEE(buf[:end]))
|
||||
le.PutUint32(buf[end+4:], uint32(len(buf)))
|
||||
return buf
|
||||
}
|
||||
|
||||
// FuzzDecodeWALEntryFields: records with a valid CRC and EntrySize but
|
||||
// arbitrary field values; the decoder must accept only what the encoder
|
||||
// can produce.
|
||||
func FuzzDecodeWALEntryFields(f *testing.F) {
|
||||
f.Add(uint64(1), uint64(0), uint8(walEntryWrite), uint8(0), uint64(7), uint32(4), []byte("abcd"))
|
||||
f.Add(uint64(9), uint64(2), uint8(walEntryWriteBatch), uint8(0), uint64(3), uint32(2), []byte("xy"))
|
||||
f.Add(uint64(4), uint64(0), uint8(walEntryTrim), uint8(0), uint64(10), uint32(8192), []byte(nil))
|
||||
f.Add(uint64(5), uint64(0), uint8(walEntryBarrier), uint8(0), uint64(0), uint32(0), []byte(nil))
|
||||
f.Add(uint64(6), uint64(0), uint8(walEntryPadding), uint8(0), uint64(0), uint32(3), []byte{0, 0, 0})
|
||||
f.Fuzz(func(t *testing.T, lsn, reserved uint64, typ, flags uint8, lba uint64, length uint32, payload []byte) {
|
||||
buf := rawWALEntry(lsn, reserved, typ, flags, lba, length, payload)
|
||||
e, err := decodeWALEntry(buf)
|
||||
if err != nil {
|
||||
if !reflect.DeepEqual(e, walEntry{}) {
|
||||
t.Fatalf("error %v with a partial value %+v", err, e)
|
||||
}
|
||||
return
|
||||
}
|
||||
if gap := knownWALDecodeGap(e); gap != "" {
|
||||
return // pinned below; see knownWALDecodeGap
|
||||
}
|
||||
if reason := walEntryEncoderRefuses(e); reason != "" {
|
||||
t.Fatalf("decoder accepted a record the encoder refuses (%s): %+v", reason, e)
|
||||
}
|
||||
re, err := e.encode()
|
||||
if err != nil || !bytes.Equal(re, buf[:walEntryHeaderSize+len(e.Data)]) {
|
||||
t.Fatalf("accepted record does not re-encode to its bytes (err %v): %+v", err, e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// knownWALDecodeGap names the record shapes decodeWALEntry accepts although
|
||||
// the encoder never produces them (found by FuzzDecodeWALEntryFields;
|
||||
// reported, not fixed here). Recovery already fails closed on an invalid
|
||||
// batch (WALIntegrity), so a decoder-level rejection is not a drop-in
|
||||
// change: it would turn that into a torn-entry stop. Any shape not listed
|
||||
// here fails the fuzz targets.
|
||||
func knownWALDecodeGap(e walEntry) string {
|
||||
switch e.Type {
|
||||
case walEntryWrite:
|
||||
if e.Length == 0 {
|
||||
return "write with no data"
|
||||
}
|
||||
case walEntryWriteBatch:
|
||||
if e.Reserved == 0 || e.Length == 0 {
|
||||
return "batch shape (checked by recovery, not by the decoder)"
|
||||
}
|
||||
case walEntryBarrier:
|
||||
if e.Length != 0 {
|
||||
return "barrier with a non-zero Length"
|
||||
}
|
||||
case walEntryTrim, walEntryPadding:
|
||||
default:
|
||||
return "unknown entry type"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// knownWALEncodeGap names the entries walEntry.encode accepts but whose
|
||||
// bytes do not decode back (found by FuzzWALEntryRoundTrip; no writer
|
||||
// builds them).
|
||||
func knownWALEncodeGap(e walEntry) string {
|
||||
switch e.Type {
|
||||
case walEntryWrite, walEntryWriteBatch, walEntryTrim, walEntryBarrier:
|
||||
return ""
|
||||
case walEntryPadding:
|
||||
if uint32(len(e.Data)) != e.Length {
|
||||
return "padding whose Length differs from its payload"
|
||||
}
|
||||
return ""
|
||||
default:
|
||||
return "unknown entry type"
|
||||
}
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// errWALFull is returned when an Append request would overflow the
|
||||
// circular WAL region. The caller is expected to either wait for
|
||||
// the flusher to advance the tail, or escalate.
|
||||
errWALFull = errors.New("storage: WAL region full")
|
||||
)
|
||||
|
||||
// errWALPwrite marks an append that failed while writing to the file:
|
||||
// part or all of its bytes may be on disk (see WALStore.noteAppendFailure).
|
||||
var errWALPwrite = errors.New("storage: WAL pwrite failed")
|
||||
|
||||
// walWriter appends entries to the circular WAL region of a store
|
||||
// file. It tracks position with monotonically-increasing logical
|
||||
// counters so head==tail unambiguously means empty (used = head-tail).
|
||||
//
|
||||
// The writer performs ONLY pwrite — fsync is the caller's
|
||||
// responsibility, typically batched through a group committer for
|
||||
// throughput.
|
||||
type walWriter struct {
|
||||
mu sync.Mutex
|
||||
fd *os.File
|
||||
walOffset uint64 // absolute file offset where WAL region starts
|
||||
walSize uint64 // size of the WAL region in bytes
|
||||
logicalHead uint64 // monotonic write position
|
||||
logicalTail uint64 // monotonic flush position
|
||||
// durableTail is the tail in the last fsynced superblock. The writer
|
||||
// overwrites only bytes released by it: bytes the on-disk superblock
|
||||
// still declares retained
|
||||
// are never reused, so a torn new record cannot land inside the
|
||||
// persisted [tail, head) and hide a record recovery needs.
|
||||
// durablePending: the bounds were rebuilt by recovery and are not yet
|
||||
// persisted; nothing is reusable until they are.
|
||||
durableTail uint64
|
||||
durablePending bool
|
||||
instr *writeInstrumentation
|
||||
|
||||
// Optional batch pwrite fault seam; nil uses the real file.
|
||||
batchWriteAt func([]byte, int64) (int, error)
|
||||
}
|
||||
|
||||
// newWALWriter constructs a writer over an open file. logicalHead and
|
||||
// logicalTail come from the superblock when reopening; both 0 for a
|
||||
// fresh store.
|
||||
func newWALWriter(fd *os.File, walOffset, walSize, head, tail uint64, instr *writeInstrumentation) *walWriter {
|
||||
return &walWriter{
|
||||
fd: fd,
|
||||
walOffset: walOffset,
|
||||
walSize: walSize,
|
||||
logicalHead: head,
|
||||
logicalTail: tail,
|
||||
durableTail: tail,
|
||||
instr: instr,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *walWriter) physicalPos(logical uint64) uint64 { return logical % w.walSize }
|
||||
|
||||
func (w *walWriter) used() uint64 { return w.logicalHead - w.logicalTail }
|
||||
|
||||
// spaceUsed is what the space checks count: everything from the durable
|
||||
// tail on. Bytes released only in memory are not reusable yet.
|
||||
func (w *walWriter) spaceUsed() uint64 {
|
||||
if w.durablePending || w.durableTail > w.logicalHead {
|
||||
return w.walSize
|
||||
}
|
||||
return w.logicalHead - w.durableTail
|
||||
}
|
||||
|
||||
// append writes one entry and returns the WAL-relative offset where
|
||||
// it was placed. If the entry would straddle the end of the WAL
|
||||
// region, a padding entry is written first and the real entry starts
|
||||
// at physical offset 0.
|
||||
//
|
||||
// Returns errWALFull when even the padding+entry would not fit.
|
||||
func (w *walWriter) append(entry *walEntry) (walRelOffset uint64, err error) {
|
||||
buf, err := entry.encodeWithInstrumentation(w.instr)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("walWriter.append: encode: %w", err)
|
||||
}
|
||||
|
||||
lockStart := time.Now()
|
||||
w.mu.Lock()
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppendLockWait(time.Since(lockStart))
|
||||
}
|
||||
defer w.mu.Unlock()
|
||||
|
||||
entryLen := uint64(len(buf))
|
||||
if entryLen > w.walSize {
|
||||
return 0, fmt.Errorf("%w: entry size %d exceeds WAL size %d", errWALFull, entryLen, w.walSize)
|
||||
}
|
||||
|
||||
physHead := w.physicalPos(w.logicalHead)
|
||||
remaining := w.walSize - physHead
|
||||
if remaining < entryLen {
|
||||
// Pad to end of region and wrap.
|
||||
if w.spaceUsed()+remaining+entryLen > w.walSize {
|
||||
return 0, errWALFull
|
||||
}
|
||||
if err := w.writePadding(remaining, physHead); err != nil {
|
||||
return 0, fmt.Errorf("%w: walWriter.append: padding: %w", errWALPwrite, err)
|
||||
}
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppendWrap(remaining)
|
||||
}
|
||||
w.logicalHead += remaining
|
||||
physHead = 0
|
||||
}
|
||||
if w.spaceUsed()+entryLen > w.walSize {
|
||||
return 0, errWALFull
|
||||
}
|
||||
absOffset := int64(w.walOffset + physHead)
|
||||
writeStart := time.Now()
|
||||
if _, err := w.fd.WriteAt(buf, absOffset); err != nil {
|
||||
return 0, fmt.Errorf("%w: walWriter.append: pwrite at %d: %w", errWALPwrite, absOffset, err)
|
||||
}
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppend(len(buf), time.Since(writeStart))
|
||||
}
|
||||
writeOffset := physHead
|
||||
w.logicalHead += entryLen
|
||||
return writeOffset, nil
|
||||
}
|
||||
|
||||
// appendBatch writes entries under one WAL-writer critical section. Each entry
|
||||
// remains independently encoded/recoverable; the batch only coalesces adjacent
|
||||
// bytes into fewer pwrite calls when the circular WAL layout allows it.
|
||||
func (w *walWriter) appendBatch(entries []walEntry) ([]uint64, error) {
|
||||
if len(entries) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
lengths := make([]uint64, len(entries))
|
||||
for i := range entries {
|
||||
entryLen, err := entries[i].encodedSize()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("walWriter.appendBatch: validate entry %d: %w", i, err)
|
||||
}
|
||||
if uint64(entryLen) > w.walSize {
|
||||
return nil, fmt.Errorf("%w: entry size %d exceeds WAL size %d", errWALFull, entryLen, w.walSize)
|
||||
}
|
||||
lengths[i] = uint64(entryLen)
|
||||
}
|
||||
pendingCapacity := boundedPendingCapacity(lengths)
|
||||
|
||||
lockStart := time.Now()
|
||||
w.mu.Lock()
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppendLockWait(time.Since(lockStart))
|
||||
}
|
||||
defer w.mu.Unlock()
|
||||
|
||||
offsets, finalHead, err := w.planAppendBatchLengths(lengths)
|
||||
if err != nil {
|
||||
return offsets, err
|
||||
}
|
||||
|
||||
localHead := w.logicalHead
|
||||
var pending []byte
|
||||
var pendingStart uint64
|
||||
flushPending := func() error {
|
||||
if len(pending) == 0 {
|
||||
return nil
|
||||
}
|
||||
writeStart := time.Now()
|
||||
writeAt := w.fd.WriteAt
|
||||
if w.batchWriteAt != nil {
|
||||
writeAt = w.batchWriteAt
|
||||
}
|
||||
if _, err := writeAt(pending, int64(w.walOffset+pendingStart)); err != nil {
|
||||
return fmt.Errorf("%w: walWriter.appendBatch: pwrite at %d: %w", errWALPwrite, w.walOffset+pendingStart, err)
|
||||
}
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppend(len(pending), time.Since(writeStart))
|
||||
}
|
||||
pending = nil
|
||||
return nil
|
||||
}
|
||||
appendPendingBytes := func(phys uint64, buf []byte) error {
|
||||
if len(buf) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(pending) == 0 {
|
||||
pendingStart = phys
|
||||
pending = append(pending, buf...)
|
||||
return nil
|
||||
}
|
||||
if pendingStart+uint64(len(pending)) != phys {
|
||||
if err := flushPending(); err != nil {
|
||||
return err
|
||||
}
|
||||
pendingStart = phys
|
||||
}
|
||||
pending = append(pending, buf...)
|
||||
return nil
|
||||
}
|
||||
appendPendingEntry := func(phys uint64, entry *walEntry, entryLen uint64) error {
|
||||
if len(pending) == 0 {
|
||||
pendingStart = phys
|
||||
pending = make([]byte, 0, pendingCapacity)
|
||||
} else if pendingStart+uint64(len(pending)) != phys {
|
||||
if err := flushPending(); err != nil {
|
||||
return err
|
||||
}
|
||||
pendingStart = phys
|
||||
pending = make([]byte, 0, pendingCapacity)
|
||||
}
|
||||
next, err := entry.appendEncoded(pending, w.instr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pending = next
|
||||
return nil
|
||||
}
|
||||
|
||||
for i := range entries {
|
||||
entry := &entries[i]
|
||||
entryLen := lengths[i]
|
||||
physHead := w.physicalPos(localHead)
|
||||
remaining := w.walSize - physHead
|
||||
if remaining < entryLen {
|
||||
padding, err := encodeWALPadding(remaining)
|
||||
if err != nil {
|
||||
return offsets, fmt.Errorf("walWriter.appendBatch: padding: %w", err)
|
||||
}
|
||||
if err := appendPendingBytes(physHead, padding); err != nil {
|
||||
return offsets, err
|
||||
}
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppendWrap(remaining)
|
||||
}
|
||||
localHead += remaining
|
||||
physHead = 0
|
||||
}
|
||||
if err := appendPendingEntry(physHead, entry, entryLen); err != nil {
|
||||
return offsets, err
|
||||
}
|
||||
localHead += entryLen
|
||||
}
|
||||
if err := flushPending(); err != nil {
|
||||
return offsets, err
|
||||
}
|
||||
w.logicalHead = finalHead
|
||||
return offsets, nil
|
||||
}
|
||||
|
||||
func boundedPendingCapacity(lengths []uint64) int {
|
||||
const maxPendingCapacity = 1 << 20
|
||||
total := 0
|
||||
for _, length := range lengths {
|
||||
if length > uint64(maxPendingCapacity) {
|
||||
return maxPendingCapacity
|
||||
}
|
||||
total += int(length)
|
||||
if total >= maxPendingCapacity {
|
||||
return maxPendingCapacity
|
||||
}
|
||||
}
|
||||
if total == 0 {
|
||||
return 0
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func (w *walWriter) planAppendBatchLengths(lengths []uint64) ([]uint64, uint64, error) {
|
||||
localHead := w.logicalHead
|
||||
offsets := make([]uint64, 0, len(lengths))
|
||||
used := func() uint64 {
|
||||
if w.durablePending || w.durableTail > localHead {
|
||||
return w.walSize
|
||||
}
|
||||
return localHead - w.durableTail
|
||||
}
|
||||
for _, entryLen := range lengths {
|
||||
physHead := w.physicalPos(localHead)
|
||||
remaining := w.walSize - physHead
|
||||
if remaining < entryLen {
|
||||
if used()+remaining+entryLen > w.walSize {
|
||||
return offsets, localHead, errWALFull
|
||||
}
|
||||
localHead += remaining
|
||||
physHead = 0
|
||||
}
|
||||
if used()+entryLen > w.walSize {
|
||||
return offsets, localHead, errWALFull
|
||||
}
|
||||
offsets = append(offsets, physHead)
|
||||
localHead += entryLen
|
||||
}
|
||||
return offsets, localHead, nil
|
||||
}
|
||||
|
||||
// writePadding fills [physPos, physPos+size) with a padding entry so
|
||||
// the next write starts at a clean offset. If size is too small for a
|
||||
// real header, just zeros the bytes — the recovery scanner skips
|
||||
// header-too-short tails.
|
||||
func (w *walWriter) writePadding(size, physPos uint64) error {
|
||||
buf, err := encodeWALPadding(size)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(buf) == 0 {
|
||||
return nil
|
||||
}
|
||||
if _, err := w.fd.WriteAt(buf, int64(w.walOffset+physPos)); err != nil {
|
||||
return err
|
||||
}
|
||||
if w.instr != nil {
|
||||
w.instr.recordWALAppendWriteAt(len(buf))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeWALPadding(size uint64) ([]byte, error) {
|
||||
if size < walEntryHeaderSize {
|
||||
return make([]byte, size), nil
|
||||
}
|
||||
buf := make([]byte, size)
|
||||
le := binary.LittleEndian
|
||||
off := 0
|
||||
le.PutUint64(buf[off:], 0) // LSN
|
||||
off += 8
|
||||
le.PutUint64(buf[off:], 0) // Reserved
|
||||
off += 8
|
||||
buf[off] = walEntryPadding
|
||||
off++
|
||||
buf[off] = 0 // Flags
|
||||
off++
|
||||
le.PutUint64(buf[off:], 0) // LBA
|
||||
off += 8
|
||||
paddingDataLen := uint32(size) - uint32(walEntryHeaderSize)
|
||||
le.PutUint32(buf[off:], paddingDataLen)
|
||||
off += 4
|
||||
dataEnd := off + int(paddingDataLen)
|
||||
crc := crc32.ChecksumIEEE(buf[:dataEnd])
|
||||
le.PutUint32(buf[dataEnd:], crc)
|
||||
le.PutUint32(buf[dataEnd+4:], uint32(size))
|
||||
return buf, nil
|
||||
}
|
||||
|
||||
// advanceTail moves the tail forward by (newPhysTail - currentPhysTail
|
||||
// modulo walSize), freeing space. Called by the flusher after entries
|
||||
// have been applied to the extent region.
|
||||
func (w *walWriter) advanceTail(newPhysTail uint64) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
physTail := w.physicalPos(w.logicalTail)
|
||||
var advance uint64
|
||||
if newPhysTail >= physTail {
|
||||
advance = newPhysTail - physTail
|
||||
} else {
|
||||
advance = w.walSize - physTail + newPhysTail
|
||||
}
|
||||
w.logicalTail += advance
|
||||
}
|
||||
|
||||
// advanceTailPastEntry frees WAL bytes through the entry at entryPhys
|
||||
// with entryLen bytes. It advances in logical space, so entries that
|
||||
// end at the same physical offset as the current tail still release a
|
||||
// wrapped span.
|
||||
func (w *walWriter) advanceTailPastEntry(entryPhys, entryLen uint64) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
physTail := w.physicalPos(w.logicalTail)
|
||||
var distanceToEntry uint64
|
||||
if entryPhys >= physTail {
|
||||
distanceToEntry = entryPhys - physTail
|
||||
} else {
|
||||
distanceToEntry = w.walSize - physTail + entryPhys
|
||||
}
|
||||
advance := distanceToEntry + entryLen
|
||||
if advance > w.used() {
|
||||
// The entry is no longer within the live WAL window. This
|
||||
// makes repeated flush/checkpoint cycles idempotent instead
|
||||
// of wrapping around and releasing unflushed entries.
|
||||
return
|
||||
}
|
||||
w.logicalTail += advance
|
||||
}
|
||||
|
||||
// reset truncates the writer to empty. Used after recovery decides
|
||||
// the WAL region should start fresh.
|
||||
func (w *walWriter) reset() {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.logicalHead = 0
|
||||
w.logicalTail = 0
|
||||
w.durableTail = 0
|
||||
w.durablePending = false
|
||||
}
|
||||
|
||||
func (w *walWriter) restoreRecoveredBounds(head, tail uint64) error {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if head < tail || head-tail > w.walSize {
|
||||
return fmt.Errorf(
|
||||
"walWriter: invalid recovered bounds tail=%d head=%d size=%d",
|
||||
tail, head, w.walSize,
|
||||
)
|
||||
}
|
||||
w.logicalHead = head
|
||||
w.logicalTail = tail
|
||||
w.durablePending = true // until the caller persists these bounds
|
||||
return nil
|
||||
}
|
||||
|
||||
// bounds returns head and tail from one snapshot.
|
||||
func (w *walWriter) bounds() (head, tail uint64) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.logicalHead, w.logicalTail
|
||||
}
|
||||
|
||||
// tailPastEntry is the tail that advanceTailPastEntry would set, without
|
||||
// moving it (the caller persists it first).
|
||||
func (w *walWriter) tailPastEntry(entryPhys, entryLen uint64) uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
physTail := w.physicalPos(w.logicalTail)
|
||||
var distanceToEntry uint64
|
||||
if entryPhys >= physTail {
|
||||
distanceToEntry = entryPhys - physTail
|
||||
} else {
|
||||
distanceToEntry = w.walSize - physTail + entryPhys
|
||||
}
|
||||
advance := distanceToEntry + entryLen
|
||||
if advance > w.used() {
|
||||
return w.logicalTail
|
||||
}
|
||||
return w.logicalTail + advance
|
||||
}
|
||||
|
||||
// tailPersisted records that a superblock with WAL tail = tail is fsynced:
|
||||
// the writer's tail moves there (never backward) and the bytes before it
|
||||
// become reusable.
|
||||
func (w *walWriter) tailPersisted(tail uint64) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if tail > w.logicalTail {
|
||||
w.logicalTail = tail
|
||||
}
|
||||
w.durableTail = tail
|
||||
w.durablePending = false
|
||||
}
|
||||
|
||||
func (w *walWriter) head() uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.physicalPos(w.logicalHead)
|
||||
}
|
||||
|
||||
func (w *walWriter) tail() uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.physicalPos(w.logicalTail)
|
||||
}
|
||||
|
||||
func (w *walWriter) logicalHeadValue() uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.logicalHead
|
||||
}
|
||||
|
||||
func (w *walWriter) logicalTailValue() uint64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.logicalTail
|
||||
}
|
||||
|
||||
// fsync forces buffered data to durable storage.
|
||||
func (w *walWriter) fsync() error {
|
||||
sync, err := newDataFileSync(w.fd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return sync()
|
||||
}
|
||||
|
||||
// usedFraction returns the fraction of the WAL region currently in
|
||||
// use, in the range [0, 1]. Used by the admission controller to
|
||||
// decide whether to throttle or block writers.
|
||||
func (w *walWriter) usedFraction() float64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.walSize == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(w.spaceUsed()) / float64(w.walSize)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,8 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -90,45 +89,6 @@ func TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreProductionRefusesLegacyWithoutMutation(t *testing.T) {
|
||||
for _, version := range []uint32{1, 2} {
|
||||
t.Run(fmt.Sprint(version), func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "legacy")
|
||||
opts := WALStoreOptions{}
|
||||
if version == 2 {
|
||||
opts = recordingOptions(&recordingMetadata{}, 2)
|
||||
}
|
||||
s, err := createLegacyWALStoreWithOptions(path, 16, 4096, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r, err := OpenWALStore(path); !errors.Is(err, ErrUnsupportedLegacyFormat) {
|
||||
if r != nil {
|
||||
_ = r.Close()
|
||||
}
|
||||
t.Fatalf("legacy writable open: %v", err)
|
||||
}
|
||||
if r, err := OpenReadOnly(path); !errors.Is(err, ErrUnsupportedLegacyFormat) {
|
||||
if r != nil {
|
||||
_ = r.Close()
|
||||
}
|
||||
t.Fatalf("legacy readonly open: %v", err)
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil || !bytes.Equal(before, after) {
|
||||
t.Fatal("legacy refusal changed bytes", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreProductionCreateOptions(t *testing.T) {
|
||||
s, err := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 64, 4096, WALStoreOptions{ChunkBlocks: 4, WMode: WModeStrict})
|
||||
if err != nil {
|
||||
|
||||
@@ -31,7 +31,7 @@ func TestWALStoreV3AdmissionUsesNativeOccupancy(t *testing.T) {
|
||||
}
|
||||
want := float64(32*4096+70) / float64(64*1024*1024)
|
||||
if got := s.admission.walUsed(); got != want {
|
||||
t.Fatalf("native occupancy=%g want%g; legacy=%g", got, want, s.wal.usedFraction())
|
||||
t.Fatalf("native occupancy=%g want%g", got, want)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -484,14 +484,16 @@ func preparePhase173FileLayoutScratch(t *testing.T, dir string) *phase173FileLay
|
||||
}
|
||||
|
||||
for index := 0; index < phase173ScratchBlocks; index++ {
|
||||
entry := walEntry{
|
||||
LSN: uint64(index + 1),
|
||||
Type: walEntryWrite,
|
||||
LBA: uint64(index),
|
||||
Length: phase173FixedWorkBlockSize,
|
||||
Data: scratch.logicalData,
|
||||
entry := walEntryV3{
|
||||
LSN: uint64(index + 1),
|
||||
Type: walEntryWrite,
|
||||
LBA: uint64(index),
|
||||
Length: phase173FixedWorkBlockSize,
|
||||
Data: scratch.logicalData,
|
||||
Nonce: [16]byte{1},
|
||||
LogicalStart: uint64(index * (walEntryHeaderSizeV3 + phase173FixedWorkBlockSize)),
|
||||
}
|
||||
encoded, err := entry.encodeWithInstrumentation(nil)
|
||||
encoded, err := encodeWALEntryV3(entry, phase173FixedWorkBlockSize, phase173ScratchBlocks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -537,7 +539,7 @@ func (s *phase173FileLayoutScratch) run(t *testing.T, split bool, run int) phase
|
||||
for pass := 0; pass < phase173ScratchPasses; pass++ {
|
||||
for index := 0; index < phase173ScratchBlocks; index++ {
|
||||
offset := s.walBase + int64(index*s.recordSize)
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
header := make([]byte, walEntryHeaderSizeV3)
|
||||
if _, err := walFile.ReadAt(header, offset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -545,7 +547,7 @@ func (s *phase173FileLayoutScratch) run(t *testing.T, split bool, run int) phase
|
||||
if _, err := walFile.ReadAt(full, offset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry, err := decodeWALEntry(full)
|
||||
entry, err := decodeWALEntryV3(full, phase173FixedWorkBlockSize, phase173ScratchBlocks)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// B5 (independent review): a batch append whose pwrite lands every record
|
||||
// and then reports an error left nextLSN and the head unchanged, so the next
|
||||
// write reused the batch's first LSN and offset while the batch's later
|
||||
// record (a higher LSN) stayed on disk past it; after that write's Sync was
|
||||
// acknowledged and the process crashed, recovery served the failed batch's
|
||||
// stale record. A failed append is now sticky for the open store: no further
|
||||
// append (so no LSN reuse) until a reopen. Recovery of the reopen may replay
|
||||
// the failed, never-acknowledged records; an acknowledged write is never
|
||||
// replaced by one of them.
|
||||
func TestWALStoreFailedBatchAppendDoesNotRevertALaterAckedWrite(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 64*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
|
||||
eio := errors.New("injected EIO after the batch bytes were written")
|
||||
s.wal.batchWriteAt = func(b []byte, off int64) (int, error) {
|
||||
n, _ := s.fd.WriteAt(b, off) // the bytes reach the file...
|
||||
return n, eio // ...but the call reports failure
|
||||
}
|
||||
stale := makeBlock(blockSize, 0x5A)
|
||||
if _, err := s.WriteBatch(10, [][]byte{makeBlock(blockSize, 0x5B), stale}); !errors.Is(err, eio) {
|
||||
t.Fatalf("WriteBatch with a failing pwrite: %v", err)
|
||||
}
|
||||
s.wal.batchWriteAt = nil
|
||||
|
||||
// The failed append is sticky: no write reuses its LSNs, nothing is acked.
|
||||
acked := makeBlock(blockSize, 0xAC)
|
||||
if _, err := s.Write(11, acked); !errors.Is(err, ErrAppendFailed) {
|
||||
t.Fatalf("write after a failed append: %v; want the sticky ErrAppendFailed", err)
|
||||
} else {
|
||||
var rf *RecoveryFailure
|
||||
if !errors.As(err, &rf) || rf.Kind != StorageRecoveryFailureSubstrateIO {
|
||||
t.Fatalf("write after a failed append: %v; want a SubstrateIO RecoveryFailure (io_error)", err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); !errors.Is(err, ErrAppendFailed) {
|
||||
t.Fatalf("Sync after a failed append: %v; want ErrAppendFailed", err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
crashed = true
|
||||
|
||||
// Reopen: recovery may replay the failed batch (never acked). A write
|
||||
// acknowledged now must survive the next crash.
|
||||
r := reopenForB5(t, path)
|
||||
lsn, err := r.Write(11, acked)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("acked write of LBA 11 after the reopen got LSN %d", lsn)
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
|
||||
q := reopenForB5(t, path)
|
||||
t.Cleanup(func() { _ = q.Close() })
|
||||
got, err := q.Read(11)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[0] != acked[0] {
|
||||
t.Fatalf("LBA 11 after recovery = %02x; want the acknowledged %02x (the failed batch's stale record is %02x)", got[0], acked[0], stale[0])
|
||||
}
|
||||
}
|
||||
|
||||
func reopenForB5(t *testing.T, path string) *WALStore {
|
||||
t.Helper()
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -2,120 +2,7 @@
|
||||
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
checkpointCrashHelperEnv = "SW_BLOCK_CHECKPOINT_CRASH_HELPER"
|
||||
checkpointCrashPathEnv = "SW_BLOCK_CHECKPOINT_CRASH_PATH"
|
||||
)
|
||||
|
||||
func TestWALStoreCheckpointSIGKILLCrashWindows(t *testing.T) {
|
||||
if crashWindow := os.Getenv(checkpointCrashHelperEnv); crashWindow != "" {
|
||||
runCheckpointCrashHelper(crashWindow, os.Getenv(checkpointCrashPathEnv))
|
||||
return
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
checkpointMin uint64
|
||||
checkpointMax uint64
|
||||
}{
|
||||
{name: "after_extent_sync", checkpointMin: 0, checkpointMax: 0},
|
||||
{name: "after_checkpoint_pwrite", checkpointMin: 0, checkpointMax: 1},
|
||||
{name: "after_checkpoint_sync", checkpointMin: 1, checkpointMax: 1},
|
||||
{name: "after_tail_publish", checkpointMin: 1, checkpointMax: 1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestWALStoreCheckpointSIGKILLCrashWindows$")
|
||||
cmd.Env = append(os.Environ(),
|
||||
checkpointCrashHelperEnv+"="+tt.name,
|
||||
checkpointCrashPathEnv+"="+path,
|
||||
)
|
||||
if output, err := cmd.CombinedOutput(); err == nil {
|
||||
t.Fatalf("crash helper returned normally: %s", output)
|
||||
}
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
checkpoint := reopened.CheckpointLSN()
|
||||
if checkpoint < tt.checkpointMin || checkpoint > tt.checkpointMax {
|
||||
t.Fatalf("checkpoint=%d want in [%d,%d]",
|
||||
checkpoint, tt.checkpointMin, tt.checkpointMax)
|
||||
}
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, makeBlock(4096, 0x7c)) {
|
||||
t.Fatal("acknowledged bytes did not survive checkpoint crash window")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func runCheckpointCrashHelper(window, path string) {
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
if _, err := s.Write(3, makeBlock(4096, 0x7c)); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
kill := func() error {
|
||||
process, err := os.FindProcess(os.Getpid())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return process.Kill()
|
||||
}
|
||||
switch window {
|
||||
case "after_extent_sync":
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return kill()
|
||||
}
|
||||
case "after_checkpoint_pwrite":
|
||||
s.writeSuperblockMetadata = func(data []byte) error {
|
||||
_, err := s.fd.WriteAt(data, 0)
|
||||
return err
|
||||
}
|
||||
s.syncSuperblockMetadata = kill
|
||||
case "after_checkpoint_sync":
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
if err := s.fd.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
return kill()
|
||||
}
|
||||
case "after_tail_publish":
|
||||
default:
|
||||
panic(fmt.Sprintf("unknown checkpoint crash window %q", window))
|
||||
}
|
||||
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := kill(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
panic("SIGKILL returned")
|
||||
}
|
||||
@@ -1,639 +1,9 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
}{
|
||||
{
|
||||
name: "write",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected checkpoint write failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sync",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected checkpoint sync failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
want := makeBlock(4096, 0x71)
|
||||
lsn, err := s.Write(3, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tailBefore := s.wal.logicalTailValue()
|
||||
savedWrite := s.writeSuperblockMetadata
|
||||
savedSync := s.syncSuperblockMetadata
|
||||
tt.inject(s)
|
||||
|
||||
if err := s.flusher.flushOnce(); err == nil {
|
||||
t.Fatal("flush with injected checkpoint failure succeeded")
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after failed metadata publication=%d want 0", got)
|
||||
}
|
||||
if got := s.sb.WALCheckpointLSN; got != 0 {
|
||||
t.Fatalf("superblock checkpoint after failed metadata publication=%d want 0", got)
|
||||
}
|
||||
if got := s.wal.logicalTailValue(); got != tailBefore {
|
||||
t.Fatalf("WAL tail after failed metadata publication=%d want %d", got, tailBefore)
|
||||
}
|
||||
if got := s.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries after failed metadata publication=%d want 1", got)
|
||||
}
|
||||
|
||||
s.writeSuperblockMetadata = savedWrite
|
||||
s.syncSuperblockMetadata = savedSync
|
||||
if tt.name == "sync" {
|
||||
// A failed fsync is sticky (ErrFsyncFailed): no checkpoint
|
||||
// retry on this open store.
|
||||
if err := s.flusher.flushOnce(); !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("retry flush after a failed fsync: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after a refused retry=%d want 0", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatalf("retry flush: %v", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != lsn {
|
||||
t.Fatalf("checkpoint after retry=%d want %d", got, lsn)
|
||||
}
|
||||
if got := s.dm.len(); got != 0 {
|
||||
t.Fatalf("dirty entries after retry=%d want 0", got)
|
||||
}
|
||||
got, err := s.Read(3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("extent bytes changed across checkpoint retry")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckpointPublicationCrashWindowsRemainRecoverable(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
wantFlushError bool
|
||||
wantCheckpointMin uint64
|
||||
wantCheckpointMax uint64
|
||||
}{
|
||||
{
|
||||
name: "checkpoint_write_failed",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected checkpoint write failure")
|
||||
}
|
||||
},
|
||||
wantFlushError: true,
|
||||
wantCheckpointMin: 0,
|
||||
wantCheckpointMax: 0,
|
||||
},
|
||||
{
|
||||
name: "checkpoint_sync_failed",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected checkpoint sync failure")
|
||||
}
|
||||
},
|
||||
wantFlushError: true,
|
||||
wantCheckpointMin: 0,
|
||||
wantCheckpointMax: 1,
|
||||
},
|
||||
{
|
||||
name: "checkpoint_synced",
|
||||
inject: func(*WALStore) {},
|
||||
wantCheckpointMin: 1,
|
||||
wantCheckpointMax: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
want := makeBlock(4096, 0x73)
|
||||
if _, err := s.Write(3, want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tt.inject(s)
|
||||
flushErr := s.flusher.flushOnce()
|
||||
if tt.wantFlushError && flushErr == nil {
|
||||
t.Fatal("flush succeeded despite injected checkpoint failure")
|
||||
}
|
||||
if !tt.wantFlushError && flushErr != nil {
|
||||
t.Fatal(flushErr)
|
||||
}
|
||||
|
||||
// Simulate process loss without the WALStore Close metadata path.
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.fd = nil
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
checkpoint := reopened.CheckpointLSN()
|
||||
if checkpoint < tt.wantCheckpointMin || checkpoint > tt.wantCheckpointMax {
|
||||
t.Fatalf("reopened checkpoint=%d want in [%d,%d]",
|
||||
checkpoint, tt.wantCheckpointMin, tt.wantCheckpointMax)
|
||||
}
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("checkpoint crash window lost the acknowledged block")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherWALSlotMismatchFailsClosed(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(4, makeBlock(4096, 0x44)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walOffset, _, lsn, _, ok := s.dm.get(4)
|
||||
if !ok {
|
||||
t.Fatal("dirty entry missing")
|
||||
}
|
||||
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
absoluteOffset := int64(s.sb.WALOffset + walOffset)
|
||||
if _, err := s.fd.ReadAt(header, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mutated := append([]byte(nil), header...)
|
||||
mutated[0] ^= 0x7f
|
||||
if _, err := s.fd.WriteAt(mutated, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = s.flusher.flushOnce()
|
||||
if err == nil || !strings.Contains(err.Error(), "WAL slot mismatch") {
|
||||
t.Fatalf("flush error=%v want WAL slot mismatch", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after WAL slot mismatch=%d want 0", got)
|
||||
}
|
||||
if got := s.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries after WAL slot mismatch=%d want 1", got)
|
||||
}
|
||||
instr := s.FlusherInstrumentation()
|
||||
if instr.ValidationFailures != 1 || instr.ValidatedRecords != 0 ||
|
||||
instr.CyclesFailed != 1 {
|
||||
t.Fatalf("validation failures/validated/cycles failed=%d/%d/%d want 1/0/1",
|
||||
instr.ValidationFailures, instr.ValidatedRecords, instr.CyclesFailed)
|
||||
}
|
||||
_, _, currentLSN, _, ok := s.dm.get(4)
|
||||
if !ok || currentLSN != lsn {
|
||||
t.Fatalf("dirty entry after mismatch ok=%t lsn=%d want true/%d", ok, currentLSN, lsn)
|
||||
}
|
||||
|
||||
if _, err := s.fd.WriteAt(header, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatalf("flush after restoring WAL header: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherRejectsCorruptOrUnsupportedDirtyRecord(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func([]byte)
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "crc",
|
||||
mutate: func(record []byte) {
|
||||
record[walEntryPrefixSize] ^= 0x7f
|
||||
},
|
||||
wantErr: "CRC mismatch",
|
||||
},
|
||||
{
|
||||
name: "unsupported_type",
|
||||
mutate: func(record []byte) {
|
||||
record[16] = walEntryBarrier
|
||||
},
|
||||
wantErr: "invalid dirty WAL record",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(2, makeBlock(4096, 0x22)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walOffset, _, _, length, ok := s.dm.get(2)
|
||||
if !ok {
|
||||
t.Fatal("dirty entry missing")
|
||||
}
|
||||
record := make([]byte, walEntryHeaderSize+length)
|
||||
absoluteOffset := int64(s.sb.WALOffset + walOffset)
|
||||
if _, err := s.fd.ReadAt(record, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := append([]byte(nil), record...)
|
||||
tt.mutate(record)
|
||||
if _, err := s.fd.WriteAt(record, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
err = s.flusher.flushOnce()
|
||||
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("flush error=%v want substring %q", err, tt.wantErr)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after invalid record=%d want 0", got)
|
||||
}
|
||||
if got := s.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries after invalid record=%d want 1", got)
|
||||
}
|
||||
instr := s.FlusherInstrumentation()
|
||||
if instr.ValidationFailures != 1 || instr.ValidatedRecords != 0 ||
|
||||
instr.CyclesFailed != 1 {
|
||||
t.Fatalf("validation failures/validated/cycles failed=%d/%d/%d want 1/0/1",
|
||||
instr.ValidationFailures, instr.ValidatedRecords, instr.CyclesFailed)
|
||||
}
|
||||
|
||||
if _, err := s.fd.WriteAt(original, absoluteOffset); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatalf("flush after restoring record: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreClosePerformsFinalFlush(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceFlusherForTest(s, time.Hour)
|
||||
|
||||
want := makeBlock(4096, 0xa5)
|
||||
lsn, err := s.Write(7, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if got := reopened.CheckpointLSN(); got != lsn {
|
||||
t.Fatalf("checkpoint after close=%d want final-flushed LSN %d", got, lsn)
|
||||
}
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("final-flushed bytes did not survive reopen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreCloseWaitsForInflightSync(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceFlusherForTest(s, time.Hour)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x61)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
syncStarted := make(chan struct{})
|
||||
releaseSync := make(chan struct{})
|
||||
s.syncCache = func() error {
|
||||
close(syncStarted)
|
||||
<-releaseSync
|
||||
return nil
|
||||
}
|
||||
syncDone := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := s.Sync()
|
||||
syncDone <- err
|
||||
}()
|
||||
<-syncStarted
|
||||
|
||||
closeDone := make(chan error, 1)
|
||||
go func() { closeDone <- s.Close() }()
|
||||
select {
|
||||
case err := <-closeDone:
|
||||
t.Fatalf("Close returned before in-flight Sync completed: %v", err)
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
|
||||
close(releaseSync)
|
||||
if err := <-syncDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := <-closeDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreMutationAPIsRejectAfterClose(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ApplyEntry(1, makeBlock(4096, 0x11), 1); err == nil {
|
||||
t.Fatal("ApplyEntry after Close succeeded")
|
||||
}
|
||||
if err := s.WriteExtentDirect(1, makeBlock(4096, 0x22)); err == nil {
|
||||
t.Fatal("WriteExtentDirect after Close succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreCloseReturnsFinalMetadataFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
inject func(*WALStore)
|
||||
}{
|
||||
{
|
||||
name: "write",
|
||||
inject: func(s *WALStore) {
|
||||
s.writeSuperblockMetadata = func([]byte) error {
|
||||
return errors.New("injected final metadata write failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "sync",
|
||||
inject: func(s *WALStore) {
|
||||
s.syncSuperblockMetadata = func() error {
|
||||
return errors.New("injected final metadata sync failure")
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replaceFlusherForTest(s, time.Hour)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x51)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tt.inject(s)
|
||||
err = s.Close()
|
||||
if err == nil || !strings.Contains(err.Error(), "injected final metadata") {
|
||||
t.Fatalf("Close error=%v want injected final metadata failure", err)
|
||||
}
|
||||
if s.fd != nil {
|
||||
t.Fatal("Close metadata failure left file open")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteExtentDirectSupersedesPriorDirtyWAL(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(5, makeBlock(4096, 0x55)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := makeBlock(4096, 0xb5)
|
||||
if err := s.WriteExtentDirect(5, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, _, _, ok := s.dm.get(5); ok {
|
||||
t.Fatal("direct BASE install left the superseded dirty WAL mapping visible")
|
||||
}
|
||||
got, err := s.Read(5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatal("read after direct BASE install returned superseded WAL bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteExtentDirectSupersededWALDoesNotReappearAfterRestart(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(9, makeBlock(4096, 0x39)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := makeBlock(4096, 0xb9)
|
||||
if err := s.WriteExtentDirect(9, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.AdvanceFrontier(10)
|
||||
if frontier, err := s.Sync(); err != nil || frontier != 10 {
|
||||
t.Fatalf("Sync frontier=%d err=%v want 10/nil", frontier, err)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if _, err := reopened.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := reopened.Read(9)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatal("superseded WAL bytes reappeared after direct BASE restart")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunningFlusherCannotOverwriteDirectBase(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
for iteration := 0; iteration < 50; iteration++ {
|
||||
if _, err := s.Write(10, makeBlock(4096, byte(iteration))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Notify()
|
||||
base := makeBlock(4096, byte(0x80+iteration))
|
||||
if err := s.WriteExtentDirect(10, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
got, err := s.Read(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatalf("iteration %d: running flusher overwrote direct BASE", iteration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlusherSnapshotCannotOverwriteLaterDirectBase(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
s.flusher.Stop()
|
||||
|
||||
old := makeBlock(4096, 0x31)
|
||||
if _, err := s.Write(6, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapshot := s.dm.snapshot()
|
||||
if len(snapshot) != 1 {
|
||||
t.Fatalf("dirty snapshot entries=%d want 1", len(snapshot))
|
||||
}
|
||||
|
||||
base := makeBlock(4096, 0xb6)
|
||||
if err := s.WriteExtentDirect(6, base); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written, err := s.writeExtentIfCurrent(snapshot[0].LBA, snapshot[0].LSN, old)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if written {
|
||||
t.Fatal("stale flusher snapshot overwrote a later direct BASE block")
|
||||
}
|
||||
got, err := s.readFromExtent(6)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, base) {
|
||||
t.Fatal("extent does not contain the direct BASE bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteExtentDirectFailureRetainsDirtyWAL(t *testing.T) {
|
||||
s, err := createLegacyWALStoreForTest(filepath.Join(t.TempDir(), "store.bin"), 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.Write(8, makeBlock(4096, 0x48)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := s.WriteExtentDirect(8, makeBlock(4096, 0xb8)); err == nil {
|
||||
t.Fatal("direct BASE write on closed file succeeded")
|
||||
}
|
||||
if _, _, _, _, ok := s.dm.get(8); !ok {
|
||||
t.Fatal("failed direct BASE write removed the recoverable dirty WAL mapping")
|
||||
}
|
||||
}
|
||||
|
||||
func replaceFlusherForTest(s *WALStore, interval time.Duration) {
|
||||
s.flusher.Stop()
|
||||
s.flusher = newFlusher(s, flusherConfig{Interval: interval})
|
||||
|
||||
@@ -2,7 +2,6 @@ package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -62,26 +61,6 @@ func TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The other legacy offset-0 writers (the checkpoint/recovery superblock
|
||||
// writer and the direct-frontier writer behind SeedChunkFrontier and Sync's
|
||||
// direct frontier) refuse on a v3 store and leave slot A untouched.
|
||||
func TestWALStoreV3LegacySuperblockWritersRefuse(t *testing.T) {
|
||||
s, path := newStoreV3(t, WModeStrict)
|
||||
t.Cleanup(func() { crashRecoveryHardeningStore(t, s) })
|
||||
writeSynced(t, s, 1, 1)
|
||||
rawA := readSlotRawV3(t, path, slotAOffsetV3)
|
||||
junk := bytes.Repeat([]byte{0xEE}, 4096)
|
||||
if err := s.writeSuperblockMetadata(junk); !errors.Is(err, errV3LegacySuperblockWrite) {
|
||||
t.Fatalf("writeSuperblockMetadata: err = %v, want errV3LegacySuperblockWrite", err)
|
||||
}
|
||||
if err := s.syncDirectFrontierMetadata(junk); !errors.Is(err, errV3LegacySuperblockWrite) {
|
||||
t.Fatalf("syncDirectFrontierMetadata: err = %v, want errV3LegacySuperblockWrite", err)
|
||||
}
|
||||
if got := readSlotRawV3(t, path, slotAOffsetV3); !bytes.Equal(got, rawA) {
|
||||
t.Fatal("a refused legacy writer changed descriptor slot A")
|
||||
}
|
||||
}
|
||||
|
||||
func readSlotRawV3(t *testing.T, path string, off int64) []byte {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWALStore_UnknownFormatWithoutFactoryRefused(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := os.OpenFile(path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb.ImplVersion = 77
|
||||
if _, err = f.Seek(0, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = sb.writeTo(f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if x, err := openLegacyWALStoreForTest(path); err == nil {
|
||||
x.Close()
|
||||
t.Fatal("unknown format opened without accepting factory")
|
||||
}
|
||||
if x, err := openLegacyReadOnlyForTest(path); err == nil {
|
||||
x.Close()
|
||||
t.Fatal("unknown format readonly opened without accepting factory")
|
||||
}
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWALStoreRecoverReplaysLegacyRangeTrim(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
trimBlocks = 3
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
|
||||
func() {
|
||||
s, err := createLegacyWALStoreForTest(path, 16, blockSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
|
||||
if err := s.WriteExtentDirect(lba, makeBlock(blockSize, 0xA5)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if stable, err := s.Sync(); err != nil || stable != 0 {
|
||||
t.Fatalf("base Sync stable=%d err=%v want 0,nil", stable, err)
|
||||
}
|
||||
trim := &walEntry{
|
||||
LSN: 1,
|
||||
Type: walEntryTrim,
|
||||
LBA: 3,
|
||||
Length: trimBlocks * blockSize,
|
||||
}
|
||||
if _, err := s.wal.append(trim); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.nextLSN = 2
|
||||
s.walHead = 1
|
||||
s.walTail = 1
|
||||
s.mu.Unlock()
|
||||
if stable, err := s.Sync(); err != nil || stable != 1 {
|
||||
t.Fatalf("Sync stable=%d err=%v want 1,nil", stable, err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
}()
|
||||
|
||||
reader, err := openLegacyReadOnlyForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
|
||||
got, err := reader.Read(lba)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, make([]byte, blockSize)) {
|
||||
t.Fatalf("read-only trim LBA %d did not return zeros", lba)
|
||||
}
|
||||
}
|
||||
if err := reader.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if recovered, err := s.Recover(); err != nil || recovered != 1 {
|
||||
t.Fatalf("Recover=%d err=%v want 1,nil", recovered, err)
|
||||
}
|
||||
|
||||
entries := recoverySnapshotEntriesByLBA(s.dm.snapshot())
|
||||
if len(entries) != trimBlocks {
|
||||
t.Fatalf("trim dirty entries=%d want %d", len(entries), trimBlocks)
|
||||
}
|
||||
wantOffset := entries[3].WALOffset
|
||||
for index, lba := range []uint64{3, 4, 5} {
|
||||
entry := entries[lba]
|
||||
if entry.WALOffset != wantOffset ||
|
||||
entry.DataOffset != uint32(index*blockSize) {
|
||||
t.Fatalf("trim LBA %d identity=(%d,%d) want=(%d,%d)",
|
||||
lba, entry.WALOffset, entry.DataOffset,
|
||||
wantOffset, index*blockSize)
|
||||
}
|
||||
got, err := s.Read(uint32(lba))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, make([]byte, blockSize)) {
|
||||
t.Fatalf("dirty trim LBA %d did not return zeros", lba)
|
||||
}
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.dm.len(); got != 0 {
|
||||
t.Fatalf("trim dirty entries after flush=%d want 0", got)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 1 {
|
||||
t.Fatalf("trim checkpoint=%d want 1", got)
|
||||
}
|
||||
for lba := uint32(3); lba < 3+trimBlocks; lba++ {
|
||||
got, err := s.readFromExtent(lba)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(got, make([]byte, blockSize)) {
|
||||
t.Fatalf("flushed trim LBA %d did not zero extent", lba)
|
||||
}
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,9 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Issue #51, walstore: pure
|
||||
// detection. A WAL hole followed by valid records is logged, counted and
|
||||
// reported as the typed warning wal_hole_suspected; nothing about what is
|
||||
// replayed, where replay stops, or whether the volume opens changes.
|
||||
|
||||
// writeSyncedEntries writes one block to each of lbas (in order), syncs,
|
||||
// and returns the store with auto-flush off (nothing checkpointed) and
|
||||
// each LBA's WAL offset.
|
||||
func writeSyncedEntries(t *testing.T, lbas []uint32) (*WALStore, string, map[uint64]uint64) {
|
||||
t.Helper()
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, blockSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for i, lba := range lbas {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0xB0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, path, walOffsetsByLBA(s)
|
||||
}
|
||||
|
||||
func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
|
||||
offs := map[uint64]uint64{}
|
||||
for _, e := range s.dm.snapshot() {
|
||||
@@ -42,34 +12,6 @@ func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
|
||||
return offs
|
||||
}
|
||||
|
||||
// flipDataByte corrupts one payload byte of the entry at walOffset without
|
||||
// fixing its CRC.
|
||||
func flipDataByte(t *testing.T, s *WALStore, walOffset uint64) {
|
||||
t.Helper()
|
||||
off := int64(s.sb.WALOffset+walOffset) + int64(walEntryHeaderSize) + 100
|
||||
b := make([]byte, 1)
|
||||
if _, err := s.fd.ReadAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b[0] ^= 0xFF
|
||||
if _, err := s.fd.WriteAt(b, off); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func reopenAfterCrash(t *testing.T, s *WALStore, path string) (*WALStore, uint64, error) {
|
||||
t.Helper()
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
lsn, rerr := r.Recover()
|
||||
return r, lsn, rerr
|
||||
}
|
||||
|
||||
func holeWarning(s *WALStore) bool {
|
||||
for _, w := range s.RecoveryWarnings() {
|
||||
if strings.HasPrefix(w, WarningWALHoleSuspected+":") {
|
||||
@@ -78,131 +20,3 @@ func holeWarning(s *WALStore) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// (a) A corrupted mid-history synced record: recovery opens as before
|
||||
// (this range stops at it), and warns (typed, counted).
|
||||
func TestWALStoreRecoverWarnsOnMidHistoryHole(t *testing.T) {
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
|
||||
flipDataByte(t, s, offs[1])
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 1 {
|
||||
t.Fatalf("Recover after a mid-history hole = %d, %v; want 1, nil (no outage)", lsn, err)
|
||||
}
|
||||
if !holeWarning(r) || r.HolesSuspected() != 1 {
|
||||
t.Fatalf("warnings %v holes %d; want %s, counted once", r.RecoveryWarnings(), r.HolesSuspected(), WarningWALHoleSuspected)
|
||||
}
|
||||
if got := r.dm.len(); got != 1 {
|
||||
t.Fatalf("dirty entries replayed = %d; want 1 (nothing after the hole)", got)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0xB0))
|
||||
}
|
||||
|
||||
// (b) A power loss with an unsynced, out-of-order tail: an earlier
|
||||
// unsynced record torn, a later one written back. No outage: recovery
|
||||
// succeeds with the synced prefix intact.
|
||||
func TestWALStoreRecoverSurvivesAnOutOfOrderUnsyncedTail(t *testing.T) {
|
||||
s, path, _ := writeSyncedEntries(t, []uint32{0, 1}) // synced
|
||||
for i, lba := range []uint32{2, 3} { // unsynced
|
||||
if _, err := s.Write(lba, makeBlock(4096, byte(0xC0+i))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
offs := walOffsetsByLBA(s)
|
||||
flipDataByte(t, s, offs[2]) // LBA 2 torn, LBA 3 reached the disk
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 2 {
|
||||
t.Fatalf("Recover after an out-of-order unsynced tail = %d, %v; want 2, nil", lsn, err)
|
||||
}
|
||||
for i, lba := range []uint32{0, 1} {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
|
||||
}
|
||||
}
|
||||
|
||||
// A torn tail (nothing valid after it) recovers without a warning.
|
||||
func TestWALStoreRecoverKeepsATornTail(t *testing.T) {
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2, 3})
|
||||
flipDataByte(t, s, offs[3])
|
||||
r, lsn, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil || lsn != 3 || holeWarning(r) {
|
||||
t.Fatalf("Recover with a torn tail = %d, %v, warnings %v; want 3, nil, none", lsn, err, r.RecoveryWarnings())
|
||||
}
|
||||
for i, lba := range []uint32{0, 1, 2} {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(4096, byte(0xB0+i)))
|
||||
}
|
||||
}
|
||||
|
||||
// (c) A hole across wrapped ranges (the older record at the high end
|
||||
// corrupted, the newer batch wrapped to offset 0) is no outage. Detection
|
||||
// here is per range: when the newer entries were scanned first there is
|
||||
// nothing "later" left to find, and telling generations apart across
|
||||
// ranges (like not replaying past such a hole) is the post-M4 watermark
|
||||
// work.
|
||||
func TestWALStoreRecoverWrappedHoleIsNoOutage(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 3; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(20, makeBlock(blockSize, 0xA4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(24, [][]byte{makeBlock(blockSize, 0xB5), makeBlock(blockSize, 0xB6)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
offs := walOffsetsByLBA(s)
|
||||
flipDataByte(t, s, offs[20])
|
||||
r, _, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil {
|
||||
t.Fatalf("Recover = %v; want no outage", err)
|
||||
}
|
||||
_ = r
|
||||
}
|
||||
|
||||
// Review finding: a damaged STALE record in a released range (below the
|
||||
// checkpoint, outside the retained window) must not cost retained data.
|
||||
// Layout: checkpoint 2, persisted tail at S, head at 3S; LSN 1 (released)
|
||||
// at 0 damaged, LSN 2 checkpointed at S, LSN 3 synced and unflushed at 2S.
|
||||
// LSN 3 must be replayed with its exact bytes.
|
||||
func TestWALStoreRecoverStaleReleasedGarbageKeepsRetainedData(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
s, path, offs := writeSyncedEntries(t, []uint32{0, 1, 2})
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
if offs[0] != 0 || offs[1] != S || offs[2] != 2*S {
|
||||
t.Fatalf("offsets %v; want 0, S, 2S", offs)
|
||||
}
|
||||
sb := *s.sb
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 2, S, 3*S
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
flipDataByte(t, s, offs[0]) // the released LSN 1
|
||||
r, _, err := reopenAfterCrash(t, s, path)
|
||||
if err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 2, makeBlock(blockSize, 0xB2)) // LSN 3, exact bytes
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWALStore_MultiBlockProfile_RecordCountReduction(t *testing.T) {
|
||||
const (
|
||||
numBlocks = 4096
|
||||
blockSize = 4096
|
||||
batches = 128
|
||||
blocksPerBatch = 16
|
||||
)
|
||||
|
||||
type profile struct {
|
||||
instr WriteInstrumentationStatus
|
||||
}
|
||||
|
||||
run := func(t *testing.T, multiblock bool) profile {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, numBlocks, blockSize)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateWALStore: %v", err)
|
||||
}
|
||||
defer s.Close()
|
||||
s.flusher.Stop()
|
||||
s.enableMultiBlockRecordsForTest(multiblock)
|
||||
|
||||
var lastBlocks [][]byte
|
||||
var lastStart uint32
|
||||
for b := 0; b < batches; b++ {
|
||||
start := uint32(b * blocksPerBatch)
|
||||
blocks := make([][]byte, blocksPerBatch)
|
||||
for i := range blocks {
|
||||
blocks[i] = makeBlock(blockSize, byte((b+i)%251+1))
|
||||
}
|
||||
if _, err := s.WriteBatch(start, blocks); err != nil {
|
||||
t.Fatalf("WriteBatch multiblock=%v batch=%d: %v", multiblock, b, err)
|
||||
}
|
||||
lastBlocks = blocks
|
||||
lastStart = start
|
||||
}
|
||||
for i, want := range lastBlocks {
|
||||
got, err := s.Read(lastStart + uint32(i))
|
||||
if err != nil {
|
||||
t.Fatalf("Read multiblock=%v block=%d: %v", multiblock, i, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("Read multiblock=%v block=%d mismatch", multiblock, i)
|
||||
}
|
||||
}
|
||||
return profile{instr: s.WriteInstrumentation()}
|
||||
}
|
||||
|
||||
single := run(t, false)
|
||||
multi := run(t, true)
|
||||
|
||||
t.Logf("phase149_single_block_wal_encode_ops=%d", single.instr.WALEncodeOps)
|
||||
t.Logf("phase149_multiblock_wal_encode_ops=%d", multi.instr.WALEncodeOps)
|
||||
t.Logf("phase149_single_block_wal_append_ops=%d", single.instr.WALAppendOps)
|
||||
t.Logf("phase149_multiblock_wal_append_ops=%d", multi.instr.WALAppendOps)
|
||||
t.Logf("phase149_single_block_wal_writeat_calls=%d", single.instr.WALAppendWriteAtCalls)
|
||||
t.Logf("phase149_multiblock_wal_writeat_calls=%d", multi.instr.WALAppendWriteAtCalls)
|
||||
|
||||
if single.instr.WALEncodeOps == 0 || multi.instr.WALEncodeOps == 0 {
|
||||
t.Fatalf("missing encode ops: single=%d multi=%d", single.instr.WALEncodeOps, multi.instr.WALEncodeOps)
|
||||
}
|
||||
if multi.instr.WALEncodeOps >= single.instr.WALEncodeOps {
|
||||
t.Fatalf("multi-block encode ops=%d, want < single=%d", multi.instr.WALEncodeOps, single.instr.WALEncodeOps)
|
||||
}
|
||||
expectedMulti := uint64(batches)
|
||||
if multi.instr.WALEncodeOps != expectedMulti {
|
||||
t.Fatalf("multi-block encode ops=%d want %d", multi.instr.WALEncodeOps, expectedMulti)
|
||||
}
|
||||
expectedSingle := uint64(batches * blocksPerBatch)
|
||||
if single.instr.WALEncodeOps != expectedSingle {
|
||||
t.Fatalf("single-block encode ops=%d want %d", single.instr.WALEncodeOps, expectedSingle)
|
||||
}
|
||||
}
|
||||
@@ -1,381 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestWALMultiBlock_EncodeDecode(t *testing.T) {
|
||||
block0 := makeBlock(4096, 0xA0)
|
||||
block1 := makeBlock(4096, 0xB0)
|
||||
data := append(append([]byte{}, block0...), block1...)
|
||||
|
||||
entry := walEntry{
|
||||
LSN: 10,
|
||||
Reserved: 2,
|
||||
Type: walEntryWriteBatch,
|
||||
LBA: 7,
|
||||
Length: uint32(len(data)),
|
||||
Data: data,
|
||||
}
|
||||
encoded, err := entry.encode()
|
||||
if err != nil {
|
||||
t.Fatalf("encode: %v", err)
|
||||
}
|
||||
decoded, err := decodeWALEntry(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if decoded.Type != walEntryWriteBatch {
|
||||
t.Fatalf("type=%d want %d", decoded.Type, walEntryWriteBatch)
|
||||
}
|
||||
if decoded.LSN != 10 || decoded.Reserved != 2 || decoded.LBA != 7 {
|
||||
t.Fatalf("identity mismatch: %+v", decoded)
|
||||
}
|
||||
if !bytes.Equal(decoded.Data[:4096], block0) || !bytes.Equal(decoded.Data[4096:], block1) {
|
||||
t.Fatal("decoded batch payload mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_MultiBlockFeatureDisabledByDefault(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
s.flusher.Stop()
|
||||
|
||||
if _, err := s.WriteBatch(2, [][]byte{
|
||||
makeBlock(4096, 0xA1),
|
||||
makeBlock(4096, 0xA2),
|
||||
makeBlock(4096, 0xA3),
|
||||
}); err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
entries := s.dm.snapshot()
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("dirty entries=%d want 3", len(entries))
|
||||
}
|
||||
seenOffsets := map[uint64]bool{}
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
for _, e := range entries {
|
||||
seenOffsets[e.WALOffset] = true
|
||||
if e.DataOffset != 0 {
|
||||
t.Fatalf("default dirty data offset=%d want 0", e.DataOffset)
|
||||
}
|
||||
if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset+e.WALOffset)); err != nil {
|
||||
t.Fatalf("read header: %v", err)
|
||||
}
|
||||
if typ := header[16]; typ != walEntryWrite {
|
||||
t.Fatalf("default entry type=%d want walEntryWrite", typ)
|
||||
}
|
||||
}
|
||||
if len(seenOffsets) != 3 {
|
||||
t.Fatalf("default WriteBatch offsets=%d want 3 independent records", len(seenOffsets))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_MultiBlockDirtyRead(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
s.flusher.Stop()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
|
||||
blocks := [][]byte{
|
||||
makeBlock(4096, 0xB1),
|
||||
makeBlock(4096, 0xB2),
|
||||
makeBlock(4096, 0xB3),
|
||||
}
|
||||
lsns, err := s.WriteBatch(4, blocks)
|
||||
if err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
for i, lsn := range lsns {
|
||||
if want := uint64(i + 1); lsn != want {
|
||||
t.Fatalf("lsn[%d]=%d want %d", i, lsn, want)
|
||||
}
|
||||
}
|
||||
entries := s.dm.snapshot()
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("dirty entries=%d want 3", len(entries))
|
||||
}
|
||||
offset := entries[0].WALOffset
|
||||
for _, e := range entries {
|
||||
if e.WALOffset != offset {
|
||||
t.Fatalf("batch dirty offset changed: %d vs %d", e.WALOffset, offset)
|
||||
}
|
||||
}
|
||||
for i, want := range blocks {
|
||||
got, err := s.Read(uint32(4 + i))
|
||||
if err != nil {
|
||||
t.Fatalf("Read %d: %v", i, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("Read %d returned wrong block", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_MultiBlockRecoverSplitsPerBlock(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
func() {
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.Stop()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(1, [][]byte{
|
||||
makeBlock(4096, 0xC1),
|
||||
makeBlock(4096, 0xC2),
|
||||
makeBlock(4096, 0xC3),
|
||||
}); err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
if stable, err := s.Sync(); err != nil || stable != 3 {
|
||||
t.Fatalf("Sync stable=%d err=%v, want stable=3", stable, err)
|
||||
}
|
||||
s.committer.Stop()
|
||||
_ = s.fd.Close()
|
||||
}()
|
||||
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if recovered, err := s.Recover(); err != nil || recovered != 3 {
|
||||
t.Fatalf("Recover=%d err=%v, want 3", recovered, err)
|
||||
}
|
||||
for i, marker := range []byte{0xC1, 0xC2, 0xC3} {
|
||||
got, err := s.Read(uint32(1 + i))
|
||||
if err != nil {
|
||||
t.Fatalf("Read %d: %v", i, err)
|
||||
}
|
||||
if got[0] != marker {
|
||||
t.Fatalf("Read %d marker=%02x want %02x", i, got[0], marker)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_DisableAutoFlushForRecoveryTestPreservesReplayAfterCrash(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
blocks := [][]byte{
|
||||
makeBlock(4096, 0xD1),
|
||||
makeBlock(4096, 0xD2),
|
||||
makeBlock(4096, 0xD3),
|
||||
makeBlock(4096, 0xD4),
|
||||
}
|
||||
|
||||
func() {
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(2, blocks); err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
if stable, err := s.Sync(); err != nil || stable != 4 {
|
||||
t.Fatalf("Sync stable=%d err=%v, want stable=4", stable, err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint=%d want 0 before crash", got)
|
||||
}
|
||||
s.committer.Stop()
|
||||
if err := s.fd.Close(); err != nil {
|
||||
t.Fatalf("close fd: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
if recovered, err := s.Recover(); err != nil || recovered != 4 {
|
||||
t.Fatalf("Recover=%d err=%v, want 4", recovered, err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 0 {
|
||||
t.Fatalf("checkpoint after recovery=%d want 0", got)
|
||||
}
|
||||
for i, want := range blocks {
|
||||
got, err := s.Read(uint32(2 + i))
|
||||
if err != nil {
|
||||
t.Fatalf("Read %d: %v", i, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("Read %d returned wrong block", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_MultiBlockRecoveryHeadLSNUsesRecoveredFrontier(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
blocks := [][]byte{
|
||||
makeBlock(4096, 0xE1),
|
||||
makeBlock(4096, 0xE2),
|
||||
makeBlock(4096, 0xE3),
|
||||
makeBlock(4096, 0xE4),
|
||||
}
|
||||
var persistedWALHeadBytes uint64
|
||||
|
||||
func() {
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(2, blocks); err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
if stable, err := s.Sync(); err != nil || stable != 4 {
|
||||
t.Fatalf("Sync stable=%d err=%v, want stable=4", stable, err)
|
||||
}
|
||||
_, _, headLSN := s.Boundaries()
|
||||
if headLSN != 4 {
|
||||
t.Fatalf("pre-close HeadLSN=%d want 4", headLSN)
|
||||
}
|
||||
persistedWALHeadBytes = s.wal.logicalHeadValue()
|
||||
if persistedWALHeadBytes <= headLSN {
|
||||
t.Fatalf("test setup did not create distinct WAL byte head: walHeadBytes=%d headLSN=%d", persistedWALHeadBytes, headLSN)
|
||||
}
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
s, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
recovered, err := s.Recover()
|
||||
if err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
if recovered != 4 {
|
||||
t.Fatalf("Recover=%d want 4", recovered)
|
||||
}
|
||||
_, _, headLSN := s.Boundaries()
|
||||
if headLSN != recovered {
|
||||
t.Fatalf("HeadLSN=%d want recovered frontier %d, not WAL byte offset %d", headLSN, recovered, persistedWALHeadBytes)
|
||||
}
|
||||
if next := s.NextLSN(); next != recovered+1 {
|
||||
t.Fatalf("NextLSN=%d want %d", next, recovered+1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_MultiBlockFlusherSplitsPerBlock(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
|
||||
blocks := [][]byte{
|
||||
makeBlock(4096, 0xD1),
|
||||
makeBlock(4096, 0xD2),
|
||||
makeBlock(4096, 0xD3),
|
||||
}
|
||||
if _, err := s.WriteBatch(6, blocks); err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
if stable, err := s.Sync(); err != nil || stable != 3 {
|
||||
t.Fatalf("Sync stable=%d err=%v, want stable=3", stable, err)
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if s.CheckpointLSN() >= 3 && s.dm.len() == 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if s.CheckpointLSN() < 3 {
|
||||
t.Fatalf("checkpoint=%d want >=3", s.CheckpointLSN())
|
||||
}
|
||||
if got := s.dm.len(); got != 0 {
|
||||
t.Fatalf("dirty map len=%d want 0 after flush", got)
|
||||
}
|
||||
for i, want := range blocks {
|
||||
got, err := s.readFromExtent(uint32(6 + i))
|
||||
if err != nil {
|
||||
t.Fatalf("read extent %d: %v", i, err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatalf("extent block %d mismatch", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStore_MultiBlockScanLBAsSplitsPerLSN(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, 4096)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
s.flusher.Stop()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
|
||||
if _, err := s.WriteBatch(8, [][]byte{
|
||||
makeBlock(4096, 0xE1),
|
||||
makeBlock(4096, 0xE2),
|
||||
makeBlock(4096, 0xE3),
|
||||
}); err != nil {
|
||||
t.Fatalf("WriteBatch: %v", err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatalf("Sync: %v", err)
|
||||
}
|
||||
var got []RecoveryEntry
|
||||
if err := s.ScanLBAs(1, func(e RecoveryEntry) error {
|
||||
dup := append([]byte(nil), e.Data...)
|
||||
e.Data = dup
|
||||
got = append(got, e)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatalf("ScanLBAs: %v", err)
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("entries=%d want 3", len(got))
|
||||
}
|
||||
for i, e := range got {
|
||||
if wantLSN := uint64(i + 1); e.LSN != wantLSN {
|
||||
t.Fatalf("entry %d LSN=%d want %d", i, e.LSN, wantLSN)
|
||||
}
|
||||
if wantLBA := uint32(8 + i); e.LBA != wantLBA {
|
||||
t.Fatalf("entry %d LBA=%d want %d", i, e.LBA, wantLBA)
|
||||
}
|
||||
if wantMarker := byte(0xE1 + i); e.Data[0] != wantMarker {
|
||||
t.Fatalf("entry %d marker=%02x want %02x", i, e.Data[0], wantMarker)
|
||||
}
|
||||
}
|
||||
|
||||
header := make([]byte, walEntryHeaderSize)
|
||||
entries := s.dm.snapshot()
|
||||
if len(entries) == 0 {
|
||||
t.Fatal("dirty map empty")
|
||||
}
|
||||
if _, err := s.fd.ReadAt(header, int64(s.sb.WALOffset+entries[0].WALOffset)); err != nil {
|
||||
t.Fatalf("read header: %v", err)
|
||||
}
|
||||
if gotType := header[16]; gotType != walEntryWriteBatch {
|
||||
t.Fatalf("entry type=%d want walEntryWriteBatch", gotType)
|
||||
}
|
||||
if count := binary.LittleEndian.Uint64(header[8:16]); count != 3 {
|
||||
t.Fatalf("batch count=%d want 3", count)
|
||||
}
|
||||
}
|
||||
@@ -1,482 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The WAL writer may only overwrite bytes that the PERSISTED superblock tail
|
||||
// has released (the torn-wrap finding). Otherwise a torn new record can
|
||||
// land inside the persisted
|
||||
// [tail, head) and stop recovery's scan before a synced record behind it.
|
||||
|
||||
func diskSuperblockForTest(t *testing.T, path string) superblock {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sb
|
||||
}
|
||||
|
||||
// The S3 trace, deterministic: LSN 2 is appended (and synced) while the
|
||||
// flush of LSN 1 runs, so the checkpoint covers LSN 1 and the persisted head
|
||||
// covers LSN 2. Synced LSN 3..5 follow; an unsynced LSN 6 wraps to offset 0
|
||||
// over the released LSN 1. The crash leaves LSN 6 torn and its end padding
|
||||
// not on disk (both unsynced pages: a plain crash, no corruption). Synced
|
||||
// LSN 2..5 must all be recovered.
|
||||
func TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.flusher.afterSnapshotForTest = func() {
|
||||
s.flusher.afterSnapshotForTest = nil
|
||||
if _, err := s.Write(1, makeBlock(blockSize, 0x11)); err != nil { // LSN 2, not in this flush
|
||||
t.Error(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sb := diskSuperblockForTest(t, path); sb.WALCheckpointLSN != 1 || sb.WALHead != 2*S {
|
||||
t.Fatalf("persisted ckpt=%d head=%d; want the flush of LSN 1 to cover LSN 2 in its head (2S=%d)", sb.WALCheckpointLSN, sb.WALHead, 2*S)
|
||||
}
|
||||
for lba := uint32(2); lba <= 4; lba++ { // LSN 3..5, synced
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps
|
||||
t.Fatal(err)
|
||||
}
|
||||
ents := recoverySnapshotEntriesByLBA(s.dm.snapshot())
|
||||
if ents[5].WALOffset != 0 || ents[1].WALOffset != S {
|
||||
t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset)
|
||||
}
|
||||
walOff := s.sb.WALOffset
|
||||
if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
for lba := uint32(1); lba <= 4; lba++ {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba)))
|
||||
}
|
||||
}
|
||||
|
||||
// A flush persists the tail it releases: the on-disk tail equals the
|
||||
// writer's tail after every checkpoint, and head/tail come from one snapshot.
|
||||
func TestWALStoreFlushPersistsTheReleasedTail(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
for round := 0; round < 3; round++ {
|
||||
for lba := uint32(0); lba < 2; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x20+round))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb := diskSuperblockForTest(t, path)
|
||||
if tail, head := s.wal.logicalTailValue(), s.wal.logicalHeadValue(); sb.WALTail != tail || sb.WALHead != head {
|
||||
t.Fatalf("round %d: persisted tail=%d head=%d, writer tail=%d head=%d; the writer may reuse bytes the persisted tail still retains", round, sb.WALTail, sb.WALHead, tail, head)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery that moves the writer's bounds persists them before any append,
|
||||
// so the writer never reuses bytes the on-disk superblock still declares
|
||||
// retained.
|
||||
func TestWALStoreRecoverPersistsTheRecoveredBounds(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// the superblock as an older flush left it: ckpt 1, tail before LSN 1
|
||||
sb := *s.sb
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, uint64(walEntryHeaderSize+blockSize)
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk := diskSuperblockForTest(t, path)
|
||||
if tail, head := r.wal.logicalTailValue(), r.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != head {
|
||||
t.Fatalf("after Recover: persisted tail=%d head=%d, writer tail=%d head=%d; want the recovered bounds persisted", disk.WALTail, disk.WALHead, tail, head)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 1, makeBlock(blockSize, 0x31))
|
||||
}
|
||||
|
||||
// The writer's space check uses the durable tail: an in-memory release that
|
||||
// is not yet persisted does not make its bytes reusable.
|
||||
func TestWALWriterReuseIsBoundedByTheDurableTail(t *testing.T) {
|
||||
f, err := os.CreateTemp(t.TempDir(), "wal")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
const walSize = 4096
|
||||
entry := func() *walEntry {
|
||||
return &walEntry{LSN: 1, Type: walEntryWrite, LBA: 0, Length: 64, Data: make([]byte, 64)}
|
||||
}
|
||||
size, err := entry().encodedSize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
n := uint64(walSize) / uint64(size)
|
||||
w := newWALWriter(f, 0, walSize, 0, 0, nil)
|
||||
for i := uint64(0); i < n; i++ {
|
||||
if _, err := w.append(entry()); err != nil {
|
||||
t.Fatalf("append %d of %d: %v", i, n, err)
|
||||
}
|
||||
}
|
||||
w.advanceTailPastEntry(0, uint64(size)) // released in memory only
|
||||
if _, err := w.append(entry()); !errors.Is(err, errWALFull) {
|
||||
t.Fatalf("append into bytes released only in memory: err=%v; want errWALFull until the tail is persisted", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A full flush persists head == tail (an empty WAL at that position). Sync
|
||||
// does not persist the head, so synced appends follow it there; recovery must
|
||||
// scan from the persisted position, not from offset 0 (a torn unsynced
|
||||
// record wrapped to 0 must not hide the synced run).
|
||||
func TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x10)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for lba := uint32(1); lba <= 4; lba++ { // LSN 2..5, synced
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(5, makeBlock(blockSize, 0x66)); err != nil { // LSN 6, unsynced, wraps
|
||||
t.Fatal(err)
|
||||
}
|
||||
ents := recoverySnapshotEntriesByLBA(s.dm.snapshot())
|
||||
if ents[5].WALOffset != 0 || ents[1].WALOffset != S {
|
||||
t.Fatalf("layout: LSN 6 at %d, LSN 2 at %d; want 0 and S", ents[5].WALOffset, ents[1].WALOffset)
|
||||
}
|
||||
walOff := s.sb.WALOffset
|
||||
if _, err := s.fd.WriteAt(make([]byte, walSize-5*S), int64(walOff+5*S)); err != nil { // padding not on disk
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(make([]byte, blockSize/2), int64(walOff+S-blockSize/2)); err != nil { // LSN 6 torn
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
for lba := uint32(1); lba <= 4; lba++ {
|
||||
assertRecoveryHardeningBlock(t, r, lba, makeBlock(blockSize, byte(0x10+lba)))
|
||||
}
|
||||
}
|
||||
|
||||
// Review of #159: the batch planner (with a padding wrap) counts from the
|
||||
// durable tail too: refused while the release is only in memory or the
|
||||
// bounds are recovery-pending, accepted once the tail is persisted.
|
||||
func TestWALWriterBatchReuseIsBoundedByTheDurableTail(t *testing.T) {
|
||||
const walSize = 4096
|
||||
mk := func(lsn uint64) walEntry {
|
||||
return walEntry{LSN: lsn, Type: walEntryWrite, LBA: lsn, Length: 64, Data: make([]byte, 64)}
|
||||
}
|
||||
e0 := mk(0)
|
||||
size, err := e0.encodedSize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sz := uint64(size)
|
||||
n := uint64(walSize) / sz // the last walSize%sz bytes force a padding wrap
|
||||
fill := func(t *testing.T) (*walWriter, *os.File) {
|
||||
f, err := os.CreateTemp(t.TempDir(), "wal")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = f.Close() })
|
||||
if err := f.Truncate(walSize); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := newWALWriter(f, 0, walSize, 0, 0, nil)
|
||||
for i := uint64(0); i < n; i++ {
|
||||
e := mk(i + 1)
|
||||
if _, err := w.append(&e); err != nil {
|
||||
t.Fatalf("fill %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
return w, f
|
||||
}
|
||||
batch := func() []walEntry { return []walEntry{mk(n + 1), mk(n + 2)} }
|
||||
refused := func(t *testing.T, w *walWriter, f *os.File, why string) {
|
||||
t.Helper()
|
||||
head := w.logicalHeadValue()
|
||||
tailBytes := make([]byte, walSize-n*sz)
|
||||
if _, err := f.ReadAt(tailBytes, int64(n*sz)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.appendBatch(batch()); !errors.Is(err, errWALFull) {
|
||||
t.Fatalf("%s: appendBatch err=%v; want errWALFull", why, err)
|
||||
}
|
||||
after := make([]byte, len(tailBytes))
|
||||
if _, err := f.ReadAt(after, int64(n*sz)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.logicalHeadValue() != head || !bytes.Equal(after, tailBytes) {
|
||||
t.Fatalf("%s: a refused batch moved the head or wrote padding", why)
|
||||
}
|
||||
}
|
||||
accepted := func(t *testing.T, w *walWriter) {
|
||||
t.Helper()
|
||||
offs, err := w.appendBatch(batch())
|
||||
if err != nil {
|
||||
t.Fatalf("after the tail is persisted: appendBatch: %v", err)
|
||||
}
|
||||
if len(offs) != 2 || offs[0] != 0 || offs[1] != sz {
|
||||
t.Fatalf("offsets %v; want the batch wrapped to [0 %d]", offs, sz)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("released in memory only", func(t *testing.T) {
|
||||
w, f := fill(t)
|
||||
w.advanceTailPastEntry(0, 2*sz)
|
||||
refused(t, w, f, "in-memory release")
|
||||
w.tailPersisted(2 * sz)
|
||||
accepted(t, w)
|
||||
})
|
||||
t.Run("recovered bounds pending", func(t *testing.T) {
|
||||
w, f := fill(t)
|
||||
w.tailPersisted(2 * sz) // the space is free on disk; only the pending flag refuses it
|
||||
if err := w.restoreRecoveredBounds(n*sz, 2*sz); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refused(t, w, f, "durablePending")
|
||||
single := mk(n + 1)
|
||||
if _, err := w.append(&single); !errors.Is(err, errWALFull) {
|
||||
t.Fatalf("durablePending: append err=%v; want errWALFull", err)
|
||||
}
|
||||
w.tailPersisted(2 * sz)
|
||||
accepted(t, w)
|
||||
})
|
||||
}
|
||||
|
||||
// Review of #159: when Recover cannot persist the rebuilt bounds (the
|
||||
// superblock write or its fsync fails), it fails, admits no append, and a
|
||||
// same-instance retry persists them; later writes survive a reopen exactly.
|
||||
func TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
S := uint64(walEntryHeaderSize + blockSize)
|
||||
errInjected := errors.New("injected superblock failure")
|
||||
for _, seam := range []string{"write", "sync"} {
|
||||
t.Run(seam, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
if _, err := s.Write(0, makeBlock(blockSize, 0x30)); err != nil { // LSN 1
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, makeBlock(blockSize, 0x31)); err != nil { // LSN 2, synced, unflushed
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sb := *s.sb // an older flush's superblock: the bounds Recover must rebuild and persist
|
||||
sb.WALCheckpointLSN, sb.WALTail, sb.WALHead = 1, 0, S
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := sb.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
crashed = true
|
||||
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
rClosed := false
|
||||
t.Cleanup(func() {
|
||||
if !rClosed {
|
||||
_ = r.Close()
|
||||
}
|
||||
})
|
||||
realWrite, realSync := r.writeSuperblockMetadata, r.syncSuperblockMetadata
|
||||
if seam == "write" {
|
||||
r.writeSuperblockMetadata = func([]byte) error { return errInjected }
|
||||
} else {
|
||||
r.syncSuperblockMetadata = func() error { return errInjected }
|
||||
}
|
||||
if _, err := r.Recover(); !errors.Is(err, errInjected) {
|
||||
t.Fatalf("Recover with a failing superblock %s: err=%v; want the injected failure", seam, err)
|
||||
}
|
||||
head := r.wal.logicalHeadValue()
|
||||
r.admissionTimeout = 200 * time.Millisecond
|
||||
if _, err := r.Write(5, makeBlock(blockSize, 0x55)); err == nil {
|
||||
t.Fatal("Write after a failed Recover succeeded; want it refused until the bounds are persisted")
|
||||
}
|
||||
if r.wal.logicalHeadValue() != head {
|
||||
t.Fatalf("refused Write moved the WAL head %d -> %d", head, r.wal.logicalHeadValue())
|
||||
}
|
||||
|
||||
r.writeSuperblockMetadata, r.syncSuperblockMetadata = realWrite, realSync
|
||||
live := r
|
||||
if seam == "sync" {
|
||||
// A failed fsync is sticky (ErrFsyncFailed): no same-instance
|
||||
// retry; the bounds are persisted by the recovery of a reopen.
|
||||
if _, err := r.Recover(); !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("same-instance Recover after a failed fsync: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, r)
|
||||
rClosed = true
|
||||
r2, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r2.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() {
|
||||
if live == r2 && !rClosed {
|
||||
_ = r2.Close()
|
||||
}
|
||||
})
|
||||
rClosed = false
|
||||
live = r2
|
||||
}
|
||||
if _, err := live.Recover(); err != nil {
|
||||
t.Fatalf("Recover retry: %v", err)
|
||||
}
|
||||
disk := diskSuperblockForTest(t, path)
|
||||
if tail, h := live.wal.logicalTailValue(), live.wal.logicalHeadValue(); disk.WALTail != tail || disk.WALHead != h {
|
||||
t.Fatalf("after the retry: persisted tail=%d head=%d, writer tail=%d head=%d", disk.WALTail, disk.WALHead, tail, h)
|
||||
}
|
||||
live.admissionTimeout = 30 * time.Second
|
||||
if _, err := live.Write(5, makeBlock(blockSize, 0x55)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := live.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, live)
|
||||
rClosed = true
|
||||
|
||||
q, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = q.Close() })
|
||||
if _, err := q.Recover(); err != nil {
|
||||
t.Fatalf("reopen Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, q, 1, makeBlock(blockSize, 0x31))
|
||||
assertRecoveryHardeningBlock(t, q, 5, makeBlock(blockSize, 0x55))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -67,39 +67,6 @@ func OpenReadOnlyWithOptions(path string, opts WALStoreOptions) (*WALStoreReader
|
||||
return openReadOnlyV3(path, opts)
|
||||
}
|
||||
|
||||
func openLegacyReadOnlyWithOptions(path string, opts WALStoreOptions) (*WALStoreReader, error) {
|
||||
f, err := os.OpenFile(path, os.O_RDONLY, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("storage: OpenReadOnly %s: %w", path, err)
|
||||
}
|
||||
if _, err := f.Seek(0, 0); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, fmt.Errorf("storage: seek superblock: %w", err)
|
||||
}
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := sb.validate(); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
metadata, _, err := bindBlockMetadata(f, &sb, opts, false, true)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
return nil, err
|
||||
}
|
||||
dm := newDirtyMap(64)
|
||||
// Replay WAL into the dirty map. recoverWAL is a pure read pass
|
||||
// over the WAL frames — no writes back to the fd.
|
||||
if _, err := recoverWAL(f, &sb, dm); err != nil {
|
||||
_ = f.Close()
|
||||
return nil, fmt.Errorf("storage: OpenReadOnly recover: %w", err)
|
||||
}
|
||||
return &WALStoreReader{metadata: metadata, fd: f, sb: &sb, dm: dm}, nil
|
||||
}
|
||||
|
||||
// Read returns the current bytes at lba — same merge logic the
|
||||
// daemon uses (WAL-recent over extent). No mutation; safe to call
|
||||
// concurrently from multiple goroutines.
|
||||
@@ -109,46 +76,10 @@ func (r *WALStoreReader) Read(lba uint32) ([]byte, error) {
|
||||
r.mu.Unlock()
|
||||
return nil, errors.New("storage: WALStoreReader.Read after Close")
|
||||
}
|
||||
if r.v3 != nil {
|
||||
defer r.mu.Unlock()
|
||||
return r.readV3(lba)
|
||||
}
|
||||
r.mu.Unlock()
|
||||
|
||||
maxLBA := uint32(r.sb.VolumeSize / uint64(r.sb.BlockSize))
|
||||
if lba >= maxLBA {
|
||||
return nil, fmt.Errorf("storage: LBA %d out of range", lba)
|
||||
}
|
||||
// WAL-recent first. Inline the same logic as WALStore.readFromWAL
|
||||
// + readFromExtent, but operating against the read-only fd.
|
||||
if walRelOff, dataOffset, _, _, ok := r.dm.get(uint64(lba)); ok {
|
||||
return r.readFromWAL(walRelOff, dataOffset)
|
||||
}
|
||||
return r.readFromExtent(lba)
|
||||
}
|
||||
defer r.mu.Unlock()
|
||||
return r.readV3(lba)
|
||||
|
||||
func (r *WALStoreReader) readFromWAL(walRelOff uint64, dataOffset uint32) ([]byte, error) {
|
||||
headerBuf := make([]byte, walEntryHeaderSize)
|
||||
absOff := int64(r.sb.WALOffset + walRelOff)
|
||||
if _, err := r.fd.ReadAt(headerBuf, absOff); err != nil {
|
||||
return nil, fmt.Errorf("storage: OpenReadOnly WAL header: %w", err)
|
||||
}
|
||||
if headerBuf[16] == walEntryTrim {
|
||||
return make([]byte, r.sb.BlockSize), nil
|
||||
}
|
||||
length := parseLengthFromHeader(headerBuf)
|
||||
if dataOffset >= length {
|
||||
return nil, fmt.Errorf("storage: OpenReadOnly WAL data offset %d >= length %d", dataOffset, length)
|
||||
}
|
||||
readLen := r.sb.BlockSize
|
||||
if remaining := length - dataOffset; remaining < readLen {
|
||||
readLen = remaining
|
||||
}
|
||||
data := make([]byte, readLen)
|
||||
if _, err := r.fd.ReadAt(data, absOff+int64(walEntryPrefixSize)+int64(dataOffset)); err != nil {
|
||||
return nil, fmt.Errorf("storage: OpenReadOnly WAL data: %w", err)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (r *WALStoreReader) readFromExtent(lba uint32) ([]byte, error) {
|
||||
|
||||
@@ -44,201 +44,11 @@ func (s *WALStore) ScanLBAs(fromLSN uint64, fn func(RecoveryEntry) error) error
|
||||
s.mu.RUnlock()
|
||||
return errors.New("storage: walstore ScanLBAs after Close")
|
||||
}
|
||||
checkpointLSN := s.checkpointLSN
|
||||
headLSN := s.nextLSN
|
||||
retentionLSNs := s.recoveryRetentionLSNs
|
||||
s.mu.RUnlock()
|
||||
if s.v3 != nil {
|
||||
// The v3 source-state gate must precede even an empty scan.
|
||||
return s.scanLBAsV3(fromLSN, fn)
|
||||
}
|
||||
|
||||
// Retention gate: by default the recycle threshold is
|
||||
// checkpointLSN; an operator-tunable retention window lets a
|
||||
// slow replica keep a recovery scan path while it lags within
|
||||
// the configured envelope.
|
||||
//
|
||||
// Effective recycle floor:
|
||||
// floor = checkpointLSN - retentionLSNs (saturating to 0)
|
||||
//
|
||||
// fromLSN is recycled when fromLSN <= floor (strict <= — an LSN
|
||||
// equal to the floor IS recycled). retentionLSNs == 0 reduces
|
||||
// to the simple 'fromLSN <= checkpointLSN' gate.
|
||||
//
|
||||
// Pinned by: INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (positive)
|
||||
// + INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (the knob itself).
|
||||
floor := checkpointLSN
|
||||
if retentionLSNs >= floor {
|
||||
floor = 0
|
||||
} else {
|
||||
floor = checkpointLSN - retentionLSNs
|
||||
}
|
||||
if fromLSN <= floor && checkpointLSN > 0 {
|
||||
// Wrap in typed RecoveryFailure so transport can extract
|
||||
// the kind via errors.As. errors.Is(err, ErrWALRecycled)
|
||||
// still works via Unwrap.
|
||||
return NewWALRecycledFailure(
|
||||
ErrWALRecycled,
|
||||
fmt.Sprintf("fromLSN=%d checkpointLSN=%d headLSN=%d retentionLSNs=%d floor=%d",
|
||||
fromLSN, checkpointLSN, headLSN, retentionLSNs, floor),
|
||||
)
|
||||
}
|
||||
if fromLSN >= headLSN {
|
||||
return nil // caller is at-or-ahead of head; nothing to ship
|
||||
}
|
||||
// The v3 source-state gate must precede even an empty scan.
|
||||
return s.scanLBAsV3(fromLSN, fn)
|
||||
|
||||
// Snapshot WAL writer's logical head/tail under its own lock,
|
||||
// then walk the active region. Wraparound handled the same way
|
||||
// recovery.go:recoverWAL does it.
|
||||
logicalHead := s.wal.logicalHeadValue()
|
||||
logicalTail := s.wal.logicalTailValue()
|
||||
walSize := s.sb.WALSize
|
||||
walOffset := s.sb.WALOffset
|
||||
|
||||
if logicalHead == logicalTail {
|
||||
return nil // WAL is empty
|
||||
}
|
||||
|
||||
physHead := logicalHead % walSize
|
||||
physTail := logicalTail % walSize
|
||||
type scanRange struct{ start, end uint64 }
|
||||
var ranges []scanRange
|
||||
if physHead > physTail {
|
||||
ranges = append(ranges, scanRange{physTail, physHead})
|
||||
} else {
|
||||
ranges = append(ranges, scanRange{physTail, walSize})
|
||||
if physHead > 0 {
|
||||
ranges = append(ranges, scanRange{0, physHead})
|
||||
}
|
||||
}
|
||||
|
||||
blockSize := s.sb.BlockSize
|
||||
|
||||
for _, r := range ranges {
|
||||
pos := r.start
|
||||
for pos < r.end {
|
||||
remaining := r.end - pos
|
||||
if remaining < uint64(walEntryHeaderSize) {
|
||||
break
|
||||
}
|
||||
headerBuf := make([]byte, walEntryHeaderSize)
|
||||
absOff := int64(walOffset + pos)
|
||||
if _, err := s.fd.ReadAt(headerBuf, absOff); err != nil {
|
||||
return fmt.Errorf("storage: walstore ScanLBAs read header at %d: %w", pos, err)
|
||||
}
|
||||
entryType := headerBuf[16]
|
||||
lengthField := parseLengthFromHeader(headerBuf)
|
||||
|
||||
if entryType == walEntryPadding {
|
||||
pos += uint64(walEntryHeaderSize) + uint64(lengthField)
|
||||
continue
|
||||
}
|
||||
var payloadLen uint64
|
||||
if entryType == walEntryWrite || entryType == walEntryWriteBatch {
|
||||
payloadLen = uint64(lengthField)
|
||||
}
|
||||
entrySize := uint64(walEntryHeaderSize) + payloadLen
|
||||
if entrySize > remaining {
|
||||
// Torn / partial entry; stop this range.
|
||||
break
|
||||
}
|
||||
fullBuf := make([]byte, entrySize)
|
||||
if _, err := s.fd.ReadAt(fullBuf, absOff); err != nil {
|
||||
return fmt.Errorf("storage: walstore ScanLBAs read entry at %d: %w", pos, err)
|
||||
}
|
||||
entry, err := decodeWALEntry(fullBuf)
|
||||
if err != nil {
|
||||
// Torn or trailing-zero region — stop scanning.
|
||||
break
|
||||
}
|
||||
|
||||
pos += entrySize
|
||||
|
||||
// LSN filter: skip entries below fromLSN; stop walking
|
||||
// is NOT correct here because LSN order in the WAL is
|
||||
// monotonic only WITHIN A RANGE — we may need to keep
|
||||
// scanning past entries below fromLSN in the wraparound
|
||||
// case. Filter inline rather than break.
|
||||
highestEntryLSN := entry.LSN
|
||||
if entry.Type == walEntryWriteBatch && entry.Reserved > 0 {
|
||||
highestEntryLSN = entry.LSN + entry.Reserved - 1
|
||||
}
|
||||
if highestEntryLSN < fromLSN {
|
||||
continue
|
||||
}
|
||||
if entry.LSN >= headLSN {
|
||||
continue
|
||||
}
|
||||
|
||||
// Build RecoveryEntry. Walstore stores full data in
|
||||
// the WAL — emit byte-for-byte.
|
||||
switch entry.Type {
|
||||
case walEntryWrite:
|
||||
blocks := entry.Length / blockSize
|
||||
if blocks == 0 {
|
||||
blocks = 1
|
||||
}
|
||||
// One WAL entry may cover multiple consecutive LBAs
|
||||
// (entry.Length spans multiple block-sized chunks).
|
||||
// Emit one RecoveryEntry per block, all carrying the
|
||||
// same LSN — V2-faithful since each LSN labels the
|
||||
// full multi-block write atomically.
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
blockData := entry.Data[i*blockSize : (i+1)*blockSize]
|
||||
emit := RecoveryEntry{
|
||||
LSN: entry.LSN,
|
||||
LBA: uint32(entry.LBA) + i,
|
||||
Flags: walEntryWrite,
|
||||
Data: blockData,
|
||||
}
|
||||
if err := fn(emit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case walEntryWriteBatch:
|
||||
blocks := uint32(entry.Reserved)
|
||||
if blocks == 0 || entry.Length != blocks*blockSize {
|
||||
return fmt.Errorf("storage: walstore ScanLBAs invalid batch record at %d", pos-entrySize)
|
||||
}
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
lsn := entry.LSN + uint64(i)
|
||||
if lsn < fromLSN || lsn >= headLSN {
|
||||
continue
|
||||
}
|
||||
blockData := entry.Data[i*blockSize : (i+1)*blockSize]
|
||||
emit := RecoveryEntry{
|
||||
LSN: lsn,
|
||||
LBA: uint32(entry.LBA) + i,
|
||||
Flags: walEntryWrite,
|
||||
Data: blockData,
|
||||
}
|
||||
if err := fn(emit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case walEntryTrim:
|
||||
blocks := entry.Length / blockSize
|
||||
if blocks == 0 {
|
||||
blocks = 1
|
||||
}
|
||||
for i := uint32(0); i < blocks; i++ {
|
||||
emit := RecoveryEntry{
|
||||
LSN: entry.LSN,
|
||||
LBA: uint32(entry.LBA) + i,
|
||||
Flags: walEntryTrim,
|
||||
Data: nil, // trim has no data
|
||||
}
|
||||
if err := fn(emit); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case walEntryBarrier:
|
||||
// barrier entries don't carry data; skip emission
|
||||
// (they're an internal marker, not a recovery payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WALCapacityBytes exposes the WAL region size for POC retention
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Condition (1) for any prefix-cut recovery rule: an intentional LSN gap
|
||||
// must not drop synced entries above it. A
|
||||
// rebuild installs BASE through WriteExtentDirect (no LSN) and applies
|
||||
// WAL-lane entries with their real LSNs through ApplyEntry; the frontier
|
||||
// jump (AdvanceFrontier at MarkBaseComplete) is not persisted before them.
|
||||
// So a replica can hold a synced LSN 101 with a persisted checkpoint of 0 and
|
||||
// no LSN 1..100 anywhere. Recovery must keep it (a rule that replays only the
|
||||
// contiguous LSN prefix above the checkpoint keeps nothing here).
|
||||
func TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, 24*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
crashed := false
|
||||
t.Cleanup(func() {
|
||||
if !crashed {
|
||||
_ = s.Close()
|
||||
}
|
||||
})
|
||||
if err := s.WriteExtentDirect(0, makeBlock(blockSize, 0xBA)); err != nil { // BASE, no LSN
|
||||
t.Fatal(err)
|
||||
}
|
||||
live := makeBlock(blockSize, 0x65)
|
||||
if err := s.ApplyEntry(3, live, 101); err != nil { // session-live entry above the BASE hint
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.ApplyEntry(4, makeBlock(blockSize, 0x66), 102); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
synced, err := s.Sync()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if synced < 102 {
|
||||
t.Fatalf("Sync frontier %d; want 102 (the applied entries are synced)", synced)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
crashed = true
|
||||
if sb := diskSuperblockForGapTest(t, path); sb.WALCheckpointLSN != 0 {
|
||||
t.Fatalf("persisted checkpoint %d; want 0 (the frontier jump is not persisted)", sb.WALCheckpointLSN)
|
||||
}
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("Recover: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 3, live)
|
||||
assertRecoveryHardeningBlock(t, r, 4, makeBlock(blockSize, 0x66))
|
||||
}
|
||||
|
||||
// diskSuperblockForGapTest reads the on-disk superblock with a plain file
|
||||
// read: no store, no flusher or committer.
|
||||
func diskSuperblockForGapTest(t *testing.T, path string) superblock {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sb
|
||||
}
|
||||
@@ -3,283 +3,12 @@ package storage
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
|
||||
"hash/crc32"
|
||||
"path/filepath"
|
||||
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWALStoreRecoverRetainsMultiBlockSuffixAcrossRestart(t *testing.T) {
|
||||
const blockSize = 4096
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 32, blockSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
|
||||
blocks := make([][]byte, 16)
|
||||
for index := range blocks {
|
||||
blocks[index] = makeBlock(blockSize, byte(0x60+index))
|
||||
}
|
||||
if _, err := s.WriteBatch(0, blocks); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.SetRecycleFloorSource(&fakeRecycleFloorSource{floor: 8, anyActive: true})
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != 8 {
|
||||
t.Fatalf("pinned checkpoint=%d want 8", got)
|
||||
}
|
||||
if got := s.wal.logicalTailValue(); got != 0 {
|
||||
t.Fatalf("physical WAL tail under pin=%d want 0", got)
|
||||
}
|
||||
_, tail, head := s.Boundaries()
|
||||
if tail != 1 || head != 16 {
|
||||
t.Fatalf("logical tail/head under pin=%d/%d want 1/16", tail, head)
|
||||
}
|
||||
var retained []RecoveryEntry
|
||||
if err := s.ScanLBAs(9, func(entry RecoveryEntry) error {
|
||||
retained = append(retained, entry)
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(retained) != 8 {
|
||||
t.Fatalf("retained entries above pin=%d want 8", len(retained))
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if recovered, err := reopened.Recover(); err != nil || recovered != 16 {
|
||||
t.Fatalf("Recover=%d err=%v want 16,nil", recovered, err)
|
||||
}
|
||||
wantRecoveredHead := uint64(walEntryHeaderSize + 16*blockSize)
|
||||
if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != 0 || head != wantRecoveredHead {
|
||||
t.Fatalf("recovered physical tail/head=%d/%d want 0/%d",
|
||||
tail, head, wantRecoveredHead)
|
||||
}
|
||||
newBlock := makeBlock(blockSize, 0xF1)
|
||||
newLSN, err := reopened.Write(20, newBlock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newEntry := recoverySnapshotEntriesByLBA(reopened.dm.snapshot())[20]
|
||||
if newEntry.WALOffset != wantRecoveredHead {
|
||||
t.Fatalf("post-recovery append offset=%d want %d",
|
||||
newEntry.WALOffset, wantRecoveredHead)
|
||||
}
|
||||
if _, err := reopened.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reopened.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := reopened.CheckpointLSN(); got != newLSN {
|
||||
t.Fatalf("checkpoint after recovery=%d want %d", got, newLSN)
|
||||
}
|
||||
for index, want := range blocks {
|
||||
assertRecoveryHardeningBlock(t, reopened, uint32(index), want)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, reopened, 20, newBlock)
|
||||
}
|
||||
|
||||
func TestWALStoreRecoverRejectsOverflowingBatchGeometry(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func([]byte)
|
||||
}{
|
||||
{
|
||||
name: "reserved multiplication overflow",
|
||||
mutate: func(record []byte) {
|
||||
binary.LittleEndian.PutUint64(record[8:16], (uint64(1)<<52)+3)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "LSN range overflow",
|
||||
mutate: func(record []byte) {
|
||||
binary.LittleEndian.PutUint64(record[0:8], ^uint64(0)-1)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "reserved length mismatch",
|
||||
mutate: func(record []byte) {
|
||||
binary.LittleEndian.PutUint64(record[8:16], 2)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
blocks = 3
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s, err := createLegacyWALStoreForTest(path, 16, blockSize)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(4, [][]byte{
|
||||
makeBlock(blockSize, 0xA1),
|
||||
makeBlock(blockSize, 0xA2),
|
||||
makeBlock(blockSize, 0xA3),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := recoverySnapshotEntriesByLBA(s.dm.snapshot())[4]
|
||||
rewriteRecoveryRecordForTest(
|
||||
t, s, uint64(walEntryHeaderSize+blocks*blockSize),
|
||||
int64(s.sb.WALOffset+entry.WALOffset), tt.mutate,
|
||||
)
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
recovered, recoverErr := reopened.Recover()
|
||||
if recovered != 0 || !errors.Is(recoverErr, ErrWALIntegrityFault) {
|
||||
t.Fatalf("Recover=%d err=%v want 0,WALIntegrity", recovered, recoverErr)
|
||||
}
|
||||
if got := reopened.dm.len(); got != 0 {
|
||||
t.Fatalf("dirty entries from malformed batch=%d want 0", got)
|
||||
}
|
||||
if got := reopened.NextLSN(); got != 1 {
|
||||
t.Fatalf("next LSN after malformed batch=%d want 1", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreRecoverReconstructsLegacyWrappedRetainedWindow(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
lowRecordSize = uint64(walEntryHeaderSize + 2*blockSize)
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 3; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
high := makeBlock(blockSize, 0xA4)
|
||||
if _, err := s.Write(20, high); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
low := [][]byte{
|
||||
makeBlock(blockSize, 0xB5),
|
||||
makeBlock(blockSize, 0xB6),
|
||||
}
|
||||
if _, err := s.WriteBatch(24, low); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries := recoverySnapshotEntriesByLBA(s.dm.snapshot())
|
||||
if entries[20].WALOffset != uint64(3*(walEntryHeaderSize+blockSize)) ||
|
||||
entries[24].WALOffset != 0 {
|
||||
t.Fatalf("high/low offsets=%d/%d want %d/0",
|
||||
entries[20].WALOffset, entries[24].WALOffset,
|
||||
3*(walEntryHeaderSize+blockSize))
|
||||
}
|
||||
|
||||
legacy := *s.sb
|
||||
legacy.WALHead = 0
|
||||
legacy.WALTail = 0
|
||||
buf := newSimpleByteBuf()
|
||||
if _, err := legacy.writeTo(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.fd.WriteAt(buf.bytes(), 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.fd.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
|
||||
reopened, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = reopened.Close() })
|
||||
if recovered, err := reopened.Recover(); err != nil || recovered != 6 {
|
||||
t.Fatalf("Recover=%d err=%v want 6,nil", recovered, err)
|
||||
}
|
||||
wantTail := entries[20].WALOffset
|
||||
wantHead := walSize + lowRecordSize
|
||||
if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != wantTail || head != wantHead {
|
||||
t.Fatalf("recovered wrapped tail/head=%d/%d want %d/%d",
|
||||
tail, head, wantTail, wantHead)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, reopened, 20, high)
|
||||
assertRecoveryHardeningBlock(t, reopened, 24, low[0])
|
||||
assertRecoveryHardeningBlock(t, reopened, 25, low[1])
|
||||
|
||||
postRecovery := makeBlock(blockSize, 0xC7)
|
||||
finalLSN, err := reopened.Write(30, postRecovery)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
postEntry := recoverySnapshotEntriesByLBA(reopened.dm.snapshot())[30]
|
||||
if postEntry.WALOffset != lowRecordSize {
|
||||
t.Fatalf("post-recovery append offset=%d want %d",
|
||||
postEntry.WALOffset, lowRecordSize)
|
||||
}
|
||||
if _, err := reopened.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reopened.flusher.flushOnce(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := reopened.CheckpointLSN(); got != finalLSN {
|
||||
t.Fatalf("checkpoint=%d want %d", got, finalLSN)
|
||||
}
|
||||
if got := reopened.dm.len(); got != 0 {
|
||||
t.Fatalf("dirty entries after wrapped flush=%d want 0", got)
|
||||
}
|
||||
wantFinalBoundary := wantHead + uint64(walEntryHeaderSize+blockSize)
|
||||
if tail, head := reopened.wal.logicalTailValue(), reopened.wal.logicalHeadValue(); tail != wantFinalBoundary || head != wantFinalBoundary {
|
||||
t.Fatalf("final wrapped tail/head=%d/%d want %d/%d",
|
||||
tail, head, wantFinalBoundary, wantFinalBoundary)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, reopened, 20, high)
|
||||
assertRecoveryHardeningBlock(t, reopened, 24, low[0])
|
||||
assertRecoveryHardeningBlock(t, reopened, 25, low[1])
|
||||
assertRecoveryHardeningBlock(t, reopened, 30, postRecovery)
|
||||
}
|
||||
|
||||
func crashRecoveryHardeningStore(t *testing.T, s *WALStore) {
|
||||
t.Helper()
|
||||
s.committer.Stop()
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Recovery is last-writer-wins by LSN. Two valid versions of one LBA
|
||||
// survive in the WAL; the persisted
|
||||
// head/tail predate the wrap, so the range scanned first holds the newer
|
||||
// version (wrapped to offset 0) and the range scanned later the older one.
|
||||
// Recovery must still serve the newer bytes.
|
||||
func TestWALStoreRecoverLastWriterWinsAcrossScanOrder(t *testing.T) {
|
||||
const (
|
||||
blockSize = 4096
|
||||
walSize = 24 * 1024
|
||||
)
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, blockSize, walSize)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
for lba := uint32(0); lba < 3; lba++ {
|
||||
if _, err := s.Write(lba, makeBlock(blockSize, byte(0x10+lba))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.flusher.flushOnce(); err != nil { // checkpoint 3: head/tail persisted here
|
||||
t.Fatal(err)
|
||||
}
|
||||
older := makeBlock(blockSize, 0xA4)
|
||||
if _, err := s.Write(20, older); err != nil { // LSN 4, at the high end
|
||||
t.Fatal(err)
|
||||
}
|
||||
newer := makeBlock(blockSize, 0xB5)
|
||||
s.enableMultiBlockRecordsForTest(true)
|
||||
if _, err := s.WriteBatch(20, [][]byte{newer, makeBlock(blockSize, 0xB6)}); err != nil { // LSN 5-6, wraps to 0
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if e := recoverySnapshotEntriesByLBA(s.dm.snapshot())[20]; e.WALOffset != 0 || e.LSN != 5 {
|
||||
t.Fatalf("newest LBA 20 entry at offset %d LSN %d; want the wrapped batch at 0, LSN 5", e.WALOffset, e.LSN)
|
||||
}
|
||||
crashRecoveryHardeningStore(t, s)
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := r.Read(20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got[0] != newer[0] {
|
||||
t.Fatalf("LBA 20 after recovery = %02x; want the newer version %02x (LSN 5), not the older %02x (LSN 4)", got[0], newer[0], older[0])
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// G7-redo priority 2.5 — WAL recycle path consumes
|
||||
// `MinPinAcrossActiveSessions()` from an external coordinator (today
|
||||
// `core/recovery.PeerShipCoordinator`). These tests pin the substrate
|
||||
@@ -29,139 +25,3 @@ type fakeRecycleFloorSource struct {
|
||||
func (f *fakeRecycleFloorSource) MinPinAcrossActiveSessions() (uint64, bool) {
|
||||
return f.floor, f.anyActive
|
||||
}
|
||||
|
||||
// TestWALStore_RecycleGate_NilSource_LegacyBehavior pins fallback:
|
||||
// when no source is installed (the daemon is in legacy mode, or
|
||||
// dual-lane wiring opted out for this volume), persistCheckpoint
|
||||
// advances exactly as it did before priority 2.5 landed.
|
||||
func TestWALStore_RecycleGate_NilSource_LegacyBehavior(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 50) // start at checkpoint=50
|
||||
|
||||
// No source set → checkpoint advances to 100 unmodified.
|
||||
if err := ws.persistCheckpoint(100); err != nil {
|
||||
t.Fatalf("persistCheckpoint(100): %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 100 {
|
||||
t.Errorf("CheckpointLSN = %d, want 100 (nil source = no clamp)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecycleGate_SourceInactive_LegacyBehavior pins the
|
||||
// `(_, false)` branch: a source that reports "no active session"
|
||||
// MUST NOT clamp. This is the steady-state (no rebuild in flight)
|
||||
// path; legacy behavior is preserved.
|
||||
func TestWALStore_RecycleGate_SourceInactive_LegacyBehavior(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 50)
|
||||
|
||||
src := &fakeRecycleFloorSource{floor: 60, anyActive: false}
|
||||
ws.SetRecycleFloorSource(src)
|
||||
|
||||
// Even though src.floor=60 (< 100), anyActive=false → no clamp.
|
||||
if err := ws.persistCheckpoint(100); err != nil {
|
||||
t.Fatalf("persistCheckpoint(100): %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 100 {
|
||||
t.Errorf("CheckpointLSN = %d, want 100 (anyActive=false bypasses gate)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecycleGate_SourceActive_ClampsAtFloor pins the
|
||||
// headline behavior: an active session with floor=70 forces the
|
||||
// effective checkpoint to 70 even though the flusher proposed 100.
|
||||
// This is what holds the WAL retained for a replica that has
|
||||
// committed pin_floor=70 in its rebuild session.
|
||||
func TestWALStore_RecycleGate_SourceActive_ClampsAtFloor(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 50)
|
||||
|
||||
src := &fakeRecycleFloorSource{floor: 70, anyActive: true}
|
||||
ws.SetRecycleFloorSource(src)
|
||||
|
||||
// Flusher proposes 100; gate clamps to 70.
|
||||
if err := ws.persistCheckpoint(100); err != nil {
|
||||
t.Fatalf("persistCheckpoint(100): %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 70 {
|
||||
t.Errorf("CheckpointLSN = %d, want 70 (clamped to active pin floor)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecycleGate_FloorAboveProposed_NoClamp pins the
|
||||
// "floor doesn't pull checkpoint forward" rule: when the source
|
||||
// reports floor=200 but the flusher only has 100 ready, the
|
||||
// effective checkpoint is the proposed 100 — the floor is an
|
||||
// upper-bound gate, not a target.
|
||||
func TestWALStore_RecycleGate_FloorAboveProposed_NoClamp(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 50)
|
||||
|
||||
src := &fakeRecycleFloorSource{floor: 200, anyActive: true}
|
||||
ws.SetRecycleFloorSource(src)
|
||||
|
||||
// floor=200 >= proposed=100 → no clamp; checkpoint advances to 100.
|
||||
if err := ws.persistCheckpoint(100); err != nil {
|
||||
t.Fatalf("persistCheckpoint(100): %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 100 {
|
||||
t.Errorf("CheckpointLSN = %d, want 100 (floor >= proposed → no clamp)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecycleGate_FloorBelowCurrentCheckpoint_NoRegress pins
|
||||
// the monotonic invariant: even if the source reports a floor BELOW
|
||||
// the current checkpoint (e.g., transient race during session
|
||||
// install), persistCheckpoint must not regress checkpointLSN. The
|
||||
// `if highestLSN <= s.checkpointLSN { return nil }` guard handles
|
||||
// this — the post-clamp value just becomes a no-op rather than a
|
||||
// rollback.
|
||||
func TestWALStore_RecycleGate_FloorBelowCurrentCheckpoint_NoRegress(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 80) // current checkpoint = 80
|
||||
|
||||
// Active session reports floor=30 (below current). The clamp
|
||||
// would set highestLSN=30, but the no-regress guard returns
|
||||
// without changing checkpointLSN.
|
||||
src := &fakeRecycleFloorSource{floor: 30, anyActive: true}
|
||||
ws.SetRecycleFloorSource(src)
|
||||
|
||||
if err := ws.persistCheckpoint(100); err != nil {
|
||||
t.Fatalf("persistCheckpoint(100): %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 80 {
|
||||
t.Errorf("CheckpointLSN = %d, want 80 (must not regress under floor)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecycleGate_SetRecycleFloorSourceNil_Disables pins the
|
||||
// disable path: passing nil to SetRecycleFloorSource removes the gate
|
||||
// (used when the daemon transitions back to legacy mode, or when a
|
||||
// volume is closing down a coordinator). After Set(nil), behavior
|
||||
// matches the nil-source default.
|
||||
func TestWALStore_RecycleGate_SetRecycleFloorSourceNil_Disables(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 50)
|
||||
|
||||
src := &fakeRecycleFloorSource{floor: 70, anyActive: true}
|
||||
ws.SetRecycleFloorSource(src)
|
||||
|
||||
// First call clamps to 70.
|
||||
if err := ws.persistCheckpoint(100); err != nil {
|
||||
t.Fatalf("persistCheckpoint(100) [gated]: %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 70 {
|
||||
t.Fatalf("CheckpointLSN = %d, want 70 (gated)", got)
|
||||
}
|
||||
|
||||
// Disable the gate.
|
||||
ws.SetRecycleFloorSource(nil)
|
||||
|
||||
// Second call advances unmodified.
|
||||
if err := ws.persistCheckpoint(150); err != nil {
|
||||
t.Fatalf("persistCheckpoint(150) [ungated]: %v", err)
|
||||
}
|
||||
if got := ws.CheckpointLSN(); got != 150 {
|
||||
t.Errorf("CheckpointLSN = %d, want 150 (gate disabled)", got)
|
||||
}
|
||||
}
|
||||
@@ -1,41 +1,9 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// G6 §1.A α + §2 substrate retention-gate tests:
|
||||
//
|
||||
// Pre-G6: walstore's recovery scan rejects fromLSN <= checkpointLSN
|
||||
// (strict gate; G5-5C scenario D evidence).
|
||||
//
|
||||
// G6: WALRetentionLSNs widens the window so fromLSN > (checkpointLSN
|
||||
// - retention) is still scannable. This buys a slow replica room to
|
||||
// catch up before the engine has to escalate to rebuild.
|
||||
//
|
||||
// Pinned by:
|
||||
// - INV-G6-CATCHUP-CONVERGES-WITHIN-RETENTION (positive: within window
|
||||
// scan succeeds)
|
||||
// - INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE (the knob is a real
|
||||
// operator-tunable plumbed from --wal-retention-lsns)
|
||||
|
||||
// freshWALStore creates a walstore in a temp dir and returns it.
|
||||
// Uses small block geometry — the tests exercise scan-gate semantics,
|
||||
// not block-IO performance.
|
||||
func freshWALStore(t *testing.T) *WALStore {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "v.bin")
|
||||
ws, err := createLegacyWALStoreForTest(path, 64, 4096)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateWALStore: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ws.Close() })
|
||||
return ws
|
||||
}
|
||||
|
||||
// advanceCheckpointForTest writes data to grow nextLSN, then forces
|
||||
// the in-memory checkpointLSN to a chosen value so the test can
|
||||
// exercise the retention gate at a known boundary. Test-only path —
|
||||
@@ -62,122 +30,3 @@ func (c *recoveryEntryCounter) onEntry(RecoveryEntry) error {
|
||||
c.count++
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestWALStore_RecoveryRetention_Default_StrictRecycle pins pre-G6
|
||||
// behavior under the new code: when WALRetentionLSNs is 0 (default),
|
||||
// the gate behaves exactly as before — fromLSN <= checkpointLSN is
|
||||
// rejected with WALRecycled.
|
||||
func TestWALStore_RecoveryRetention_Default_StrictRecycle(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 100)
|
||||
|
||||
if got := ws.RecoveryRetentionLSNs(); got != 0 {
|
||||
t.Fatalf("default retention = %d, want 0", got)
|
||||
}
|
||||
|
||||
// fromLSN = 50 (well under checkpoint=100) must be recycled.
|
||||
c := &recoveryEntryCounter{}
|
||||
err := ws.ScanLBAs(50, c.onEntry)
|
||||
if err == nil {
|
||||
t.Fatal("fromLSN=50 with checkpoint=100 + retention=0 should be recycled")
|
||||
}
|
||||
if !errors.Is(err, ErrWALRecycled) {
|
||||
t.Errorf("expected ErrWALRecycled (or unwrap chain match), got %v", err)
|
||||
}
|
||||
|
||||
// fromLSN = 100 is at-or-below checkpoint → still recycled
|
||||
// (boundary preserved: <= is rejected, > is accepted).
|
||||
err = ws.ScanLBAs(100, c.onEntry)
|
||||
if !errors.Is(err, ErrWALRecycled) {
|
||||
t.Errorf("fromLSN=100 (== checkpoint) with retention=0 should be recycled, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecoveryRetention_NonZero_WidensWindow verifies the
|
||||
// G6 α path: setting retention=N accepts fromLSN as low as
|
||||
// checkpointLSN - N (exclusive: at floor still rejected; above floor
|
||||
// accepted).
|
||||
func TestWALStore_RecoveryRetention_NonZero_WidensWindow(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 100)
|
||||
ws.SetRecoveryRetentionLSNs(20)
|
||||
if got := ws.RecoveryRetentionLSNs(); got != 20 {
|
||||
t.Fatalf("retention after Set: got %d, want 20", got)
|
||||
}
|
||||
|
||||
// floor = 100 - 20 = 80; fromLSN > 80 is accepted, fromLSN <= 80
|
||||
// is rejected.
|
||||
c := &recoveryEntryCounter{}
|
||||
|
||||
// fromLSN = 90: above floor → accepted (no error). The scan
|
||||
// itself may produce no entries because we haven't written
|
||||
// anything in the window; that's fine — this test only pins the
|
||||
// gate decision, not scan content.
|
||||
if err := ws.ScanLBAs(90, c.onEntry); err != nil {
|
||||
t.Errorf("fromLSN=90 with checkpoint=100 + retention=20 should be accepted, got %v", err)
|
||||
}
|
||||
|
||||
// fromLSN = 81: above floor (80) → accepted.
|
||||
if err := ws.ScanLBAs(81, c.onEntry); err != nil {
|
||||
t.Errorf("fromLSN=81 with checkpoint=100 + retention=20 should be accepted (floor=80), got %v", err)
|
||||
}
|
||||
|
||||
// fromLSN = 80: at floor → rejected (<= floor recycles).
|
||||
err := ws.ScanLBAs(80, c.onEntry)
|
||||
if !errors.Is(err, ErrWALRecycled) {
|
||||
t.Errorf("fromLSN=80 (==floor) should be recycled, got %v", err)
|
||||
}
|
||||
|
||||
// fromLSN = 50: well below floor → rejected.
|
||||
err = ws.ScanLBAs(50, c.onEntry)
|
||||
if !errors.Is(err, ErrWALRecycled) {
|
||||
t.Errorf("fromLSN=50 (<floor) should be recycled, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero
|
||||
// verifies the saturating-subtraction guard: if retention >=
|
||||
// checkpoint, the floor saturates to 0 and any fromLSN > 0 is
|
||||
// accepted.
|
||||
func TestWALStore_RecoveryRetention_LargerThanCheckpoint_ClampsToZero(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 100)
|
||||
ws.SetRecoveryRetentionLSNs(1_000_000) // way larger than checkpoint
|
||||
|
||||
c := &recoveryEntryCounter{}
|
||||
// fromLSN = 1: floor saturates to 0; 1 > 0 → accepted.
|
||||
if err := ws.ScanLBAs(1, c.onEntry); err != nil {
|
||||
t.Errorf("fromLSN=1 with retention >> checkpoint should be accepted (floor saturates to 0), got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWALStore_RecoveryRetention_TypedFailureKind verifies that the
|
||||
// recycle-rejection error is the typed RecoveryFailure envelope (so
|
||||
// the transport layer can extract via errors.As). This pins the
|
||||
// substrate side of INV-G6-WALRECYCLE-DISPATCHES-REBUILD: if the
|
||||
// substrate returned a bare sentinel here, transport's
|
||||
// classifyRecoveryFailure would fall through to RecoveryFailureTransport
|
||||
// and the engine wouldn't escalate to rebuild.
|
||||
func TestWALStore_RecoveryRetention_TypedFailureKind(t *testing.T) {
|
||||
ws := freshWALStore(t)
|
||||
advanceCheckpointForTest(t, ws, 100)
|
||||
ws.SetRecoveryRetentionLSNs(20)
|
||||
|
||||
c := &recoveryEntryCounter{}
|
||||
err := ws.ScanLBAs(50, c.onEntry) // below floor 80 → rejected
|
||||
if err == nil {
|
||||
t.Fatal("expected recycle error")
|
||||
}
|
||||
|
||||
var rf *RecoveryFailure
|
||||
if !errors.As(err, &rf) {
|
||||
t.Fatalf("expected typed *RecoveryFailure (so transport can map kind via errors.As), got %T (%v)", err, err)
|
||||
}
|
||||
if rf.Kind != StorageRecoveryFailureWALRecycled {
|
||||
t.Errorf("RecoveryFailure.Kind = %v, want StorageRecoveryFailureWALRecycled", rf.Kind)
|
||||
}
|
||||
// errors.Is chain still works for legacy callers.
|
||||
if !errors.Is(err, ErrWALRecycled) {
|
||||
t.Error("errors.Is(err, ErrWALRecycled) should still hold via Unwrap chain")
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -24,107 +24,3 @@ func assertStickyFsync(t *testing.T, err error) {
|
||||
t.Fatalf("err %v; want a SubstrateIO RecoveryFailure (io_error)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func stickyStore(t *testing.T) (*WALStore, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil { // acked before the fault
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, path
|
||||
}
|
||||
|
||||
// assertRefusesAfterFault: no Sync ack (and no physical WAL fsync), no write,
|
||||
// no checkpoint; a reopen clears it and keeps the data acked before the fault.
|
||||
func assertRefusesAfterFault(t *testing.T, s *WALStore, path string) {
|
||||
t.Helper()
|
||||
before := s.WALSyncCount()
|
||||
_, err := s.Sync()
|
||||
assertStickyFsync(t, err)
|
||||
if n := s.WALSyncCount() - before; n != 0 {
|
||||
t.Fatalf("a Sync after the fault fsynced again (%d); it must refuse without retrying", n)
|
||||
}
|
||||
if _, err := s.Write(2, makeBlock(4096, 0x22)); err == nil {
|
||||
t.Fatal("a write after an fsync failure was accepted")
|
||||
} else {
|
||||
assertStickyFsync(t, err)
|
||||
}
|
||||
if _, err := s.WriteBatch(3, [][]byte{makeBlock(4096, 0x33)}); err == nil {
|
||||
t.Fatal("a batch write after an fsync failure was accepted")
|
||||
}
|
||||
ckpt := s.CheckpointLSN()
|
||||
_ = s.flusher.flushOnce()
|
||||
if got := s.CheckpointLSN(); got != ckpt {
|
||||
t.Fatalf("the flusher advanced the checkpoint %d -> %d after an fsync failure", ckpt, got)
|
||||
}
|
||||
_ = s.Close()
|
||||
r, err := openLegacyWALStoreForTest(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { _ = r.Close() })
|
||||
if _, err := r.Recover(); err != nil {
|
||||
t.Fatalf("reopen after an fsync failure: %v", err)
|
||||
}
|
||||
assertRecoveryHardeningBlock(t, r, 0, makeBlock(4096, 0x10))
|
||||
if _, err := r.Write(4, makeBlock(4096, 0x44)); err != nil {
|
||||
t.Fatalf("write after a reopen: %v", err)
|
||||
}
|
||||
if _, err := r.Sync(); err != nil {
|
||||
t.Fatalf("Sync after a reopen: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWALStoreWALFsyncFailureIsSticky(t *testing.T) {
|
||||
s, path := stickyStore(t)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
real := s.syncWALFile
|
||||
s.syncWALFile = func() error { return errInjectedFsync }
|
||||
if _, err := s.Sync(); !errors.Is(err, errInjectedFsync) {
|
||||
t.Fatalf("Sync with a failing fsync: %v", err)
|
||||
}
|
||||
s.syncWALFile = real // the disk "recovers": the next fsync would succeed
|
||||
assertRefusesAfterFault(t, s, path)
|
||||
}
|
||||
|
||||
func TestWALStoreExtentFsyncFailureIsSticky(t *testing.T) {
|
||||
s, path := stickyStore(t)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
real := s.syncExtentFile
|
||||
s.syncExtentFile = func() error { return errInjectedFsync }
|
||||
if err := s.flusher.flushOnce(); !errors.Is(err, errInjectedFsync) {
|
||||
t.Fatalf("flush with a failing extent fsync: %v", err)
|
||||
}
|
||||
s.syncExtentFile = real
|
||||
assertRefusesAfterFault(t, s, path)
|
||||
}
|
||||
|
||||
func TestWALStoreCheckpointFsyncFailureIsSticky(t *testing.T) {
|
||||
s, path := stickyStore(t)
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
real := s.syncSuperblockMetadata
|
||||
s.syncSuperblockMetadata = func() error { return errInjectedFsync }
|
||||
if err := s.flusher.flushOnce(); !errors.Is(err, errInjectedFsync) {
|
||||
t.Fatalf("flush with a failing checkpoint fsync: %v", err)
|
||||
}
|
||||
s.syncSuperblockMetadata = real
|
||||
assertRefusesAfterFault(t, s, path)
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -114,82 +112,6 @@ func startWorker(t workerTB, fn func() error, gates ...*gate) <-chan error {
|
||||
return res
|
||||
}
|
||||
|
||||
func heldStore(t *testing.T) (*WALStore, string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "store.bin")
|
||||
s := createLegacyWALStoreWithWALSizeForTest(t, path, 64, 4096, 64*1024)
|
||||
s.DisableAutoFlushForRecoveryTest()
|
||||
t.Cleanup(func() { // runs after the workers' and gates' cleanups (LIFO)
|
||||
if _, leaked := leakedStores.LoadAndDelete(t); leaked {
|
||||
return // a worker is still inside the store: never close under it
|
||||
}
|
||||
_ = s.Close()
|
||||
})
|
||||
return s, path
|
||||
}
|
||||
|
||||
func diskCheckpoint(t *testing.T, path string) uint64 {
|
||||
t.Helper()
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
sb, err := readSuperblock(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return sb.WALCheckpointLSN
|
||||
}
|
||||
|
||||
// A Sync queued behind an fsync that then fails must not be acknowledged by
|
||||
// a second fsync of the same batch run.
|
||||
func TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused(t *testing.T) {
|
||||
s, _ := heldStore(t)
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := newGate(t)
|
||||
real := s.syncWALFile
|
||||
var calls atomic.Int32
|
||||
fault := errors.New("injected fsync failure")
|
||||
s.syncWALFile = func() error {
|
||||
if calls.Add(1) == 1 {
|
||||
g.block()
|
||||
return fault
|
||||
}
|
||||
return real() // a later fsync would "succeed"
|
||||
}
|
||||
|
||||
errA := startWorker(t, func() error {
|
||||
_, err := s.Sync()
|
||||
return err
|
||||
}, g)
|
||||
g.waitEntered(t, "Sync A's fsync")
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
errB := startWorker(t, func() error {
|
||||
_, err := s.Sync()
|
||||
return err
|
||||
}, g)
|
||||
waitQueuedSync(t, s, 1) // B passed the entry check and waits in the committer
|
||||
g.open()
|
||||
|
||||
if err := recvErr(t, errA, "Sync A"); !errors.Is(err, fault) {
|
||||
t.Fatalf("Sync A: %v; want the injected fault", err)
|
||||
}
|
||||
if err := recvErr(t, errB, "Sync B"); !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("queued Sync B after the failed fsync: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
if n := calls.Load(); n != 1 {
|
||||
t.Fatalf("physical fsyncs=%d; want 1 (no fsync after the fault)", n)
|
||||
}
|
||||
if r, _, _ := s.Boundaries(); r != 0 {
|
||||
t.Fatalf("published R=%d after the fault", r)
|
||||
}
|
||||
}
|
||||
|
||||
func waitQueuedSync(t *testing.T, s *WALStore, n int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(holdBound)
|
||||
@@ -205,80 +127,6 @@ func waitQueuedSync(t *testing.T, s *WALStore, n int) {
|
||||
t.Fatalf("no queued Sync after %v", holdBound)
|
||||
}
|
||||
|
||||
// A writer admitted (past its entry check) while an append fails, and then
|
||||
// waiting for the append lock, must not reuse the failed append's LSNs or
|
||||
// offsets. One subtest per write path, each with its own oracle.
|
||||
func TestWALStoreWritersQueuedBehindAFailedAppendAreRefused(t *testing.T) {
|
||||
paths := []struct {
|
||||
name string
|
||||
run func(s *WALStore, lsn uint64) error
|
||||
}{
|
||||
{"Write", func(s *WALStore, _ uint64) error { _, err := s.Write(11, makeBlock(4096, 0xAC)); return err }},
|
||||
{"WriteBatch", func(s *WALStore, _ uint64) error {
|
||||
_, err := s.WriteBatch(20, [][]byte{makeBlock(4096, 0xAD)})
|
||||
return err
|
||||
}},
|
||||
{"ApplyEntry", func(s *WALStore, lsn uint64) error { return s.ApplyEntry(21, makeBlock(4096, 0xAE), lsn) }},
|
||||
}
|
||||
for _, p := range paths {
|
||||
t.Run(p.name, func(t *testing.T) {
|
||||
s, _ := heldStore(t)
|
||||
// WAL admission reads usage under the WAL writer's lock, which the
|
||||
// held append owns; without it the queued writer reaches its
|
||||
// admission point (and then the append lock) deterministically.
|
||||
s.admission = nil
|
||||
appendGate := newGate(t)
|
||||
eio := errors.New("injected EIO after the batch bytes were written")
|
||||
var batchCalls atomic.Int32
|
||||
s.wal.batchWriteAt = func(b []byte, off int64) (int, error) {
|
||||
if batchCalls.Add(1) == 1 {
|
||||
appendGate.block()
|
||||
}
|
||||
n, _ := s.fd.WriteAt(b, off)
|
||||
return n, eio
|
||||
}
|
||||
nextBefore := s.NextLSN()
|
||||
headBefore := s.wal.logicalHeadValue()
|
||||
|
||||
errA := startWorker(t, func() error {
|
||||
_, err := s.WriteBatch(10, [][]byte{makeBlock(4096, 0x5B), makeBlock(4096, 0x5A)})
|
||||
return err
|
||||
}, appendGate)
|
||||
appendGate.waitEntered(t, "the failing batch append")
|
||||
|
||||
// The queued writer acknowledges that it passed its entry check
|
||||
// before the fault exists, then waits for the append lock.
|
||||
admitted := make(chan struct{})
|
||||
var admitOnce sync.Once
|
||||
s.testAfterAdmit = func() { admitOnce.Do(func() { close(admitted) }) }
|
||||
errB := startWorker(t, func() error { return p.run(s, nextBefore) }, appendGate)
|
||||
select {
|
||||
case <-admitted:
|
||||
case <-time.After(holdBound):
|
||||
t.Fatalf("%s was never admitted", p.name)
|
||||
}
|
||||
appendGate.open()
|
||||
|
||||
if err := recvErr(t, errA, "the failing batch"); !errors.Is(err, eio) {
|
||||
t.Fatalf("failing batch: %v", err)
|
||||
}
|
||||
if err := recvErr(t, errB, p.name); !errors.Is(err, ErrAppendFailed) {
|
||||
t.Fatalf("%s admitted before the fault: %v; want ErrAppendFailed", p.name, err)
|
||||
}
|
||||
s.testAfterAdmit = nil
|
||||
if n := batchCalls.Load(); n != 1 {
|
||||
t.Fatalf("batch pwrites=%d; want 1 (no append after the fault)", n)
|
||||
}
|
||||
if got := s.NextLSN(); got != nextBefore {
|
||||
t.Fatalf("NextLSN %d -> %d after a refused %s", nextBefore, got, p.name)
|
||||
}
|
||||
if got := s.wal.logicalHeadValue(); got != headBefore {
|
||||
t.Fatalf("WAL head %d -> %d after a refused %s", headBefore, got, p.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// heldMetadata blocks BeforeCheckpointAdvance once armed.
|
||||
type heldMetadata struct {
|
||||
armed atomic.Bool
|
||||
@@ -294,100 +142,6 @@ func (m *heldMetadata) BeforeCheckpointAdvance(uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// A direct-frontier publication must not complete after the flusher's
|
||||
// extent fsync failed, even when that failure lands while the publication
|
||||
// is past its fault check (in its metadata barrier).
|
||||
func TestWALStoreExtentFsyncFaultDuringDirectFrontierPublication(t *testing.T) {
|
||||
s, path := heldStore(t)
|
||||
meta := &heldMetadata{g: newGate(t)}
|
||||
s.metadata = meta
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ckptBefore, diskBefore := s.CheckpointLSN(), diskCheckpoint(t, path)
|
||||
|
||||
extentGate := newGate(t)
|
||||
eio := errors.New("injected extent fsync failure")
|
||||
s.syncExtentFile = func() error { extentGate.block(); return eio }
|
||||
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, extentGate, meta.g)
|
||||
extentGate.waitEntered(t, "the flusher's extent fsync")
|
||||
|
||||
meta.armed.Store(true)
|
||||
s.AdvanceFrontier(10)
|
||||
errSync := startWorker(t, func() error {
|
||||
_, err := s.Sync()
|
||||
return err
|
||||
}, extentGate, meta.g)
|
||||
inBarrier := meta.g.enteredWithin(300 * time.Millisecond)
|
||||
extentGate.open() // the extent fsync fails and latches the fault
|
||||
if err := recvErr(t, errFlush, "the flush"); !errors.Is(err, eio) {
|
||||
t.Fatalf("flush: %v; want the injected extent fault", err)
|
||||
}
|
||||
meta.g.open()
|
||||
err := recvErr(t, errSync, "the direct-frontier Sync")
|
||||
t.Logf("Sync reached its metadata barrier before the fault: %t", inBarrier)
|
||||
if !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("direct-frontier Sync after the extent fsync failed: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != ckptBefore {
|
||||
t.Fatalf("checkpoint %d -> %d after the fault", ckptBefore, got)
|
||||
}
|
||||
if got := diskCheckpoint(t, path); got != diskBefore {
|
||||
t.Fatalf("superblock checkpoint %d -> %d after the fault", diskBefore, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A checkpoint publication must not complete after a WAL fsync failed, even
|
||||
// when that failure lands while the flusher is past its fault check (in its
|
||||
// metadata barrier).
|
||||
func TestWALStoreWALFsyncFaultDuringCheckpointPublication(t *testing.T) {
|
||||
s, path := heldStore(t)
|
||||
meta := &heldMetadata{g: newGate(t)}
|
||||
s.metadata = meta
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil { // dirty WAL
|
||||
t.Fatal(err)
|
||||
}
|
||||
ckptBefore, diskBefore := s.CheckpointLSN(), diskCheckpoint(t, path)
|
||||
|
||||
walGate := newGate(t)
|
||||
fault := errors.New("injected WAL fsync failure")
|
||||
s.syncWALFile = func() error { walGate.block(); return fault }
|
||||
errSync := startWorker(t, func() error {
|
||||
_, err := s.Sync()
|
||||
return err
|
||||
}, walGate, meta.g)
|
||||
walGate.waitEntered(t, "the WAL fsync")
|
||||
|
||||
meta.armed.Store(true)
|
||||
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, walGate, meta.g)
|
||||
inBarrier := meta.g.enteredWithin(300 * time.Millisecond)
|
||||
walGate.open() // the WAL fsync fails and latches the fault
|
||||
if err := recvErr(t, errSync, "the Sync"); !errors.Is(err, fault) {
|
||||
t.Fatalf("Sync: %v; want the injected WAL fault", err)
|
||||
}
|
||||
meta.g.open()
|
||||
err := recvErr(t, errFlush, "the flush")
|
||||
t.Logf("the flusher reached its metadata barrier before the fault: %t", inBarrier)
|
||||
if !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("flush after the WAL fsync failed: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != ckptBefore {
|
||||
t.Fatalf("checkpoint %d -> %d after the fault", ckptBefore, got)
|
||||
}
|
||||
if got := diskCheckpoint(t, path); got != diskBefore {
|
||||
t.Fatalf("superblock checkpoint %d -> %d after the fault", diskBefore, got)
|
||||
}
|
||||
}
|
||||
|
||||
// extentHeldMetadata blocks the first OnExtentWrite (the flusher after its
|
||||
// snapshot, before its extent fsync) and, once armed, BeforeCheckpointAdvance.
|
||||
type extentHeldMetadata struct {
|
||||
@@ -411,135 +165,6 @@ func (m *extentHeldMetadata) BeforeCheckpointAdvance(uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// The fault check at the publication's own superblock fsync: a direct-
|
||||
// frontier Sync is already in its metadata barrier (past every earlier
|
||||
// check) when the flusher's extent fsync fails; its superblock publication
|
||||
// must be refused.
|
||||
func TestWALStoreExtentFsyncFaultAfterThePublicationCheck(t *testing.T) {
|
||||
s, path := heldStore(t)
|
||||
meta := &extentHeldMetadata{extent: newGate(t), barrier: newGate(t)}
|
||||
s.metadata = meta
|
||||
if _, err := s.Write(1, makeBlock(4096, 0x11)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ckptBefore, diskBefore := s.CheckpointLSN(), diskCheckpoint(t, path)
|
||||
|
||||
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, meta.extent, meta.barrier)
|
||||
meta.extent.waitEntered(t, "the flusher's extent write") // before its extent fsync
|
||||
|
||||
meta.armed.Store(true)
|
||||
s.AdvanceFrontier(10)
|
||||
errSync := startWorker(t, func() error {
|
||||
_, err := s.Sync()
|
||||
return err
|
||||
}, meta.extent, meta.barrier)
|
||||
meta.barrier.waitEntered(t, "the Sync's metadata barrier") // past the store-lock check
|
||||
|
||||
eio := errors.New("injected extent fsync failure")
|
||||
s.syncExtentFile = func() error { return eio }
|
||||
meta.extent.open()
|
||||
if err := recvErr(t, errFlush, "the flush"); !errors.Is(err, eio) {
|
||||
t.Fatalf("flush: %v; want the injected extent fault", err)
|
||||
}
|
||||
meta.barrier.open()
|
||||
if err := recvErr(t, errSync, "the direct-frontier Sync"); !errors.Is(err, ErrFsyncFailed) {
|
||||
t.Fatalf("Sync whose barrier outlived the extent fault: %v; want ErrFsyncFailed", err)
|
||||
}
|
||||
if got := s.CheckpointLSN(); got != ckptBefore {
|
||||
t.Fatalf("checkpoint %d -> %d after the fault", ckptBefore, got)
|
||||
}
|
||||
if got := diskCheckpoint(t, path); got != diskBefore {
|
||||
t.Fatalf("superblock checkpoint %d -> %d after the fault", diskBefore, got)
|
||||
}
|
||||
}
|
||||
|
||||
// No two fsyncs of the store's file overlap: an extent fsync waits for a
|
||||
// WAL fsync in flight (so a failure of either is latched before the other
|
||||
// can complete as a success).
|
||||
func TestWALStoreFsyncsOfTheFileAreSerialized(t *testing.T) {
|
||||
s, _ := heldStore(t)
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
walGate := newGate(t)
|
||||
real := s.syncWALFile
|
||||
s.syncWALFile = func() error { walGate.block(); return real() }
|
||||
errSync := startWorker(t, func() error {
|
||||
_, err := s.Sync()
|
||||
return err
|
||||
}, walGate)
|
||||
walGate.waitEntered(t, "the WAL fsync")
|
||||
|
||||
extentEntered := make(chan struct{})
|
||||
var once sync.Once
|
||||
realExtent := s.syncExtentFile
|
||||
s.syncExtentFile = func() error { once.Do(func() { close(extentEntered) }); return realExtent() }
|
||||
arrived := make(chan struct{})
|
||||
var arriveOnce sync.Once
|
||||
s.testBeforeFileSync = func() { arriveOnce.Do(func() { close(arrived) }) } // the next syncFile caller: the flusher
|
||||
errFlush := startWorker(t, func() error { return s.flusher.flushOnce() }, walGate)
|
||||
select { // the flusher reached the serialization boundary...
|
||||
case <-arrived:
|
||||
case <-time.After(holdBound):
|
||||
t.Fatal("the flusher never reached the file sync boundary")
|
||||
}
|
||||
select { // ...and does not pass it while the WAL fsync is in flight
|
||||
case <-extentEntered:
|
||||
t.Fatal("the extent fsync ran while a WAL fsync of the same file was in flight")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
walGate.open()
|
||||
if err := recvErr(t, errSync, "the Sync"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := recvErr(t, errFlush, "the flush"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-extentEntered:
|
||||
default:
|
||||
t.Fatal("the extent fsync never ran")
|
||||
}
|
||||
}
|
||||
|
||||
// The failure path's cleanup settles: a test that stops (here SkipNow, which
|
||||
// ends the test the same way as Fatal) while a worker is held inside the
|
||||
// store still opens the gate, joins the worker and then closes the store.
|
||||
func TestWALStoreHeldWorkersSettleOnAFailurePath(t *testing.T) {
|
||||
var s *WALStore
|
||||
var res <-chan error
|
||||
t.Run("stops-while-held", func(t *testing.T) {
|
||||
s, _ = heldStore(t)
|
||||
if _, err := s.Write(0, makeBlock(4096, 0x10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := newGate(t)
|
||||
// After its gate opens the flush still takes a while, so only a
|
||||
// cleanup that joins it (not one that just opens the gate) sees it end.
|
||||
s.syncExtentFile = func() error { g.block(); time.Sleep(200 * time.Millisecond); return nil }
|
||||
res = startWorker(t, func() error { return s.flusher.flushOnce() }, g)
|
||||
g.waitEntered(t, "the held flush")
|
||||
t.SkipNow() // leaves the flush held inside the store
|
||||
})
|
||||
select {
|
||||
case err := <-res:
|
||||
if err != nil {
|
||||
t.Fatalf("held flush after cleanup: %v", err)
|
||||
}
|
||||
default:
|
||||
t.Fatal("cleanup returned while the held flush was still running")
|
||||
}
|
||||
s.mu.RLock()
|
||||
closed := s.closed
|
||||
s.mu.RUnlock()
|
||||
if !closed {
|
||||
t.Fatal("cleanup did not close the store")
|
||||
}
|
||||
}
|
||||
|
||||
// leakRecorder records cleanups and errors in place of a *testing.T.
|
||||
type leakRecorder struct {
|
||||
mu sync.Mutex
|
||||
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user