Merge remote-tracking branch 'origin/main' into test/single-volume-master-loss

This commit is contained in:
pingqiu committed 2026-11-22 22:42:30 -08:00
commit 5400298ca2
37 files changed
+3824 -201

No files matched your search

@@ -152,7 +152,6 @@ func TestDurableStartup_Issue51_SmartWALTornTailRecovers(t *testing.T) {
// V3 replaces the legacy warning-only recovery policy with nonce-bound,
// contiguous WAL recovery. Corruption below strict W must block readiness.
// The old v2 warning control is retained in walstore_midhistory_hole_test.go.
func TestDurableStartup_Issue51_WALStoreV3CommittedHoleBlocksReadiness(t *testing.T) {
const childEnv = "SWBLOCK_V3_STARTUP_CRASH_PATH"
if path := os.Getenv(childEnv); path != "" {
@@ -185,10 +185,13 @@ type handoffEnv struct {
}
// bvHost is one host's blockvolume: its server id, endpoints, local root
// and the volume it serves (v1 when empty).
// and the volume it serves (v1 when empty). server and replica, when set,
// replace id as the server id and r1 as the replica id (several volumes
// under one server id).
type bvHost struct {
id, data, ctrl, status, nvme, root string
volume string
server, replica string
}
// startHandoffEnv runs the chapter's steps 1-3: a weed cluster, the cluster
@@ -267,11 +270,17 @@ func (env *handoffEnv) volArgs(id string) []string { return env.volArgsFor(env.h
func (env *handoffEnv) volArgsFor(b bvHost) []string {
lockDir := b.root + ".locks" // each simulated host has its own
_ = os.MkdirAll(lockDir, 0o700)
vol := b.volume
vol, server, replica := b.volume, b.server, b.replica
if vol == "" {
vol = "v1"
}
return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", b.id, "--volume-id", vol, "--replica-id", "r1",
if server == "" {
server = b.id
}
if replica == "" {
replica = "r1"
}
return append([]string{"--volume-lock-dir-test-only", lockDir, "--master", env.h.masterAddr, "--server-id", server, "--volume-id", vol, "--replica-id", replica,
"--data-addr", b.data, "--ctrl-addr", b.ctrl, "--status-addr", b.status,
"--durable-root", b.root, "--durable-impl", "walstore-chunk",
"--durable-blocks", "65536", "--durable-blocksize", "4096",
@@ -0,0 +1,442 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"fmt"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
)
// Single-volume coverage, gap 1 (cell A2.4, V1-SPEC r2.55): kill -9 of the
// holder WITH guest I/O in flight, then a restart inside the lease. Every
// write a Flush acknowledged must read back after the restart
// (INV-WAL-SYNCED-RECOVERED-001); writes not yet acknowledged by a Flush may
// vanish, but what is left of them must be a prefix of the stream in LBA
// order with nothing torn or invented (the writer writes LBAs in order).
//
// The writer is the guest: qd1 NVMe/TCP writes of distinct blocks, a Flush
// every crashIOFlushEvery writes; it records the last LBA a successful
// Flush covered. The holder is killed while the writer is mid-stream.
const (
crashIOBase = 2048 // first LBA the writer uses (chunk 2)
crashIOSpan = 40000
crashIOFlushEvery = 8
)
func crashIOBlock(lba uint64) []byte {
s := fmt.Sprintf("crash-io lba %08d|", lba)
b := make([]byte, 4096)
for i := range b {
b[i] = s[i%len(s)]
}
return b
}
// crashIOWriter writes LBAs crashIOBase.. in order until stopped or an I/O
// fails, and reports how far the Flush acknowledgements reached.
type crashIOWriter struct {
mu sync.Mutex
written int // writes completed (acknowledged by the write itself)
flushed int // writes covered by an acknowledged Flush
err error
done chan struct{}
}
func startCrashIOWriter(t *testing.T, env *handoffEnv, id string) *crashIOWriter {
t.Helper()
w := &crashIOWriter{done: make(chan struct{})}
c := dialNVMe(t, env.hosts[id].nvme, plannedHandoffNQN)
go func() {
defer close(w.done)
defer c.close()
for n := 0; n < crashIOSpan; n++ {
lba := crashIOBase + uint64(n)
err := c.tryWrite(lba, crashIOBlock(lba))
if err == nil && n%crashIOFlushEvery == crashIOFlushEvery-1 {
err = c.tryFlush()
if err == nil {
w.mu.Lock()
w.flushed = n + 1
w.mu.Unlock()
}
}
w.mu.Lock()
if err != nil {
w.err = err
} else {
w.written = n + 1
}
w.mu.Unlock()
if err != nil {
return
}
}
}()
return w
}
func (w *crashIOWriter) counts() (written, flushed int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.written, w.flushed, w.err
}
func TestProcedureCrashWithIOInFlight(t *testing.T) {
env := startHandoffEnv(t, 1)
first := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, first, "s1")
w := startCrashIOWriter(t, env, "s1")
// Let the stream run until a good number of Flushes acknowledged, so the
// kill lands mid-stream with writes in flight.
poll(t, 60*time.Second, "the writer never got 2000 flushed writes", func() bool {
_, flushed, err := w.counts()
return flushed >= 2000 || err != nil
})
if _, _, err := w.counts(); err != nil {
t.Fatalf("a write failed before the kill: %v", err)
}
first.kill(t) // SIGKILL while the writer is still writing
select {
case <-w.done:
case <-time.After(70 * time.Second):
t.Fatal("the writer did not stop after the holder was killed")
}
written, flushed, werr := w.counts()
if werr == nil {
t.Fatalf("the writer finished all %d writes before the kill: no I/O was in flight", crashIOSpan)
}
t.Logf("at the kill: %d writes completed, %d covered by an acknowledged Flush; the writer's error: %v", written, flushed, werr)
again := env.start(t, "blockvolume-s1-again", "s1")
if got := env.adopt(t, again, "s1"); got != e {
t.Fatalf("the restarted holder adopted epoch %d; want %d", got, e)
}
c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN)
defer c.close()
zero := make([]byte, 4096)
for n := 0; n < flushed; n++ {
lba := crashIOBase + uint64(n)
if got := c.read(t, lba, 4096); !bytes.Equal(got, crashIOBlock(lba)) {
t.Fatalf("flush-acknowledged write %d (LBA %d) is lost or wrong after kill -9 and restart", n, lba)
}
}
// Past the Flush acknowledgements: a prefix of the stream, then zeros.
kept, ended := flushed, false
for n := flushed; n < written+crashIOFlushEvery && n < crashIOSpan; n++ {
lba := crashIOBase + uint64(n)
got := c.read(t, lba, 4096)
switch {
case !ended && bytes.Equal(got, crashIOBlock(lba)):
kept++
case bytes.Equal(got, zero):
ended = true
default:
t.Fatalf("LBA %d after the last acknowledged Flush holds data out of the stream's order or torn (kept %d)", lba, kept)
}
}
t.Logf("after the restart: all %d flush-acknowledged writes read back; %d writes past the last acknowledged Flush survived as a prefix (%d had completed; one in flight may persist without its reply)", flushed, kept-flushed, written-flushed)
}
// Gap 1, cell A3.5: kill -9 of a holder serving on a FRESH root (after a
// clean move) while chunk fills from HEAD are in flight. s1 writes one block
// in each of the first fillChunks chunks; after the hand-over, s2 starts
// with no local copy. A reader walks those chunks (each read misses and
// fills) while a writer streams Flush-acknowledged writes into chunks s1
// never wrote; s2 is SIGKILLed mid-walk and restarted. Every s1 block must
// read back (the fills are redone from HEAD) and every acknowledged s2 write
// must survive.
const (
fillChunks = 60
fillWriterBase = 60 * ladderChunkBlocks
fillWriterSpan = 4 * ladderChunkBlocks
fillFlushEvery = 8
)
func fillSourceBlock(c int) []byte {
s := fmt.Sprintf("fill-src chunk %03d|", c)
b := make([]byte, 4096)
for i := range b {
b[i] = s[i%len(s)]
}
return b
}
func TestProcedureCrashOnAFreshRootWithFillsInFlight(t *testing.T) {
env := startHandoffEnv(t, 2)
must, mustU := fatalOn(t)
h := env.h
old := env.start(t, "blockvolume-s1", "s1")
e := env.adopt(t, old, "s1")
for c := 0; c < fillChunks; c++ {
env.writeBlock(t, "s1", uint64(c*ladderChunkBlocks), fillSourceBlock(c))
}
g := env.seal(t, "s1", e)
l := env.sealedLSN(t, e, g)
env.revoke(t, e, g)
if err := old.wait(30 * time.Second); err != nil {
t.Fatalf("s1 after the revocation: %v", err)
}
env.waitAck(t, e, g)
moved, _ := h.command(t, env.moveClean(e, "s2", "move-v1-1")...)
e2 := mustU(movedEpochTo(moved, e, g, l, "s2"))
nw := env.start(t, "blockvolume-s2", "s2")
must(checkClaimDoneBy(nw.waitLog(t, 60*time.Second, "durable: HEAD claim for volume=v1 done in"), e2, "s2"))
if got := env.adopt(t, nw, "s2"); got != e2 {
t.Fatalf("s2 adopted at epoch %d; want %d", got, e2)
}
// The reader: read misses fill each source chunk from HEAD.
var rmu sync.Mutex
reads, readErr := 0, error(nil)
readerDone := make(chan struct{})
rc := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN)
go func() {
defer close(readerDone)
defer rc.close()
for c := 0; c < fillChunks; c++ {
_, err := rc.tryRead(uint64(c*ladderChunkBlocks), 4096)
rmu.Lock()
if err != nil {
readErr = err
rmu.Unlock()
return
}
reads = c + 1
rmu.Unlock()
}
}()
// The writer: acknowledged local writes into chunks s1 never wrote.
var wmu sync.Mutex
written, flushed := 0, 0
writerDone := make(chan struct{})
wc := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN)
go func() {
defer close(writerDone)
defer wc.close()
for n := 0; n < fillWriterSpan; n++ {
lba := uint64(fillWriterBase + n)
err := wc.tryWrite(lba, crashIOBlock(lba))
if err == nil && n%fillFlushEvery == fillFlushEvery-1 {
if err = wc.tryFlush(); err == nil {
wmu.Lock()
flushed = n + 1
wmu.Unlock()
}
}
if err != nil {
return
}
wmu.Lock()
written = n + 1
wmu.Unlock()
}
}()
poll(t, 60*time.Second, "s2 never got its first fills and acknowledged writes", func() bool {
rmu.Lock()
r := reads
rmu.Unlock()
wmu.Lock()
f := flushed
wmu.Unlock()
return r >= 3 && f >= 8
})
nw.kill(t) // SIGKILL with fills and writes in flight
<-readerDone
<-writerDone
rmu.Lock()
readsAtKill, rerr := reads, readErr
rmu.Unlock()
wmu.Lock()
writtenAtKill, flushedAtKill := written, flushed
wmu.Unlock()
if readsAtKill >= fillChunks {
t.Fatalf("the reader finished all %d fills before the kill: no fill was in flight", fillChunks)
}
t.Logf("at the kill: %d of %d source chunks read (filled), reader error %v; %d writes completed, %d covered by a Flush", readsAtKill, fillChunks, rerr, writtenAtKill, flushedAtKill)
again := env.start(t, "blockvolume-s2-again", "s2")
if got := env.adopt(t, again, "s2"); got != e2 {
t.Fatalf("the restarted s2 adopted epoch %d; want %d", got, e2)
}
c := dialNVMe(t, env.hosts["s2"].nvme, plannedHandoffNQN)
defer c.close()
for k := 0; k < fillChunks; k++ {
if got := c.read(t, uint64(k*ladderChunkBlocks), 4096); !bytes.Equal(got, fillSourceBlock(k)) {
t.Fatalf("source chunk %d (filled before the kill: %t) does not read back after the restart", k, k < readsAtKill)
}
}
for n := 0; n < flushedAtKill; n++ {
lba := uint64(fillWriterBase + n)
if got := c.read(t, lba, 4096); !bytes.Equal(got, crashIOBlock(lba)) {
t.Fatalf("flush-acknowledged write %d (LBA %d) on the fresh root is lost after kill -9 and restart", n, lba)
}
}
t.Logf("after the restart: all %d source chunks and all %d flush-acknowledged writes read back", fillChunks, flushedAtKill)
}
// tryRead is read returning the error (for readers off the test goroutine).
func (c *nvmeInitiator) tryRead(lba uint64, n int) ([]byte, error) {
cmd := c.ioCmd(0x02, lba, n/4096)
if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil {
return nil, fmt.Errorf("nvme Read: %w", err)
}
var data []byte
for {
ch, err := c.r.Dequeue()
if err != nil {
return nil, fmt.Errorf("nvme Read: %w", err)
}
if ch.Type == 0x5 {
var resp nvme.CapsuleResponse
if err := c.r.Receive(&resp); err != nil {
return nil, fmt.Errorf("nvme Read response: %w", err)
}
if resp.Status != 0 {
return nil, fmt.Errorf("nvme Read status 0x%04x", resp.Status)
}
break
}
if ch.Type != 0x7 {
return nil, fmt.Errorf("nvme Read: unexpected PDU type 0x%x", ch.Type)
}
var dh nvme.C2HDataHeader
if err := c.r.Receive(&dh); err != nil {
return nil, fmt.Errorf("nvme C2HData: %w", err)
}
part := make([]byte, c.r.Length())
if err := c.r.ReceiveData(part); err != nil {
return nil, fmt.Errorf("nvme C2HData payload: %w", err)
}
data = append(data, part...)
}
if len(data) != n {
return nil, fmt.Errorf("nvme Read returned %d bytes; want %d", len(data), n)
}
return data, nil
}
// Gap 2, procedure part (cells P8.7, P9.4, P11.3): kill -9 of the holder
// during a cut's upload, with real binaries. Image A is cut; every block is
// rewritten and a second cut starts; the holder is SIGKILLed after a delay.
// The kill counts as mid-upload only if chunk objects of the second cut
// reached the filer while HEAD stayed at the first cut's generation; else the
// delay is adapted (shorter if the cut had committed, longer if nothing was
// uploaded) and the step repeats with a new image, up to cutCrashAttempts
// times. After the mid-upload kill and a restart: HEAD verifies whole at
// depth data, every block reads the last image locally, and the next cut,
// read back through a snapshot restored into a new volume, is that image.
const cutCrashAttempts = 6
const (
cutCrashChunks = 48
cutCrashPer = 64 // blocks written per chunk
)
func cutCrashBlock(img byte, lba uint64) []byte {
s := fmt.Sprintf("cut-crash %c lba %08d|", img, lba)
b := make([]byte, 4096)
for i := range b {
b[i] = s[i%len(s)]
}
return b
}
func (env *handoffEnv) writeCutCrashImage(t *testing.T, img byte) {
t.Helper()
c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN)
defer c.close()
for ch := 0; ch < cutCrashChunks; ch++ {
for i := 0; i < cutCrashPer; i++ {
lba := uint64(ch*ladderChunkBlocks + i)
c.write(t, lba, cutCrashBlock(img, lba))
}
}
c.flush(t)
}
func (env *handoffEnv) requireCutCrashImage(t *testing.T, hostID string, img byte) {
t.Helper()
c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN)
defer c.close()
for ch := 0; ch < cutCrashChunks; ch++ {
for i := 0; i < cutCrashPer; i++ {
lba := uint64(ch*ladderChunkBlocks + i)
if got := c.read(t, lba, 4096); !bytes.Equal(got, cutCrashBlock(img, lba)) {
t.Fatalf("%s: LBA %d is not image %c", hostID, lba, img)
}
}
}
}
func TestProcedureCrashDuringACut(t *testing.T) {
env := startHandoffEnvWith(t, 1, []string{"v2"})
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
holder := env.start(t, "blockvolume-v1", "s1")
e := env.adopt(t, holder, "s1")
cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status}
verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
headGen := func() uint64 {
out, _ := env.h.command(t, env.chunkShow()...)
h, err := parseHead(out)
if err != nil {
t.Fatal(err)
}
return h.Gen
}
env.writeCutCrashImage(t, 'A')
cutStart := time.Now()
env.h.command(t, cut...)
delay := time.Since(cutStart) / 2
img, landed := byte('A'), false
for attempt := 1; attempt <= cutCrashAttempts && !landed; attempt++ {
img++
env.writeCutCrashImage(t, img)
gen, entries := headGen(), f1FilerEntries(t, env)
done := make(chan int, 1)
go func() {
_, _, code := env.h.run(t, cut...)
done <- code
}()
time.Sleep(delay)
holder.kill(t)
code := <-done
uploaded := f1FilerEntries(t, env) - entries
after := headGen()
switch {
case after != gen:
t.Logf("attempt %d: the cut committed before the kill at %s (HEAD gen %d -> %d, CLI exit %d); shorter", attempt, delay, gen, after, code)
delay /= 2
case uploaded <= 0:
t.Logf("attempt %d: nothing was uploaded before the kill at %s; longer", attempt, delay)
delay *= 2
default:
landed = true
t.Logf("attempt %d: killed at %s mid-upload: %d new filer entries, HEAD still gen %d (CLI exit %d)", attempt, delay, uploaded, gen, code)
}
if out, errOut, rc := env.h.run(t, verify...); rc != 0 {
t.Fatalf("attempt %d: HEAD is not whole after the kill (verify exit %d):\n%s\n%s", attempt, rc, out, errOut)
}
holder = env.start(t, fmt.Sprintf("blockvolume-v1-%d", attempt), "s1")
if got := env.adopt(t, holder, "s1"); got != e {
t.Fatalf("attempt %d: the restarted holder adopted epoch %d; want %d", attempt, got, e)
}
env.requireCutCrashImage(t, "s1", img)
}
if !landed {
t.Fatalf("no kill landed mid-upload in %d attempts", cutCrashAttempts)
}
env.h.command(t, cut...)
env.snapshot(t, "s1", "v1", "after-crash")
env.restoreInto(t, "v1", "after-crash", "v2")
env.requireCutCrashImage(t, "n-v2", img)
}
@@ -0,0 +1,256 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"path"
"testing"
"time"
)
// restoreProgress is the restore driver's status of a target.
type restoreProgress struct {
Phase string `json:"phase"`
Running bool `json:"running"`
Filled int `json:"filled"`
Owned int `json:"owned"`
Foreign int `json:"foreign"`
Batches int `json:"batches"`
}
// restoreStatus reads target's restore status straight from its status
// server (a GET answers the status without starting a run).
func (env *handoffEnv) restoreStatus(c *http.Client, target string) (restoreProgress, string, bool) {
resp, err := c.Get("http://" + env.hosts["n-"+target].status + "/chunk/restore?volume=" + target)
if err != nil {
return restoreProgress{}, "", false
}
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
var st restoreProgress
if resp.StatusCode != http.StatusOK || json.Unmarshal(b, &st) != nil {
return restoreProgress{}, string(b), false
}
return st, string(b), true
}
// awaitRestorePhase polls target's restore status every 10 ms until ok
// holds and returns that status, logging each change with when it was seen
// (the record of where a kill landed). It fails the test if the restore
// failed, became independent first (the moment was missed), or bound passed.
// The driver's counters (filled, owned, foreign) are written when a step
// ends, not while it runs: a moment inside a step is chosen by the phase and
// the time spent in it, not by a counter.
func (env *handoffEnv) awaitRestorePhase(t *testing.T, target, what string, bound time.Duration, ok func(restoreProgress) bool) restoreProgress {
t.Helper()
c := &http.Client{Timeout: 2 * time.Second}
began := time.Now()
last := restoreProgress{Phase: "-"}
for time.Since(began) < bound {
if st, raw, good := env.restoreStatus(c, target); good {
if st != last {
t.Logf("restore of %s at +%v (waiting for %s): %+v", target, time.Since(began).Round(time.Millisecond), what, st)
last = st
}
switch {
case ok(st):
return st
case st.Phase == "failed":
t.Fatalf("restore of %s failed waiting for %s: %s", target, what, raw)
case st.Phase == "independent":
t.Fatalf("restore of %s became independent before %s was seen (the restore is too small to catch it): %s", target, what, raw)
}
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("restore of %s: %s not seen within %v", target, what, bound)
return restoreProgress{}
}
// requireRestoreState reads target's restore status once and fails the test
// unless the run is still going and ok holds: the check, right before a
// kill, that the kill lands where the test says.
func (env *handoffEnv) requireRestoreState(t *testing.T, target, what string, ok func(restoreProgress) bool) restoreProgress {
t.Helper()
st, raw, good := env.restoreStatus(&http.Client{Timeout: 2 * time.Second}, target)
if !good || !st.Running || !ok(st) {
t.Fatalf("restore of %s is no longer %s before the kill: %s", target, what, raw)
}
return st
}
// requireBlocksOf reads every block of img on the host and requires each to
// equal img (whole 4 KiB blocks compared byte for byte).
func (env *handoffEnv) requireBlocksOf(t *testing.T, hostID string, img map[uint64][]byte) {
t.Helper()
c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN)
defer c.close()
for lba, want := range img {
if got := c.read(t, lba, 4096); string(got) != string(want) {
t.Fatalf("%s: block %d differs from what was written", hostID, lba)
}
}
}
// denseImage fills every block of the given chunks with incompressible
// bytes (seeded by tag and LBA), so that their chunks are full size in the
// store and a restore of them takes measurable time at the driver's rate.
func denseImage(tag string, chunks []uint64) map[uint64][]byte {
img := map[uint64][]byte{}
var seed int64
for _, c := range tag {
seed = seed*31 + int64(c)
}
for _, c := range chunks {
for i := uint64(0); i < ladderChunkBlocks; i++ {
lba := c*ladderChunkBlocks + i
b := make([]byte, 4096)
rand.New(rand.NewSource(seed ^ int64(lba))).Read(b)
img[lba] = b
}
}
return img
}
// independent reports whether target's independence marker exists, read
// from the filer (not through the product's status, which reports only a
// run of this process).
func (env *handoffEnv) independent(t *testing.T, target string) bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
p := path.Join(env.chunkPath, target, "RESTORE-INDEPENDENT")
resp, err := c.Get("http://" + env.cluster.filerHTTP + p + "?metadata=true")
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true
case http.StatusNotFound:
return false
}
t.Fatalf("filer lookup of %s: status %d", p, resp.StatusCode)
return false
}
// subsetOf returns the blocks of img in the given chunks.
func subsetOf(img map[uint64][]byte, chunks []uint64) map[uint64][]byte {
in := map[uint64]bool{}
for _, c := range chunks {
in[c] = true
}
out := map[uint64][]byte{}
for lba, b := range img {
if in[lba/ladderChunkBlocks] {
out[lba] = b
}
}
return out
}
// startTarget starts target's blockvolume and waits until it serves.
func (env *handoffEnv) startTarget(t *testing.T, target, name string) *daemon {
t.Helper()
b := env.hosts["n-"+target]
d := env.h.start(t, name, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target))
poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool {
return volumeFrontendReady(b.status, target)
})
return d
}
// TestSnapshotLadderC3KilledHydratingAndBeforeIndependence: a restore of a
// snapshot of 32 full chunks of incompressible data into v2 (128 MiB to make
// local at the driver's 64 MiB/s: about 2 s of hydrating).
//
// 1. Its blockvolume is killed (SIGKILL) one second into hydrating and
// started again. Every other chunk is read back (a partly filled chunk
// must never be served), which makes those chunks local and leaves the
// rest to the driver, and the driver is started again.
// 2. The resumed run must report, when its hydrating step ends, that it
// filled some chunks and not all (0 < filled < 32: it resumed from a
// partly local volume). Then, the run still going and not independent,
// the guest writes to v2 (acknowledged); checked still running and not
// independent, the blockvolume is killed again and restarted. Before the
// driver is started again the independence marker must be absent (the
// kill landed before independence); every acknowledged write reads back.
// 3. The driver is started again, the guest writes once more, and the run
// reaches independence (per its status and the marker). Then v2 holds
// the snapshot with every acknowledged write over it, read back in full,
// and the source's snapshot, restored again into v3, is unchanged (none
// of v2's writes in it).
//
// Not covered: guest writes while the driver reports Owning. The status
// shows owning only once the single batch (32 chunks, under the 64-chunk
// batch) has ended, a few ms before independent.
func TestSnapshotLadderC3KilledHydratingAndBeforeIndependence(t *testing.T) {
env := startLadderEnv(t, "v2", "v3")
var chunks []uint64
for c := uint64(0); c < 32; c++ {
chunks = append(chunks, c)
}
src := denseImage("c3ksrc", chunks)
env.writeImage(t, "s1", src)
env.snapshot(t, "s1", "v1", "base")
env.h.command(t, "ops", "chunk", "restore", "--source", "v1", "--snapshot", "base", "--target", "v2",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
target := env.startTarget(t, "v2", "blockvolume-v2")
drive := func() {
t.Helper()
env.h.command(t, "ops", "chunk", "restore", "--volume", "v2", "--status-addr", env.hosts["n-v2"].status)
}
drive()
// Killed one second into hydrating.
env.awaitRestorePhase(t, "v2", "hydrating", 120*time.Second, func(s restoreProgress) bool { return s.Phase == "hydrating" })
time.Sleep(time.Second)
st := env.requireRestoreState(t, "v2", "hydrating", func(s restoreProgress) bool { return s.Phase == "hydrating" })
target.kill(t)
t.Logf("killed 1 s into hydrating: %+v", st)
target = env.startTarget(t, "v2", "blockvolume-v2-after-hydrate-kill")
var even []uint64
for c := uint64(0); c < 32; c += 2 {
even = append(even, c)
}
env.requireBlocksOf(t, "n-v2", subsetOf(src, even)) // no partly filled chunk is served
drive()
// The resumed run: it fills what is not local yet; then, before
// independence, written and killed.
notDone := func(s restoreProgress) bool { return s.Phase != "independent" }
st = env.awaitRestorePhase(t, "v2", "the resumed run's hydrating step ended", 60*time.Second, func(s restoreProgress) bool {
return s.Running && s.Filled > 0 && notDone(s)
})
if st.Filled >= len(chunks) {
t.Fatalf("the resumed run filled %d chunks: it did not resume from a partly local volume (%d read back before it)", st.Filled, len(even))
}
w1 := ladderImage("c3kw1", []uint64{3, 17, 50}, 3)
env.writeImage(t, "n-v2", w1)
st = env.requireRestoreState(t, "v2", "running and not independent", notDone)
target.kill(t)
t.Logf("killed in the resumed run after it filled %d of %d chunks, after the write: %+v", st.Filled, len(chunks), st)
target = env.startTarget(t, "v2", "blockvolume-v2-after-batch-kill")
if env.independent(t, "v2") {
t.Fatal("the independence marker exists after the second kill: the kill did not land before independence")
}
env.requireBlocksOf(t, "n-v2", w1) // every acknowledged write survived the kill
drive()
w2 := ladderImage("c3kw2", []uint64{17, 44, 60}, 2) // not chunk 40: requireEdges keeps it untouched
env.writeImage(t, "n-v2", w2)
env.waitIndependent(t, "v2")
if !env.independent(t, "v2") {
t.Fatal("the restore status says independent but the marker is absent")
}
env.requireImage(t, "n-v2", mergeImages(src, w1, w2))
env.restoreChecked(t, "base", "v3", src, w1, w2)
}
@@ -0,0 +1,390 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"testing"
"time"
)
// Rung D of the snapshot ladder: deletes. D1-D3 are the logical delete: a
// deleted snapshot leaves every other snapshot restorable, whichever one is
// deleted (the newest, a middle one, one whose content recurs later). No
// collector runs in them (a delete only marks the snapshot and frees its
// name), so they prove nothing about reclamation. D4 runs the collector and
// measures what it reclaims.
//
// The collector's grace may not be shorter than the operation deadline plus
// the clock skew plus the CAS apply bound (11 minutes with the defaults), and
// an unreferenced chunk is reclaimed only by a second mark at least the grace
// after the first, on a chunk older than the grace: D4 runs for about 25
// minutes.
const (
ladderGCGrace = 11 * time.Minute
// ladderGCWait is the grace plus the collector's clock skew allowance
// and its one-second timestamp resolution, with a margin.
ladderGCWait = ladderGCGrace + time.Minute + 15*time.Second
)
// deleteSnapshot deletes vol's snapshot name and checks the answer names it.
func (env *handoffEnv) deleteSnapshot(t *testing.T, vol, name string) {
t.Helper()
out, _ := env.h.command(t, "ops", "chunk", "snapshot-delete", "--volume", vol, "--name", name,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
var body struct {
VolumeID string `json:"volumeID"`
Name string `json:"name"`
}
if err := json.Unmarshal([]byte(out), &body); err != nil || body.Name != name {
t.Fatalf("delete %s of %s: %v\n%s", name, vol, err, out)
}
}
// requireSnapshotNames checks vol's snapshot list is exactly names, in order.
func (env *handoffEnv) requireSnapshotNames(t *testing.T, vol string, names ...string) {
t.Helper()
list := env.snapshots(t, vol, "")
ok := len(list) == len(names)
for i := 0; ok && i < len(list); i++ {
ok = list[i].Name == names[i] && list[i].State == "active"
}
if !ok {
t.Fatalf("snapshots of %s: %+v; want exactly %v, active", vol, list, names)
}
}
// restoreChecked restores snap of v1 into target until its status says
// independent and checks it equals img, with every block of later that img
// does not hold reading zero.
func (env *handoffEnv) restoreChecked(t *testing.T, snap, target string, img map[uint64][]byte, later ...map[uint64][]byte) {
t.Helper()
env.restoreInto(t, "v1", snap, target)
env.waitIndependent(t, target)
env.requireImage(t, "n-"+target, img, later...)
}
// TestSnapshotLadderD1DeleteTheNewest: three snapshots over overlapping
// chunks; the newest is deleted; the other two restore as they were.
func TestSnapshotLadderD1DeleteTheNewest(t *testing.T) {
env := startLadderEnv(t, "v2", "v3")
img1 := ladderImage("d1one", []uint64{0, 4}, 4)
img2 := ladderImage("d1two", []uint64{4, 8}, 3)
img3 := ladderImage("d1three", []uint64{0, 8}, 2)
for i, img := range []map[uint64][]byte{img1, img2, img3} {
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))
}
env.deleteSnapshot(t, "v1", "s3")
env.requireSnapshotNames(t, "v1", "s1", "s2")
env.restoreChecked(t, "s1", "v2", img1, img2, img3)
env.restoreChecked(t, "s2", "v3", mergeImages(img1, img2), img3)
}
// TestSnapshotLadderD2DeleteAMiddleOne: four snapshots, each sharing chunks
// with its neighbours; the second is deleted; the first, the third and the
// fourth restore as they were. No collector runs: whether the deleted one's
// chunks that a neighbour still uses would survive collection is not tested
// here.
func TestSnapshotLadderD2DeleteAMiddleOne(t *testing.T) {
env := startLadderEnv(t, "v2", "v3", "v4")
img1 := ladderImage("d2one", []uint64{0, 2}, 4)
img2 := ladderImage("d2two", []uint64{2, 5}, 3) // chunk 2 shared with s1, chunk 5 kept by s3
img3 := ladderImage("d2three", []uint64{0, 9}, 2)
img4 := ladderImage("d2four", []uint64{9, 12}, 2)
for i, img := range []map[uint64][]byte{img1, img2, img3, img4} {
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))
}
env.deleteSnapshot(t, "v1", "s2")
env.requireSnapshotNames(t, "v1", "s1", "s3", "s4")
env.restoreChecked(t, "s1", "v2", img1, img2, img3, img4)
env.restoreChecked(t, "s3", "v3", mergeImages(img1, img2, img3), img4)
env.restoreChecked(t, "s4", "v4", mergeImages(img1, img2, img3, img4))
}
// TestSnapshotLadderD3DeleteWhenContentRecurs: the A, B, A volume of A4
// (one block holds A, then B, then A again, a snapshot after each), then the
// live block is overwritten with C; the first snapshot is deleted; the
// third, whose content equals the first's, and the second restore as they
// were, not as HEAD is now. No collector runs here: this is the logical
// delete and restore, not the reclamation of a recurring chunk.
func TestSnapshotLadderD3DeleteWhenContentRecurs(t *testing.T) {
env := startLadderEnv(t, "v2", "v3")
a, b, c := pattern("ladder-d3-blk-A!"), pattern("ladder-d3-blk-B!"), pattern("ladder-d3-blk-C!")
for i, content := range [][]byte{a, b, a} {
env.writeBlock(t, "s1", 7, content)
env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))
}
env.writeBlock(t, "s1", 7, c) // HEAD now differs from every snapshot
env.deleteSnapshot(t, "v1", "s1")
env.requireSnapshotNames(t, "v1", "s2", "s3")
env.restoreChecked(t, "s3", "v2", map[uint64][]byte{7: a})
env.restoreChecked(t, "s2", "v3", map[uint64][]byte{7: b})
}
// gcObject is one chunk object a collector pass names as eligible.
type gcObject struct {
Volume string `json:"volume"`
Key string `json:"key"`
FID string `json:"fid"`
}
// chunkKeys lists the names (unescaped) of v1's chunk-key bindings, read
// straight from the filer's directory listing, not through the collector.
func (env *handoffEnv) chunkKeys(t *testing.T, vol string) map[string]bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
dir := path.Join(env.chunkPath, vol, "keys") + "/"
keys := map[string]bool{}
for last := ""; ; {
req, _ := http.NewRequest("GET", "http://"+env.cluster.filerHTTP+dir+"?limit=1000&lastFileName="+url.QueryEscape(last), nil)
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
var page struct {
Entries []struct {
FullPath string `json:"FullPath"`
} `json:"Entries"`
LastFileName string `json:"LastFileName"`
ShouldDisplayLoadMore bool `json:"ShouldDisplayLoadMore"`
}
err = json.NewDecoder(resp.Body).Decode(&page)
resp.Body.Close()
if err != nil || resp.StatusCode != http.StatusOK {
t.Fatalf("filer listing of %s: status %d %v", dir, resp.StatusCode, err)
}
for _, e := range page.Entries {
name, err := url.PathUnescape(path.Base(e.FullPath))
if err != nil {
t.Fatalf("chunk key %q: %v", e.FullPath, err)
}
keys[name] = true
}
if !page.ShouldDisplayLoadMore || page.LastFileName == "" || page.LastFileName == last {
return keys
}
last = page.LastFileName
}
}
// objectsByKey indexes collector objects by key and counts the records that
// are not distinct v1 chunk objects (another volume, an empty field, or a
// key or fid named again).
func objectsByKey(objs []gcObject) (map[string]gcObject, int) {
byKey, fids, odd := map[string]gcObject{}, map[string]bool{}, 0
for _, o := range objs {
_, dup := byKey[o.Key]
if o.Volume != "v1" || o.Key == "" || o.FID == "" || fids[o.FID] || dup {
odd++
continue
}
byKey[o.Key], fids[o.FID] = o, true
}
return byKey, odd
}
// requireBudget fails the test before it starts anything when the test
// binary's deadline leaves less than need: a wait cut short by the package
// timeout would skip the harness's cleanup.
func requireBudget(t *testing.T, need time.Duration) {
t.Helper()
if dl, ok := t.Deadline(); ok && time.Until(dl) < need {
t.Fatalf("this test needs %v; the test deadline leaves %v (run with -timeout 45m)", need, time.Until(dl).Round(time.Second))
}
}
// gc runs one collector pass (applying or a preview) and returns the chunk
// objects it found eligible and how many it reclaimed.
func (env *handoffEnv) gc(t *testing.T, apply bool) ([]gcObject, int) {
t.Helper()
args := []string{"ops", "chunk", "gc", "--master", env.h.masterAddr, "--grace", ladderGCGrace.String(),
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
if apply {
args = append(args, "--apply")
}
out, _ := env.h.command(t, args...)
var body struct {
MarkSaved bool `json:"mark_saved"`
UnknownOutcomes []string `json:"unknown_outcomes"`
FailedDeletes []any `json:"failed_deletes"`
WouldDelete []gcObject `json:"would_delete"`
Candidates int
Reclaimed int
}
if err := json.Unmarshal([]byte(out), &body); err != nil || (apply && !body.MarkSaved) || len(body.UnknownOutcomes) != 0 || len(body.FailedDeletes) != 0 {
t.Fatalf("gc pass (apply %v): %v\n%s", apply, err, out)
}
t.Logf("gc pass (apply %v): %d candidates, %d eligible, %d reclaimed", apply, body.Candidates, len(body.WouldDelete), body.Reclaimed)
return body.WouldDelete, body.Reclaimed
}
// exclusiveBytes is what the usage command says deleting snapshot name of vol
// makes eligible for collection: the chunk bytes no other holder references.
func (env *handoffEnv) exclusiveBytes(t *testing.T, vol, name string) uint64 {
t.Helper()
out, _ := env.h.command(t, "ops", "chunk", "usage", "--volume", vol,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
var u struct {
Snapshots []struct {
Name string `json:"name"`
ExclusiveBytes uint64 `json:"exclusiveBytes"`
} `json:"snapshots"`
}
if err := json.Unmarshal([]byte(out), &u); err != nil {
t.Fatalf("usage of %s: %v\n%s", vol, err, out)
}
for _, s := range u.Snapshots {
if s.Name == name {
return s.ExclusiveBytes
}
}
t.Fatalf("usage of %s has no snapshot %s\n%s", vol, name, out)
return 0
}
// blobStored reports whether the weed store still holds the chunk data of
// fid (a volume server answers 200 for it, 404 once it is deleted).
func (env *handoffEnv) blobStored(t *testing.T, fid string) bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
vid, _, ok := strings.Cut(fid, ",")
if !ok {
t.Fatalf("chunk object fid %q has no volume id", fid)
}
resp, err := c.Get("http://" + env.cluster.master + "/dir/lookup?volumeId=" + vid)
if err != nil {
t.Fatal(err)
}
var lookup struct {
Locations []struct {
URL string `json:"url"`
} `json:"locations"`
}
err = json.NewDecoder(resp.Body).Decode(&lookup)
resp.Body.Close()
if err != nil || len(lookup.Locations) == 0 {
t.Fatalf("weed lookup of volume %s: %v %+v", vid, err, lookup)
}
resp, err = c.Get("http://" + lookup.Locations[0].URL + "/" + fid)
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true
case http.StatusNotFound:
return false
}
t.Fatalf("weed read of %s: status %d", fid, resp.StatusCode)
return false
}
// TestSnapshotLadderD4DeleteAllButOneThenCollect is a MEASUREMENT, not a
// pass/fail rung: what the collector reclaims after deletes, against an
// expected set taken independently of it. Three snapshots, each overwriting
// the same four chunks; the third and then the second are deleted. The
// third's chunks are still HEAD's, so the bindings the second's cut created
// (those that appear in the filer between the first and the second
// snapshot) are referenced by nothing. Two collector passes the grace apart
// run; the test reports, in one MEASUREMENT line, how many of the expected
// bindings a preview names and the applying pass reclaims, how many of
// those are gone from the weed store, what else either pass named, and the
// surplus left. It fails only when the harness cannot measure (the setup
// did not create the expected bindings, a command failed) or when data is
// lost: HEAD must still read the newest content and the remaining snapshot
// restore as it was.
//
// What is measured is chunk data in the weed store for the bindings the
// deleted snapshot alone created, not filer entries and not the whole store.
// The known surplus of today's format, not measured:
// - a reclaimed binding's filer entry is kept for ever (marked reclaimed),
// so filer entry counts and usage's stored bindings and stored bytes do
// not fall after collection;
// - a needle uploaded before its binding was written (a retried upload)
// cannot be enumerated and is never reclaimed;
// - disk space returns only when weed compacts its volume.
func TestSnapshotLadderD4DeleteAllButOneThenCollect(t *testing.T) {
requireBudget(t, 2*ladderGCWait+10*time.Minute)
env := startLadderEnv(t, "v2")
chunks := []uint64{0, 1, 2, 3}
imgs := []map[uint64][]byte{ladderImage("d4one", chunks, 4), ladderImage("d4two", chunks, 4), ladderImage("d4three", chunks, 4)}
uploads := make([]int, len(imgs))
keysAfter := make([]map[string]bool, len(imgs))
for i, img := range imgs {
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1))
uploads[i] = env.lastCutUploads(t, "s1", "v1")
keysAfter[i] = env.chunkKeys(t, "v1")
}
expected := map[string]bool{} // the bindings the second snapshot's cut created
for k := range keysAfter[1] {
if !keysAfter[0][k] {
expected[k] = true
}
}
t.Logf("the second snapshot's cut uploaded %d chunks and created %d bindings", uploads[1], len(expected))
if len(expected) < len(chunks) {
t.Fatalf("the second snapshot's cut created %d bindings; want at least one per overwritten chunk (%d)", len(expected), len(chunks))
}
if uploads[1] != len(chunks) {
t.Fatalf("the second snapshot's cut uploaded %d chunks; want the %d it overwrote", uploads[1], len(chunks))
}
env.deleteSnapshot(t, "v1", "s3")
exclusive := env.exclusiveBytes(t, "v1", "s2")
env.deleteSnapshot(t, "v1", "s2")
env.requireSnapshotNames(t, "v1", "s1")
deleted := time.Now()
requireBudget(t, time.Until(deleted.Add(ladderGCWait))+ladderGCWait+5*time.Minute)
time.Sleep(time.Until(deleted.Add(ladderGCWait))) // the chunks are older than the grace
_, firstReclaimed := env.gc(t, true)
first := time.Now()
requireBudget(t, ladderGCWait+5*time.Minute)
time.Sleep(time.Until(first.Add(ladderGCWait))) // a second mark the grace after the first
eligible, _ := env.gc(t, false)
named, oddPreview := objectsByKey(eligible)
namedExpected, namedOther, storedBefore := 0, 0, 0
for k, o := range named {
if !expected[k] {
namedOther++
continue
}
namedExpected++
if env.blobStored(t, o.FID) {
storedBefore++
}
}
reclaimedObjs, n := env.gc(t, true)
reclaimed, oddApply := objectsByKey(reclaimedObjs)
reclaimedExpected, reclaimedOther, goneAfter := 0, 0, 0
for k, o := range reclaimed {
if !expected[k] {
reclaimedOther++
continue
}
reclaimedExpected++
if !env.blobStored(t, o.FID) {
goneAfter++
}
}
t.Logf("D4 MEASUREMENT: expected %d bindings (s2's cut uploaded %d chunks; usage: deleting s2 frees %d bytes); "+
"first mark reclaimed %d; preview named %d of them (%d still in the store), %d others, %d malformed; "+
"apply reclaimed %d (%d of them, %d now gone from the store), %d others, %d malformed; surplus left: %d of the expected",
len(expected), uploads[1], exclusive, firstReclaimed, namedExpected, storedBefore, namedOther, oddPreview,
n, reclaimedExpected, goneAfter, reclaimedOther, oddApply, len(expected)-goneAfter)
env.requireImage(t, "s1", imgs[2])
env.restoreChecked(t, "s1", "v2", imgs[0], imgs[1], imgs[2])
}
@@ -0,0 +1,244 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"testing"
"time"
)
// Rung E of the snapshot ladder: faults. E1 kills the holder (SIGKILL) while
// a snapshot is being taken, at several points of the snapshot, and restarts
// it within its lease. The per-step crash cases of the catalog half (after
// the name record, after the intent, with the attempt create unknown) are
// pinned by a unit test of the catalog; this rung is the same property
// through the real processes.
// nameRecorded reports whether vol's catalog holds a name record for the
// snapshot name, read from the filer (not through the product).
func (env *handoffEnv) nameRecorded(t *testing.T, vol, name string) bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
p := path.Join(env.chunkPath, vol, "snapnames", url.PathEscape(name))
resp, err := c.Get("http://" + env.cluster.filerHTTP + p + "?metadata=true")
if err != nil {
t.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return true
case http.StatusNotFound:
return false
}
t.Fatalf("filer lookup of %s: status %d", p, resp.StatusCode)
return false
}
// filerNames lists the entry names (unescaped) of a filer directory, read
// straight from the filer (not through the product); a missing directory
// lists as empty.
func (env *handoffEnv) filerNames(t *testing.T, dir string) map[string]bool {
t.Helper()
c := &http.Client{Timeout: 10 * time.Second}
names := map[string]bool{}
for last := ""; ; {
req, _ := http.NewRequest("GET", "http://"+env.cluster.filerHTTP+dir+"/?limit=1000&lastFileName="+url.QueryEscape(last), nil)
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
var page struct {
Entries []struct {
FullPath string `json:"FullPath"`
} `json:"Entries"`
LastFileName string `json:"LastFileName"`
ShouldDisplayLoadMore bool `json:"ShouldDisplayLoadMore"`
}
err = json.NewDecoder(resp.Body).Decode(&page)
resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return names
}
if err != nil || resp.StatusCode != http.StatusOK {
t.Fatalf("filer listing of %s: status %d %v", dir, resp.StatusCode, err)
}
for _, e := range page.Entries {
name, err := url.PathUnescape(path.Base(e.FullPath))
if err != nil {
t.Fatalf("filer entry %q: %v", e.FullPath, err)
}
names[name] = true
}
if !page.ShouldDisplayLoadMore || page.LastFileName == "" || page.LastFileName == last {
return names
}
last = page.LastFileName
}
}
// TestSnapshotLadderE1CrashDuringASnapshot: rounds on one volume. In each,
// blocks in twelve chunks are written and acknowledged (so the snapshot's cut
// has twelve chunks to upload), a snapshot with a fixed request id is
// started, and the holder is killed after a different delay (from at once to
// well after the answer), then restarted within its lease. Each round is
// classified from what the kill left in the filer: ANSWERED (the command
// answered success first), MID (no answer, but the snapshot's name record or
// an intent that was not there before the request: the kill landed inside
// the snapshot, in its cut or its catalog steps), or BEFORE (neither). The test fails as inconclusive unless at
// least one round is MID. After each restart, before the retry:
// - the snapshot is listed at most once and only active; an ANSWERED one
// is listed, at the cut its answer gave;
// - one more block is written (acknowledged).
//
// Then a retry with the same request id completes the snapshot, listed once:
// at the cut listed before the retry if it was listed (a replay), else at a
// new cut that holds the post-restart block. At the end a next snapshot is
// taken after more writes. Every round's snapshot and the next one restore
// (to independence, per the restore status) exactly as expected: the blocks
// acknowledged before it, the post-restart block only when the retry cut
// anew, and every block written after it reading zero.
func TestSnapshotLadderE1CrashDuringASnapshot(t *testing.T) {
delays := []time.Duration{0, 25 * time.Millisecond, 50 * time.Millisecond, 75 * time.Millisecond,
100 * time.Millisecond, 125 * time.Millisecond, 150 * time.Millisecond, 200 * time.Millisecond, 600 * time.Millisecond}
var targets []string
for i := 0; i <= len(delays); i++ {
targets = append(targets, fmt.Sprintf("v%d", i+2))
}
env := startHandoffEnvWith(t, 1, targets)
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
holder := env.start(t, "blockvolume-v1", "s1")
e := env.adopt(t, holder, "s1")
marker := pattern("ladder-e1-marker")
env.writeBlock(t, "s1", 0, marker)
type result struct {
out, errOut string
code int
err error
}
var images []map[uint64][]byte // what each round's snapshot must hold
cum := map[uint64][]byte{0: marker}
classes := map[string]int{}
for k, delay := range delays {
img := ladderImage(fmt.Sprintf("e1r%d", k), []uint64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, 3)
env.writeImage(t, "s1", img)
cum = mergeImages(cum, img)
name, req := fmt.Sprintf("e1-%d", k), fmt.Sprintf("r-e1-%d", k)
intents := path.Join(env.chunkPath, "v1", "intents")
before := env.filerNames(t, intents)
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
done := make(chan result, 1)
go func() {
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status,
"--name", name, "--request-id", req)
done <- result{out, errOut, code, err}
}()
time.Sleep(delay)
holder.kill(t)
killed := time.Now()
var r result
select {
case r = <-done:
case <-time.After(60 * time.Second):
cancel()
select { // join the worker before failing
case <-done:
case <-time.After(10 * time.Second):
t.Error("the snapshot worker did not finish within 10 s of its cancellation")
}
t.Fatalf("round %d: the snapshot command did not return within 60 s of the holder's kill", k)
}
cancel()
answered := r.err == nil && r.code == 0
newIntent := false
for n := range env.filerNames(t, intents) {
newIntent = newIntent || !before[n]
}
class := "BEFORE"
switch {
case answered:
class = "ANSWERED"
case env.nameRecorded(t, "v1", name) || newIntent:
class = "MID"
}
classes[class]++
// Restarted within the lease, as the unit's RestartSec does: the same
// epoch, serving the blocks written before the kill.
holder = env.start(t, fmt.Sprintf("blockvolume-v1-r%d", k), "s1")
if got := env.adopt(t, holder, "s1"); got != e {
t.Fatalf("round %d: the restarted holder adopted epoch %d; want %d (restarted %v after the kill: within the lease?)", k, got, e, time.Since(killed).Round(time.Millisecond))
}
adopted := time.Since(killed)
poll(t, 60*time.Second, fmt.Sprintf("round %d: the restarted holder never reported its frontend ready", k), func() bool {
return env.frontendReadyAt("s1")
})
t.Logf("round %d (kill after %v): %s (exit %d err %v; new intent %v); adopted %v and frontend ready %v after the kill", k, delay, class, r.code, r.err,
newIntent, adopted.Round(time.Millisecond), time.Since(killed).Round(time.Millisecond))
env.requireImage(t, "s1", cum)
pre := env.snapshots(t, "v1", name)
switch {
case len(pre) > 1:
t.Fatalf("round %d: %s listed %d times: %+v", k, name, len(pre), pre)
case len(pre) == 1 && pre[0].State != "active":
t.Fatalf("round %d: %s listed but not active: %+v", k, name, pre[0])
case answered && len(pre) == 0:
t.Fatalf("round %d: %s answered success before the kill but is not listed: %s", k, name, r.out)
}
if answered {
var a snapshotInfo
if err := json.Unmarshal([]byte(r.out), &a); err != nil || a.CutLSN != pre[0].CutLSN || a.HeadGen != pre[0].HeadGen {
t.Fatalf("round %d: %s answered %s before the kill but is listed as %+v", k, name, r.out, pre[0])
}
}
// 16 bytes: pattern repeats it to exactly one block.
post := map[uint64][]byte{uint64(50+k) * ladderChunkBlocks: pattern(fmt.Sprintf("e1-post-%02d-blk!!", k))}
env.writeImage(t, "s1", post)
out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status,
"--name", name, "--request-id", req)
var info snapshotInfo
if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name {
t.Fatalf("round %d: retry of %s: %v %s", k, name, err, out)
}
if len(pre) == 1 && (info.CutLSN != pre[0].CutLSN || info.HeadGen != pre[0].HeadGen) {
t.Fatalf("round %d: %s was listed as %+v before the retry, which answered %+v: a listed snapshot was taken again", k, name, pre[0], info)
}
if l := env.snapshots(t, "v1", name); len(l) != 1 || l[0].State != "active" || l[0].CutLSN != info.CutLSN {
t.Fatalf("round %d: after the retry %s is listed as %+v; its retry answered %+v", k, name, l, info)
}
if len(pre) == 1 {
images = append(images, cum) // a replay: the post-restart block is not in it
} else {
images = append(images, mergeImages(cum, post)) // cut anew after the restart
}
cum = mergeImages(cum, post)
}
t.Logf("rounds: %v", classes)
if classes["MID"] == 0 {
t.Fatalf("inconclusive: no kill landed inside a snapshot (rounds %v)", classes)
}
next := ladderImage("e1next", []uint64{30, 31}, 3)
env.writeImage(t, "s1", next)
env.snapshot(t, "s1", "v1", "e1-next")
final := mergeImages(cum, next)
for k := range delays {
later := []map[uint64][]byte{final}
env.restoreChecked(t, fmt.Sprintf("e1-%d", k), targets[k], images[k], later...)
}
env.restoreChecked(t, "e1-next", targets[len(delays)], final)
}
@@ -0,0 +1,148 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"context"
"fmt"
"os"
"strings"
"sync"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/link"
)
// Rung F1's heartbeat-ordering watch (V1-SPEC r2.53): with N processes under
// one server id, a volume's slot at the master can expire when its
// heartbeats are dropped. The watch polls the master's view of every source
// volume's replica each second and records each span where the master does
// not observe it (a slot expiry), and what the volume shows meanwhile: an
// epoch change or its frontend leaving ready. At the end it counts the
// master's per-slot superseded lines for the volume ('blockmaster:
// heartbeat superseded ... volume=<v> ...'; 0 where the master does not log
// them).
// f1Health is one source volume's record over the whole run.
type f1Health struct {
Volume string `json:"volume"`
Replica string `json:"replica"`
Polls int `json:"polls"`
PollErrors int `json:"poll_errors"`
SlotExpiries int `json:"slot_expiries"`
SlotUnobservedMs float64 `json:"slot_unobserved_ms"`
EpochChanges int `json:"epoch_changes"`
FrontendNotReady int `json:"frontend_not_ready_polls"`
DuringExpiry []string `json:"during_expiry,omitempty"`
SupersededLogLines int `json:"master_superseded_lines"`
}
type f1Watch struct {
stop chan struct{}
done chan struct{}
mu sync.Mutex
vols map[string]*f1Health
}
// f1StartWatch starts polling the master for every source volume.
func f1StartWatch(env *handoffEnv, vols []f1Volume) *f1Watch {
w := &f1Watch{stop: make(chan struct{}), done: make(chan struct{}), vols: map[string]*f1Health{}}
for _, v := range vols {
w.vols[v.id] = &f1Health{Volume: v.id, Replica: env.hosts[v.node].replica}
}
go func() {
defer close(w.done)
conn, err := link.Dial(env.h.masterAddr)
if err != nil {
return
}
defer conn.Close()
cl := control.NewClusterEvidenceServiceClient(conn)
type state struct {
unobservedSince time.Time
epoch uint64
}
st := map[string]*state{}
t := time.NewTicker(time.Second)
defer t.Stop()
for {
select {
case <-w.stop:
return
case <-t.C:
}
for _, v := range vols {
h, s := w.vols[v.id], st[v.id]
if s == nil {
s = &state{}
st[v.id] = s
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
ev, err := cl.GetVolumeStatus(ctx, &control.GetVolumeStatusRequest{VolumeId: v.id})
cancel()
w.mu.Lock()
h.Polls++
if err != nil {
h.PollErrors++
w.mu.Unlock()
continue
}
observed := false
for _, r := range ev.GetReplicas() {
if r.GetReplicaId() == h.Replica && r.GetObserved() {
observed = true
}
}
now := time.Now()
switch {
case !observed && s.unobservedSince.IsZero():
s.unobservedSince = now
h.SlotExpiries++
case observed && !s.unobservedSince.IsZero():
h.SlotUnobservedMs += ms(now.Sub(s.unobservedSince))
s.unobservedSince = time.Time{}
}
if e := ev.GetEpoch(); s.epoch != 0 && e != s.epoch {
h.EpochChanges++
if !s.unobservedSince.IsZero() {
h.DuringExpiry = append(h.DuringExpiry, fmt.Sprintf("epoch %d -> %d", s.epoch, e))
}
}
s.epoch = ev.GetEpoch()
w.mu.Unlock()
ready := volumeFrontendReady(env.hosts[v.node].status, v.id)
w.mu.Lock()
if !ready {
h.FrontendNotReady++
if !s.unobservedSince.IsZero() {
h.DuringExpiry = append(h.DuringExpiry, "frontend not ready at "+now.UTC().Format(time.RFC3339))
}
}
w.mu.Unlock()
}
}
}()
return w
}
// finish stops the watch and counts the master's superseded lines per
// volume from its log.
func (w *f1Watch) finish(masterLog string) []f1Health {
close(w.stop)
<-w.done
b, _ := os.ReadFile(masterLog)
lines := strings.Split(string(b), "\n")
w.mu.Lock()
defer w.mu.Unlock()
var out []f1Health
for _, h := range w.vols {
for _, l := range lines {
if strings.Contains(l, "heartbeat superseded") && strings.Contains(l, " volume="+h.Volume+" ") {
h.SupersededLogLines++
}
}
out = append(out, *h)
}
return out
}
@@ -0,0 +1,666 @@
//go:build subprocess && chunkstore_integration
package main_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/nvme"
"github.com/seaweedfs/seaweed-block/core/hostlimit"
)
// Snapshot ladder rung F1 (V1-SPEC r2.49, r2.52): N volumes on one host,
// every volume snapshotted at the same instant, round after round, under
// write load. It must hold: every snapshot restores exactly; no write fails;
// the host limiter paces the cuts and none starves (every snapshot commits
// within ceil(N/slots)+1 times the slowest single cut). It measures, per
// volume and round: the snapshot's cut (total and guest barrier pause), the
// client write latency inside and outside snapshot windows, request to
// commit time, host-slot waits, restore time, chunks and bytes uploaded,
// filer entries per snapshot, and blockvolume RSS. The JSON report goes to
// F1_REPORT.
//
// A large test: it runs only with F1_RUN=1, on a host booked for it, never in
// CI. Knobs: F1_VOLUMES (10), F1_ROUNDS (3), F1_WRITE_SECONDS (120),
// F1_CONTROL_PAUSE_SECONDS (a negative control: stop the last volume's
// process that long after the rounds; the rung must then fail),
// F1_LOAD_SPAN (8192 blocks per volume per round, written evenly across the
// write period, so writes run before, during and after the snapshots),
// F1_HOST_LIMIT_DIR (a local, non-temporary directory; required for the
// limiter checks, a smoke may leave it unset), F1_HOST_LIMIT_SLOTS
// (the limiter's normal slots; default hostlimit's), F1_REPORT.
//
// Each volume has two regions. The ledger region is written and flushed
// before a round's snapshot, so the snapshot must hold it exactly. The load
// region is written in LBA order during the snapshot, so the snapshot must
// hold a prefix of it (A3's one-point-in-time check).
type f1Config struct {
Volumes, Rounds int
WriteSeconds int
HostLimitDir string
Slots int
Report string
LedgerBlocksPerRnd int
LoadSpan int
ControlPauseSecs int
}
func f1ConfigFromEnv(t *testing.T) f1Config {
t.Helper()
if os.Getenv("F1_RUN") != "1" {
t.Skip("rung F1 is a large test: set F1_RUN=1 on a booked host")
}
num := func(k string, def int) int {
if v := os.Getenv(k); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
t.Fatalf("%s=%q: want a positive integer", k, v)
}
return n
}
return def
}
c := f1Config{Volumes: num("F1_VOLUMES", 10), Rounds: num("F1_ROUNDS", 3), WriteSeconds: num("F1_WRITE_SECONDS", 120),
HostLimitDir: os.Getenv("F1_HOST_LIMIT_DIR"), Slots: num("F1_HOST_LIMIT_SLOTS", hostlimit.DefaultConfig("").NormalSlots),
Report: os.Getenv("F1_REPORT"), LedgerBlocksPerRnd: 64, LoadSpan: num("F1_LOAD_SPAN", 8192)}
if v := os.Getenv("F1_CONTROL_PAUSE_SECONDS"); v != "" {
c.ControlPauseSecs = num("F1_CONTROL_PAUSE_SECONDS", 0)
}
if c.Rounds*(c.LedgerBlocksPerRnd+c.LoadSpan) > ladderUntouched {
t.Fatalf("F1_ROUNDS=%d does not fit below the untouched chunk", c.Rounds)
}
return c
}
// f1Volume is one source volume: its id, host record and daemon.
type f1Volume struct {
id, node string
d *daemon
}
// f1Sample is one client write.
type f1Sample struct {
start time.Time
d time.Duration
}
// f1Round is one volume's measurements in one round.
type f1Round struct {
Volume string `json:"volume"`
Round int `json:"round"`
SnapshotMs float64 `json:"snapshot_request_to_commit_ms"`
CutTotalMs float64 `json:"cut_total_ms"`
BarrierPauseMs float64 `json:"cut_barrier_pause_ms"`
UploadedChunks int `json:"uploaded_chunks"`
UploadedBytes int64 `json:"uploaded_bytes"`
HostSlotWaits uint64 `json:"host_slot_waits"`
RestoreMs float64 `json:"restore_ms"`
RestoreExact bool `json:"restore_exact"`
LoadPrefix int `json:"load_prefix_blocks"`
WritesIn int `json:"writes_in_window"`
WritesOut int `json:"writes_outside_window"`
WriteP50InMs float64 `json:"write_p50_in_ms"`
WriteP99InMs float64 `json:"write_p99_in_ms"`
WriteMaxInMs float64 `json:"write_max_in_ms"`
WriteP50OutMs float64 `json:"write_p50_out_ms"`
WriteP99OutMs float64 `json:"write_p99_out_ms"`
WriteMaxOutMs float64 `json:"write_max_out_ms"`
RSSKiB int64 `json:"blockvolume_rss_kib"`
FilerEntriesNew int `json:"filer_entries_added_by_round"`
FilerPerSnap float64 `json:"filer_entries_per_snapshot"`
}
type f1Report struct {
Config f1Config `json:"config"`
Limiter string `json:"limiter"`
StartedAt time.Time `json:"started_at"`
Rounds []f1Round `json:"rounds"`
Health []f1Health `json:"heartbeat_health"`
CommitBound float64 `json:"commit_bound_ms"`
WriteErrors int `json:"write_errors"`
Verdict string `json:"verdict"`
Failures []string `json:"failures,omitempty"`
}
func TestSnapshotLadderF1VolumesOneHost(t *testing.T) {
cfg := f1ConfigFromEnv(t)
rep := &f1Report{Config: cfg, StartedAt: time.Now().UTC(), Limiter: "off"}
env, master := f1StartEnv(t, cfg)
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
if cfg.HostLimitDir != "" {
env.volExtra = append(env.volExtra, "--host-limit-dir", cfg.HostLimitDir, "--host-limit-normal-slots", strconv.Itoa(cfg.Slots))
rep.Limiter = fmt.Sprintf("%s, %d normal slots", cfg.HostLimitDir, cfg.Slots)
}
vols := f1StartSources(t, env, cfg.Volumes)
defer f1WriteReport(t, cfg, rep)
watch := f1StartWatch(env, vols)
for round := 1; round <= cfg.Rounds; round++ {
before := f1FilerEntries(t, env)
rounds := f1RunRound(t, env, cfg, vols, round, rep)
added := f1FilerEntries(t, env) - before
for i := range rounds {
rounds[i].FilerEntriesNew = added
rounds[i].FilerPerSnap = float64(added) / float64(len(rounds))
}
rep.Rounds = append(rep.Rounds, rounds...)
}
if cfg.ControlPauseSecs > 0 {
// Negative control: the last volume's blockvolume is stopped
// (SIGSTOP) past the master's freshness window, so its heartbeats
// stop; the watch must record a slot expiry and the rung must fail.
last := vols[len(vols)-1]
if err := last.d.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatalf("control: SIGSTOP %s: %v", last.id, err)
}
time.Sleep(time.Duration(cfg.ControlPauseSecs) * time.Second)
if err := last.d.proc.Signal(syscall.SIGCONT); err != nil {
t.Fatalf("control: SIGCONT %s: %v", last.id, err)
}
time.Sleep(3 * time.Second)
}
rep.Health = watch.finish(master.log)
f1Judge(t, cfg, rep)
}
func f1RestoreTarget(vol, round int) string { return fmt.Sprintf("v%dr%d", vol, round) }
// f1StartEnv is the procedure harness laid out as one host (V1-SPEC r2.52,
// the layout ruling): ONE server id, s1, and one blockvolume process per
// volume, each with its own replica id and its own data/ctrl/status/NVMe
// ports. Source v<i> is replica r<i>; the restore target of v<i> in round k
// is replica r<i+N*k> on the same server. The node record carries the first
// source's pair, as the deployment page writes one node.
func f1StartEnv(t *testing.T, cfg f1Config) (*handoffEnv, *daemon) {
t.Helper()
h := newPlannedHandoffHarness(t)
env := &handoffEnv{h: h, cluster: startWorkspaceWeed(t), chunkPath: fmt.Sprintf("/f1-%d", time.Now().UnixNano()), hosts: map[string]bvHost{}}
must, _ := fatalOn(t)
add := func(key, vol string, replica int) {
b := bvHost{id: key, server: "s1", replica: fmt.Sprintf("r%d", replica), volume: vol, root: filepath.Join(h.dir, "vol-"+key),
data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t)}
if key == "v1" {
b.data, b.ctrl, b.status, b.nvme = h.dataAddr, h.ctrlAddr, h.statusAddr, h.nvmeAddr
}
env.hosts[key] = b
}
for i := 1; i <= cfg.Volumes; i++ {
add(fmt.Sprintf("v%d", i), fmt.Sprintf("v%d", i), i)
}
for r := 1; r <= cfg.Rounds; r++ {
for i := 1; i <= cfg.Volumes; i++ {
v := f1RestoreTarget(i, r)
add(v, v, i+cfg.Volumes*r)
}
}
var vols strings.Builder
keys := make([]string, 0, len(env.hosts))
for k := range env.hosts {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
b := env.hosts[k]
fmt.Fprintf(&vols, " - id: %s\n size_bytes: 268435456\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: %s\n", b.volume, b.replica)
}
spec := filepath.Join(h.dir, "cluster-spec.yaml")
must(os.WriteFile(spec, []byte(fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n%s", h.dataAddr, h.ctrlAddr, vols.String())), 0o644))
mstate := filepath.Join(h.dir, "master")
master := h.start(t, "blockmaster", h.master, "--authority-store", filepath.Join(mstate, "authority"), "--lifecycle-store", filepath.Join(mstate, "lifecycle"),
"--cluster-spec", spec, "--expected-slots-per-volume", "1", "--listen", h.masterAddr,
"--workspace-rpc", "--workspace-head-base-url", "http://"+env.cluster.filerHTTP+env.chunkPath)
master.waitLog(t, 30*time.Second, "blockmaster: lock acquired, reloaded=")
return env, master
}
// f1Up starts the blockvolume of key and waits for its volume to be primary
// and its frontend ready.
func f1Up(t *testing.T, env *handoffEnv, key string) *daemon {
t.Helper()
b := env.hosts[key]
d := env.h.start(t, "blockvolume-"+key, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at %s@", b.volume, b.replica))
poll(t, 60*time.Second, key+" never reported its frontend ready", func() bool { return volumeFrontendReady(b.status, b.volume) })
return d
}
// f1StartSources starts the N source volumes.
func f1StartSources(t *testing.T, env *handoffEnv, n int) []f1Volume {
t.Helper()
var vols []f1Volume
for i := 1; i <= n; i++ {
v := fmt.Sprintf("v%d", i)
vols = append(vols, f1Volume{id: v, node: v, d: f1Up(t, env, v)})
}
return vols
}
// f1Restore restores snapshot snap of src into target (a new volume on the
// same server) and drives the restore; the target's blockvolume is stopped
// once verified (f1RunRound), so restores do not pile up processes.
func f1Restore(t *testing.T, env *handoffEnv, src, snap, target string) *daemon {
t.Helper()
b := env.hosts[target]
env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := f1Up(t, env, target)
env.h.command(t, "ops", "chunk", "restore", "--volume", target, "--status-addr", b.status)
return d
}
// f1Block is one deterministic 4096-byte block (pattern needs a length that
// divides 4096; these labels do not, so the block is filled explicitly).
func f1Block(vol string, round int, kind string, lba uint64) []byte {
s := fmt.Sprintf("%s r%d %s %08d|", vol, round, kind, lba)
b := make([]byte, 4096)
for i := range b {
b[i] = s[i%len(s)]
}
return b
}
func f1LedgerBase(cfg f1Config, round int) uint64 {
return uint64((round - 1) * (cfg.LedgerBlocksPerRnd + cfg.LoadSpan))
}
// f1RunRound: write and flush each volume's ledger region, start the load
// writers, snapshot every volume at the same instant, stop the load, then
// restore and verify every snapshot.
func f1RunRound(t *testing.T, env *handoffEnv, cfg f1Config, vols []f1Volume, round int, rep *f1Report) []f1Round {
t.Helper()
for _, v := range vols {
c := dialNVMe(t, env.hosts[v.node].nvme, plannedHandoffNQN)
base := f1LedgerBase(cfg, round)
for i := 0; i < cfg.LedgerBlocksPerRnd; i++ {
c.write(t, base+uint64(i), f1Block(v.id, round, "ledger", base+uint64(i)))
}
c.flush(t)
c.close()
}
type writer struct {
mu sync.Mutex
samples []f1Sample
written int
err error
}
stop := make(chan struct{})
ws := make([]*writer, len(vols))
var wg sync.WaitGroup
for i, v := range vols {
ws[i] = &writer{}
c := dialNVMe(t, env.hosts[v.node].nvme, plannedHandoffNQN)
wg.Add(1)
go func(w *writer, c *nvmeInitiator, vol string) {
defer wg.Done()
defer c.close()
first := f1LedgerBase(cfg, round) + uint64(cfg.LedgerBlocksPerRnd)
// Paced so the span covers the whole write period.
every := time.Duration(cfg.WriteSeconds) * time.Second / time.Duration(cfg.LoadSpan)
begin := time.Now()
for n := 0; n < cfg.LoadSpan; n++ {
if wait := time.Until(begin.Add(time.Duration(n) * every)); wait > 0 {
select {
case <-stop:
return
case <-time.After(wait):
}
}
select {
case <-stop:
return
default:
}
lba := first + uint64(n)
s := time.Now()
err := c.tryWrite(lba, f1Block(vol, round, "load", lba))
if err == nil && n%16 == 15 {
err = c.tryFlush()
}
w.mu.Lock()
w.samples = append(w.samples, f1Sample{start: s, d: time.Since(s)})
if err != nil {
w.err = err
} else {
w.written = n + 1
}
w.mu.Unlock()
if err != nil {
return
}
}
}(ws[i], c, v.id)
}
time.Sleep(time.Duration(cfg.WriteSeconds) * time.Second / 2) // load before the snapshots
type snapRes struct {
start, end time.Time
out, err string
code int
}
res := make([]snapRes, len(vols))
var sg sync.WaitGroup
gate := make(chan struct{})
for i, v := range vols {
sg.Add(1)
go func(i int, v f1Volume) {
defer sg.Done()
<-gate
res[i].start = time.Now()
res[i].out, res[i].err, res[i].code = env.h.run(t, "ops", "chunk", "snapshot", "--volume", v.id, "--status-addr", env.hosts[v.node].status, "--name", fmt.Sprintf("f1-r%d", round))
res[i].end = time.Now()
}(i, v)
}
close(gate)
sg.Wait()
time.Sleep(time.Duration(cfg.WriteSeconds) * time.Second / 2) // load after the snapshots
close(stop)
wg.Wait()
out := make([]f1Round, len(vols))
for i, v := range vols {
r := f1Round{Volume: v.id, Round: round}
w := ws[i]
if w.err != nil {
rep.WriteErrors++
rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: write error: %v", v.id, round, w.err))
}
if res[i].code != 0 {
rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: snapshot exit %d: %s %s", v.id, round, res[i].code, res[i].out, res[i].err))
out[i] = r
continue
}
r.SnapshotMs = ms(res[i].end.Sub(res[i].start))
f1Latencies(&r, w.samples, res[i].start, res[i].end)
f1CutStats(t, env, v, &r)
r.RSSKiB = f1RSS(v.d)
target := f1RestoreTarget(i+1, round)
rs := time.Now()
rd := f1Restore(t, env, v.id, fmt.Sprintf("f1-r%d", round), target)
r.RestoreMs = ms(time.Since(rs))
r.RestoreExact, r.LoadPrefix = f1Verify(t, env, cfg, v.id, target, round, w.written)
rd.term(t, 60*time.Second)
if !r.RestoreExact {
rep.Failures = append(rep.Failures, fmt.Sprintf("%s round %d: the restored snapshot is not the volume at its point", v.id, round))
}
out[i] = r
}
return out
}
// f1Verify reads the restored snapshot: every ledger block of rounds 1..round
// exact; each round's load region a prefix, at most what was written.
func f1Verify(t *testing.T, env *handoffEnv, cfg f1Config, vol, target string, round, written int) (bool, int) {
t.Helper()
c := dialNVMe(t, env.hosts[target].nvme, plannedHandoffNQN)
defer c.close()
zero := make([]byte, 4096)
prefix := 0
for r := 1; r <= round; r++ {
base := f1LedgerBase(cfg, r)
for i := 0; i < cfg.LedgerBlocksPerRnd; i++ {
if !bytes.Equal(c.read(t, base+uint64(i), 4096), f1Block(vol, r, "ledger", base+uint64(i))) {
return false, 0
}
}
first := base + uint64(cfg.LedgerBlocksPerRnd)
ended, k := false, 0
for n := 0; n < cfg.LoadSpan; n++ {
got := c.read(t, first+uint64(n), 4096)
switch {
case !ended && bytes.Equal(got, f1Block(vol, r, "load", first+uint64(n))):
k++
case bytes.Equal(got, zero) && r == round:
ended = true
case r < round && n >= k && bytes.Equal(got, zero):
ended = true
default:
return false, 0
}
}
if r == round {
prefix = k
if k > written {
return false, k
}
}
}
return true, prefix
}
// f1Latencies splits the client write latencies at the snapshot window.
func f1Latencies(r *f1Round, samples []f1Sample, from, to time.Time) {
var in, out []time.Duration
for _, s := range samples {
if !s.start.Before(from) && !s.start.After(to) {
in = append(in, s.d)
} else {
out = append(out, s.d)
}
}
r.WritesIn, r.WritesOut = len(in), len(out)
r.WriteP50InMs, r.WriteP99InMs, r.WriteMaxInMs = pct(in, 50), pct(in, 99), pct(in, 100)
r.WriteP50OutMs, r.WriteP99OutMs, r.WriteMaxOutMs = pct(out, 50), pct(out, 99), pct(out, 100)
}
func pct(d []time.Duration, p float64) float64 {
if len(d) == 0 {
return 0
}
s := append([]time.Duration(nil), d...)
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
i := int(math.Ceil(p/100*float64(len(s)))) - 1
if i < 0 {
i = 0
}
return ms(s[i])
}
func ms(d time.Duration) float64 { return float64(d) / float64(time.Millisecond) }
// f1CutStats reads the volume's last cut (the snapshot's) from its durable
// status.
func f1CutStats(t *testing.T, env *handoffEnv, v f1Volume, r *f1Round) {
t.Helper()
c := &http.Client{Timeout: 5 * time.Second}
resp, err := c.Get("http://" + env.hosts[v.node].status + "/status/durable?volume=" + v.id)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var st struct {
Volumes []struct {
VolumeID string
Chunk *struct {
HostSlotWaits uint64
Stats struct {
LastCut *struct {
TotalNs, BarrierPauseNs int64
UploadedChunks int
UploadedBytes int64
}
}
}
}
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err := json.Unmarshal(body, &st); err != nil {
t.Fatalf("durable status of %s: %v", v.id, err)
}
for _, s := range st.Volumes {
if s.VolumeID != v.id || s.Chunk == nil || s.Chunk.Stats.LastCut == nil {
continue
}
l := s.Chunk.Stats.LastCut
r.CutTotalMs, r.BarrierPauseMs = float64(l.TotalNs)/1e6, float64(l.BarrierPauseNs)/1e6
r.UploadedChunks, r.UploadedBytes, r.HostSlotWaits = l.UploadedChunks, l.UploadedBytes, s.Chunk.HostSlotWaits
return
}
t.Fatalf("durable status of %s has no last cut: %s", v.id, body)
}
// f1RSS is the blockvolume's resident set (KiB), 0 where /proc is absent.
func f1RSS(d *daemon) int64 {
b, err := os.ReadFile(fmt.Sprintf("/proc/%d/status", d.proc.Pid))
if err != nil {
return 0
}
for _, l := range strings.Split(string(b), "\n") {
if strings.HasPrefix(l, "VmRSS:") {
f := strings.Fields(l)
if len(f) >= 2 {
n, _ := strconv.ParseInt(f[1], 10, 64)
return n
}
}
}
return 0
}
// f1FilerEntries counts the filer entries (files and directories) under the
// chunk path, by the filer's JSON listing.
func f1FilerEntries(t *testing.T, env *handoffEnv) int {
t.Helper()
c := &http.Client{Timeout: 30 * time.Second}
var walk func(dir string) int
walk = func(dir string) int {
n, last := 0, ""
for {
u := "http://" + env.cluster.filerHTTP + dir + "/?limit=1000&lastFileName=" + url.QueryEscape(last)
req, _ := http.NewRequest(http.MethodGet, u, nil)
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
t.Fatalf("filer list %s: %v", dir, err)
}
var page struct {
Entries []struct {
FullPath string
Mode uint32
}
ShouldDisplayLoadMore bool
LastFileName string
}
err = json.NewDecoder(resp.Body).Decode(&page)
resp.Body.Close()
if err != nil {
t.Fatalf("filer list %s: %v", dir, err)
}
for _, e := range page.Entries {
n++
if e.Mode&uint32(os.ModeDir) != 0 {
n += walk(e.FullPath)
}
}
if !page.ShouldDisplayLoadMore || page.LastFileName == "" {
return n
}
last = page.LastFileName
}
}
return walk(env.chunkPath)
}
// f1Judge applies the pass rule: no failure recorded, and every snapshot
// committed within ceil(N/slots)+1 times the slowest single cut (N+1 when
// the limiter is off).
func f1Judge(t *testing.T, cfg f1Config, rep *f1Report) {
t.Helper()
worst, longest := 0.0, 0.0
for _, r := range rep.Rounds {
worst = math.Max(worst, r.CutTotalMs)
longest = math.Max(longest, r.SnapshotMs)
}
waves := float64(cfg.Volumes + 1)
if cfg.HostLimitDir != "" {
waves = math.Ceil(float64(cfg.Volumes)/float64(cfg.Slots)) + 1
}
rep.CommitBound = waves * worst
for _, h := range rep.Health {
if h.SlotExpiries > 0 {
rep.Failures = append(rep.Failures, fmt.Sprintf("%s: the master lost its slot %d time(s) for %.0f ms in total (during: %v)", h.Volume, h.SlotExpiries, h.SlotUnobservedMs, h.DuringExpiry))
}
}
if longest > rep.CommitBound {
rep.Failures = append(rep.Failures, fmt.Sprintf("a snapshot took %.0f ms, above the bound %.0f ms (%.0f waves x the slowest cut %.0f ms): a volume starved", longest, rep.CommitBound, waves, worst))
}
rep.Verdict = "PASS"
if len(rep.Failures) > 0 {
rep.Verdict = "FAIL"
t.Errorf("rung F1: %s", strings.Join(rep.Failures, "; "))
}
}
func f1WriteReport(t *testing.T, cfg f1Config, rep *f1Report) {
b, err := json.MarshalIndent(rep, "", " ")
if err != nil {
t.Errorf("report: %v", err)
return
}
t.Logf("rung F1 report: %s", b)
if cfg.Report != "" {
if err := os.WriteFile(cfg.Report, b, 0o644); err != nil {
t.Errorf("write %s: %v", cfg.Report, err)
}
}
}
// tryWrite and tryFlush are write and flush returning the error (the load
// writers run off the test goroutine, where t.Fatal is not allowed).
func (c *nvmeInitiator) tryWrite(lba uint64, data []byte) error {
cmd := c.ioCmd(0x01, lba, len(data)/4096)
if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil {
return fmt.Errorf("nvme Write: %w", err)
}
ch, err := c.r.Dequeue()
if err != nil || ch.Type != 0x9 {
return fmt.Errorf("nvme Write: want R2T, got type %v err %v", ch, err)
}
var r2t nvme.R2THeader
if err := c.r.Receive(&r2t); err != nil {
return fmt.Errorf("nvme R2T: %w", err)
}
h2c := nvme.H2CDataHeader{CCCID: cmd.CID, TAG: r2t.TAG, DATAL: uint32(len(data))}
if err := c.w.SendWithData(0x6, 0, &h2c, 16, data); err != nil {
return fmt.Errorf("nvme H2CData: %w", err)
}
return c.tryStatus("Write")
}
func (c *nvmeInitiator) tryFlush() error {
cmd := c.ioCmd(0x00, 0, 0)
if err := c.w.SendHeaderOnly(0x4, &cmd, 64); err != nil {
return fmt.Errorf("nvme Flush: %w", err)
}
return c.tryStatus("Flush")
}
func (c *nvmeInitiator) tryStatus(op string) error {
ch, err := c.r.Dequeue()
if err != nil || ch.Type != 0x5 {
return fmt.Errorf("nvme %s response: type %v err %v", op, ch, err)
}
var resp nvme.CapsuleResponse
if err := c.r.Receive(&resp); err != nil {
return fmt.Errorf("nvme %s response body: %w", op, err)
}
if resp.Status != 0 {
return fmt.Errorf("nvme %s status 0x%04x", op, resp.Status)
}
return nil
}
@@ -4,10 +4,13 @@ package main_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os/exec"
"strings"
"testing"
"time"
@@ -181,17 +184,214 @@ func (env *handoffEnv) writeDuringSnapshot(t *testing.T, name string, first uint
}
}
// snapshot takes the named snapshot of vol on its host and checks the answer
// names it.
func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) {
// snapshotInfo is what a snapshot's answer and its list entry say about it.
type snapshotInfo struct {
Name string `json:"name"`
HeadGen uint64 `json:"headGen"`
CutLSN uint64 `json:"cutLSN"`
State string `json:"state"`
ChunkCount int `json:"chunkCount"`
}
// snapshot takes the named snapshot of vol on its host, checks the answer
// names it, and returns the answer.
func (env *handoffEnv) snapshot(t *testing.T, hostID, vol, name string) snapshotInfo {
t.Helper()
out, _ := env.h.command(t, "ops", "chunk", "snapshot", "--volume", vol, "--status-addr", env.hosts[hostID].status, "--name", name)
var info struct {
Name string `json:"name"`
}
var info snapshotInfo
if err := json.Unmarshal([]byte(out), &info); err != nil || info.Name != name {
t.Fatalf("snapshot %s of %s: %v\n%s", name, vol, err, out)
}
return info
}
// listSnapshots lists vol's snapshots (with a name prefix when given) under
// ctx, without failing the test.
func (env *handoffEnv) listSnapshots(ctx context.Context, vol, prefix string) ([]snapshotInfo, error) {
args := []string{"ops", "chunk", "snapshots", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
if prefix != "" {
args = append(args, "--prefix", prefix)
}
out, errOut, code, err := runCLI(ctx, env.h, args...)
if err != nil {
return nil, err
}
var body struct {
Snapshots []snapshotInfo `json:"snapshots"`
}
if code != 0 || json.Unmarshal([]byte(out), &body) != nil {
return nil, fmt.Errorf("snapshots of %s: exit %d: %s %s", vol, code, out, errOut)
}
return body.Snapshots, nil
}
// snapshots lists vol's snapshots (with a name prefix when given).
func (env *handoffEnv) snapshots(t *testing.T, vol, prefix string) []snapshotInfo {
t.Helper()
args := []string{"ops", "chunk", "snapshots", "--volume", vol, "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath}
if prefix != "" {
args = append(args, "--prefix", prefix)
}
out, _ := env.h.command(t, args...)
var body struct {
Snapshots []snapshotInfo `json:"snapshots"`
}
if err := json.Unmarshal([]byte(out), &body); err != nil {
t.Fatalf("snapshots of %s: %v\n%s", vol, err, out)
}
return body.Snapshots
}
// restoreAttached creates target from snapshot snap of src and starts its
// blockvolume, but not the restore driver: target serves and stays
// dependent on its source (not independent).
func (env *handoffEnv) restoreAttached(t *testing.T, src, snap, target string) {
t.Helper()
b := env.hosts["n-"+target]
env.h.command(t, "ops", "chunk", "restore", "--source", src, "--snapshot", snap, "--target", target,
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath)
d := env.h.start(t, "blockvolume-"+target, env.h.volume, env.volArgsFor(b)...)
d.waitLog(t, 60*time.Second, fmt.Sprintf("blockvolume: volume %s adopted as PRIMARY at r1@", target))
poll(t, 60*time.Second, fmt.Sprintf("%s never reported its frontend ready", target), func() bool {
return volumeFrontendReady(b.status, target)
})
}
// TestSnapshotLadderB1SnapshotQuery: three snapshots with writes between
// them. The list is exactly the committed snapshots, in order, each active,
// with the point (cut LSN), HEAD generation and size (chunk count) its
// creation answered; a prefix shows one. A snapshot being taken appears in
// the list only committed, with the fields its creation answers, and stays;
// the test fails as inconclusive unless at least one listing ran while the
// snapshot was in flight and did not show it. A snapshot request that is refused
// (a restore volume not yet independent) leaves no name in the list.
func TestSnapshotLadderB1SnapshotQuery(t *testing.T) {
env := startLadderEnv(t, "v2")
var made []snapshotInfo
for i, w := range []struct {
lba uint64
text string
}{{0, "ladder-b1-blk-A!"}, {2 * ladderChunkBlocks, "ladder-b1-blk-B!"}, {1, "ladder-b1-blk-C!"}} {
env.writeBlock(t, "s1", w.lba, pattern(w.text))
made = append(made, env.snapshot(t, "s1", "v1", fmt.Sprintf("s%d", i+1)))
}
list := env.snapshots(t, "v1", "")
if len(list) != len(made) {
t.Fatalf("list has %d snapshots; want exactly the %d committed: %+v", len(list), len(made), list)
}
wantChunks := []int{1, 2, 2}
for i, got := range list {
m := made[i]
if got.Name != m.Name || got.State != "active" || got.CutLSN != m.CutLSN || got.HeadGen != m.HeadGen || got.ChunkCount != m.ChunkCount {
t.Fatalf("list entry %d %+v; want %+v, active", i, got, m)
}
if got.ChunkCount != wantChunks[i] {
t.Fatalf("%s holds %d chunks; want %d", got.Name, got.ChunkCount, wantChunks[i])
}
if i > 0 && (got.CutLSN <= list[i-1].CutLSN || got.HeadGen <= list[i-1].HeadGen) {
t.Fatalf("list not in order of points: %+v after %+v", got, list[i-1])
}
}
if one := env.snapshots(t, "v1", "s2"); len(one) != 1 || one[0].Name != "s2" || one[0].CutLSN != made[1].CutLSN {
t.Fatalf("show s2: %+v", one)
}
// A snapshot being taken: listed only committed, and then it stays. The
// write before it is acknowledged first, so its cut is past s3's; a
// second write follows its start, and may land before or after its cut
// (the test claims nothing about it).
env.writeBlock(t, "s1", 3, pattern("ladder-b1-blk-D!"))
type result struct {
out, errOut string
code int
err error
}
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
done := make(chan result, 1)
joined := false
t.Cleanup(func() { // before the daemons stop: cancel and join the worker
cancel()
if !joined {
select {
case <-done:
case <-time.After(10 * time.Second): // runCLI's 5 s WaitDelay, with a margin
t.Error("snapshot s4 worker did not finish within 10 s of its cancellation: its completion is unresolved")
}
}
})
go func() {
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "snapshot", "--volume", "v1", "--status-addr", env.hosts["s1"].status, "--name", "s4")
done <- result{out, errOut, code, err}
}()
env.writeBlock(t, "s1", 4, pattern("ladder-b1-blk-E!"))
var observed []snapshotInfo
var r result
inFlightUnlisted := 0 // listings begun before s4 answered that did not show it
// The observation bound: every list probe runs within what is left of it,
// and a probe that returns after it fails the test.
deadline := time.Now().Add(160 * time.Second)
obs, obsCancel := context.WithDeadline(context.Background(), deadline)
defer obsCancel()
for running := true; running; {
select {
case r = <-done:
joined, running = true, false
default:
}
if running && time.Now().After(deadline) {
t.Fatal("snapshot s4 did not return within its bound")
}
list, err := env.listSnapshots(obs, "v1", "s4")
if err != nil || time.Now().After(deadline) {
t.Fatalf("listing s4 within the observation bound: %v", err)
}
var s4 *snapshotInfo
for _, e := range list {
e := e
s4 = &e
}
if running && s4 == nil {
inFlightUnlisted++
}
switch {
case s4 == nil && len(observed) > 0:
t.Fatal("s4 was listed, then disappeared")
case s4 != nil && (s4.State != "active" || s4.CutLSN <= made[2].CutLSN || s4.HeadGen <= made[2].HeadGen):
t.Fatalf("s4 listed before it was committed: %+v", *s4)
case s4 != nil:
observed = append(observed, *s4)
}
}
if r.err != nil || r.code != 0 {
t.Fatalf("snapshot s4: exit %d %v\n%s\n%s", r.code, r.err, r.out, r.errOut)
}
if inFlightUnlisted == 0 {
t.Fatalf("inconclusive: no listing ran while s4 was in flight and unlisted (%d listings saw it committed)", len(observed))
}
t.Logf("s4: %d listings while in flight did not show it; %d showed it committed", inFlightUnlisted, len(observed))
var created snapshotInfo
if err := json.Unmarshal([]byte(r.out), &created); err != nil || created.Name != "s4" {
t.Fatalf("snapshot s4 answer: %v\n%s", err, r.out)
}
final := env.snapshots(t, "v1", "s4")
if len(final) != 1 {
t.Fatalf("s4 not listed after its snapshot returned: %+v", final)
}
for _, o := range append(observed, final[0]) {
if o.State != "active" || o.CutLSN != created.CutLSN || o.HeadGen != created.HeadGen || o.ChunkCount != created.ChunkCount {
t.Fatalf("s4 listed as %+v; its creation answered %+v", o, created)
}
}
// A refused snapshot is not a snapshot.
env.restoreAttached(t, "v1", "s1", "v2")
out, errOut, code := env.h.run(t, "ops", "chunk", "snapshot", "--volume", "v2", "--status-addr", env.hosts["n-v2"].status, "--name", "x")
if code == 0 || !strings.Contains(out+errOut, "restore_incomplete") {
t.Fatalf("snapshot of a restore volume not yet independent: exit %d, want restore_incomplete\n%s\n%s", code, out, errOut)
}
if l := env.snapshots(t, "v2", ""); len(l) != 0 {
t.Fatalf("a refused snapshot left %+v in the list", l)
}
}
// lastCutUploads is the number of chunks the last cut of vol uploaded, from
@@ -294,3 +494,189 @@ func volumeFrontendReady(statusAddr, vol string) bool {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
return frontendReady(b)
}
// waitIndependent polls the restore status of target until the restore
// driver reports its phase independent (what the status says; it is not a
// separate measurement of which keys hold the chunks). 120 s bounds the
// observation: every query runs within what is left of it, and a success
// seen after it does not count. A query cancelled at the bound may take up
// to runCLI's 5 s WaitDelay more to clean up.
func (env *handoffEnv) waitIndependent(t *testing.T, target string) {
t.Helper()
const bound = 120 * time.Second
end := time.Now().Add(bound)
ctx, cancel := context.WithDeadline(context.Background(), end)
defer cancel()
last := ""
for time.Now().Before(end) {
out, errOut, code, err := runCLI(ctx, env.h, "ops", "chunk", "restore", "--volume", target, "--status-addr", env.hosts["n-"+target].status, "--status")
var st struct {
Phase string `json:"phase"`
}
if err == nil && code == 0 && json.Unmarshal([]byte(out), &st) == nil {
if st.Phase == "failed" {
t.Fatalf("restore of %s failed: %s", target, out)
}
if st.Phase == "independent" && time.Now().Before(end) {
return
}
}
last = out + errOut
time.Sleep(200 * time.Millisecond)
}
t.Fatalf("%s never became independent within %v; last status: %s", target, bound, last)
}
// runCLI runs sw-block under ctx and returns its output and exit status. It
// never fails the test, so a worker goroutine may call it; a failure to run
// or a cancelled context comes back as err.
func runCLI(ctx context.Context, h *plannedHandoffHarness, args ...string) (string, string, int, error) {
cmd := exec.CommandContext(ctx, h.cli, args...)
cmd.Dir = h.dir
cmd.WaitDelay = 5 * time.Second
var stdout, stderr strings.Builder
cmd.Stdout, cmd.Stderr = &stdout, &stderr
err := cmd.Run()
var exit *exec.ExitError
switch {
case err == nil:
return stdout.String(), stderr.String(), 0, nil
case errors.As(err, &exit) && ctx.Err() == nil:
return stdout.String(), stderr.String(), exit.ExitCode(), nil
}
return stdout.String(), stderr.String(), -1, fmt.Errorf("sw-block %q: %w", args, err)
}
// ladderImage is a written picture of a volume: blocks in several chunks.
func ladderImage(tag string, chunks []uint64, perChunk int) map[uint64][]byte {
img := map[uint64][]byte{}
for _, c := range chunks {
for i := 0; i < perChunk; i++ {
lba := c*ladderChunkBlocks + uint64(i)*37
img[lba] = pattern(fmt.Sprintf("%-8s%08d", tag, lba)[:16])
}
}
return img
}
func (env *handoffEnv) writeImage(t *testing.T, hostID string, img map[uint64][]byte) {
t.Helper()
c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN)
defer c.close()
for lba, b := range img {
c.write(t, lba, b)
}
c.flush(t)
}
// requireImage reads every block of img on the host and the zeros next to
// each written run, and the edge blocks. Every block of later (writes made
// after the snapshot that img pictures) that img does not hold must read
// zero: data written after the snapshot must not leak into its restore.
func (env *handoffEnv) requireImage(t *testing.T, hostID string, img map[uint64][]byte, later ...map[uint64][]byte) {
t.Helper()
zero := make([]byte, 4096)
c := dialNVMe(t, env.hosts[hostID].nvme, plannedHandoffNQN)
defer c.close()
for lba, want := range img {
if got := c.read(t, lba, 4096); !bytes.Equal(got, want) {
t.Fatalf("%s: block %d differs from the snapshot", hostID, lba)
}
if _, written := img[lba+1]; !written && lba+1 <= ladderLastBlock {
if got := c.read(t, lba+1, 4096); !bytes.Equal(got, zero) {
t.Fatalf("%s: block %d should be zero", hostID, lba+1)
}
}
}
for _, l := range later {
for lba := range l {
if _, held := img[lba]; held {
continue // an overwrite: img's value was checked above
}
if got := c.read(t, lba, 4096); !bytes.Equal(got, zero) {
t.Fatalf("%s: block %d was written after the snapshot and should read zero", hostID, lba)
}
}
}
c.close()
env.requireEdges(t, hostID)
}
func mergeImages(imgs ...map[uint64][]byte) map[uint64][]byte {
out := map[uint64][]byte{}
for _, img := range imgs {
for k, v := range img {
out[k] = v
}
}
return out
}
// TestSnapshotLadderC1FullRestore: blocks in five chunks are written and a
// snapshot taken, then some of them overwritten and new chunks written; the
// snapshot's restore into a new volume, once its status says independent,
// equals the snapshot block by block, without the later writes.
func TestSnapshotLadderC1FullRestore(t *testing.T) {
env := startLadderEnv(t, "v2")
img := ladderImage("c1", []uint64{0, 1, 7, 20, 63}, 8)
env.writeImage(t, "s1", img)
env.snapshot(t, "s1", "v1", "full")
later := mergeImages(ladderImage("c1later", []uint64{1, 20}, 8), ladderImage("c1new", []uint64{9, 33}, 3))
env.writeImage(t, "s1", later)
env.restoreInto(t, "v1", "full", "v2")
env.waitIndependent(t, "v2")
env.requireImage(t, "n-v2", img, later)
}
// TestSnapshotLadderC2IncrementalRestore: three snapshots, each after more
// writes; the restores of the second and the third, each to independence,
// equal those snapshots (the earlier writes and theirs, nothing later).
func TestSnapshotLadderC2IncrementalRestore(t *testing.T) {
env := startLadderEnv(t, "v2", "v3")
img1 := ladderImage("c2one", []uint64{0, 5}, 4)
img2 := ladderImage("c2two", []uint64{5, 9}, 3) // overwrites some of chunk 5
img3 := ladderImage("c2three", []uint64{0, 30}, 2)
env.writeImage(t, "s1", img1)
env.snapshot(t, "s1", "v1", "s1")
env.writeImage(t, "s1", img2)
env.snapshot(t, "s1", "v1", "s2")
env.writeImage(t, "s1", img3)
env.snapshot(t, "s1", "v1", "s3")
env.restoreInto(t, "v1", "s2", "v2")
env.waitIndependent(t, "v2")
env.requireImage(t, "n-v2", mergeImages(img1, img2), img3) // nothing written after s2, chunk 30 included
env.restoreInto(t, "v1", "s3", "v3")
env.waitIndependent(t, "v3")
env.requireImage(t, "n-v3", mergeImages(img1, img2, img3))
}
// TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt: a restored volume,
// once its status says independent, is written and snapshotted itself, then
// written again; that snapshot holds its first writes and not the later
// ones, and the source's snapshot, also written past, still restores
// unchanged. Every write to the restored volume comes after it is
// independent.
func TestSnapshotLadderC3RestoreThenWriteThenSnapshotIt(t *testing.T) {
env := startLadderEnv(t, "v2", "v3", "v4")
src := ladderImage("c3src", []uint64{0, 3}, 4)
env.writeImage(t, "s1", src)
env.snapshot(t, "s1", "v1", "base")
srcLater := ladderImage("c3srclater", []uint64{3, 15}, 2)
env.writeImage(t, "s1", srcLater)
env.restoreInto(t, "v1", "base", "v2")
env.waitIndependent(t, "v2")
own := ladderImage("c3own", []uint64{3, 11}, 3)
env.writeImage(t, "n-v2", own)
env.snapshot(t, "n-v2", "v2", "mine")
ownLater := ladderImage("c3ownlater", []uint64{0, 11, 25}, 2)
env.writeImage(t, "n-v2", ownLater)
env.restoreInto(t, "v2", "mine", "v3")
env.waitIndependent(t, "v3")
env.requireImage(t, "n-v3", mergeImages(src, own), ownLater, srcLater)
env.restoreInto(t, "v1", "base", "v4") // the source's snapshot is unchanged
env.waitIndependent(t, "v4")
env.requireImage(t, "n-v4", src, srcLater, own, ownLater)
}
@@ -2,6 +2,7 @@ package authority
import (
"errors"
"log"
"sort"
"sync"
"time"
@@ -10,7 +11,7 @@ import (
// ============================================================
// P14 S4 — Observation Store
//
// Push-ingested latest-wins observation store per ServerID. The
// Push-ingested latest-wins observation store per replica slot. The
// store computes derived freshness on read, based on wall-clock
// time vs ObservedAt + FreshnessWindow. Expired observations stay
// visible; they are just semantically ineligible for supported
@@ -35,18 +36,19 @@ type ObservationStore struct {
revision uint64
onMutation func()
// supersededCount counts heartbeat ingests that were dropped
// because a newer ObservedAt was already stored for the same
// ServerID. Diagnostic only — PCDD-DELAYED-HB-001 evidence
// supersededCount counts slot reports that were dropped because a
// newer ObservedAt was stored for that server/volume/replica slot.
// Diagnostic only — PCDD-DELAYED-HB-001 evidence
// surface. Not an authority input; publisher / controller /
// evidence minting paths MUST NOT read it. Exposed via
// SupersededCount().
supersededCount uint64
supersededSlots map[[3]string]uint64
}
// SupersededCount returns the total number of ingests that were
// dropped because a newer observation from the same server was
// already stored. Diagnostic surface for PCDD-DELAYED-HB-001.
// SupersededCount returns the total number of slot reports dropped
// because a newer report of that same server/volume/replica was stored.
// Diagnostic surface for PCDD-DELAYED-HB-001.
// NOT authority input. Monotonic across the lifetime of the store.
func (s *ObservationStore) SupersededCount() uint64 {
s.mu.Lock()
@@ -54,6 +56,14 @@ func (s *ObservationStore) SupersededCount() uint64 {
return s.supersededCount
}
// SupersededSlotCount is the diagnostic count for one reporting slot.
// Like SupersededCount, it is not an authority input.
func (s *ObservationStore) SupersededSlotCount(serverID, volumeID, replicaID string) uint64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.supersededSlots[[3]string{serverID, volumeID, replicaID}]
}
// SlotFact returns the most-recently-observed SlotFact for a
// (volumeID, replicaID) pair across all reporting servers, or
// (zero, false) if no server has reported that slot.
@@ -201,10 +211,11 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat
}
cfg := config.withDefaults()
return &ObservationStore{
config: cfg,
now: now,
startedAt: now(),
observations: map[string]Observation{},
config: cfg,
now: now,
startedAt: now(),
observations: map[string]Observation{},
supersededSlots: make(map[[3]string]uint64),
}
}
@@ -231,11 +242,10 @@ var ErrInvalidObservation = errors.New("observation_store: invalid observation")
// ExpiresAt, and fires the registered mutation callback if
// anything changed.
//
// Latest-wins per ServerID. If an incoming observation has an
// ObservedAt strictly older than the currently-stored one from
// the same server, the store keeps the newer one (ignores the
// stale ingest). No error is returned for that case; it's a
// routine ordering event, not a bug.
// Latest-wins per (ServerID, volume, replica). A slot report strictly
// older than that slot's stored fact is ignored; other slots in the
// observation are accepted independently. No error is returned for
// superseded reports.
func (s *ObservationStore) Ingest(obs Observation) error {
_, err := s.ingest(obs)
return err
@@ -290,44 +300,65 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro
var fn func()
var transitions []SlotHealthTransition
type supersededReport struct {
volume, replica string
sentAt, newest time.Time
total uint64
}
var dropped []supersededReport
// Both the all-superseded and mixed-report paths release mu before
// returning. Logging never runs under the store lock.
defer func() {
for _, d := range dropped {
log.Printf("heartbeat superseded server=%s volume=%s replica=%s sent_at=%s newest=%s total=%d",
obs.ServerID, d.volume, d.replica, d.sentAt.UTC().Format(time.RFC3339Nano), d.newest.UTC().Format(time.RFC3339Nano), d.total)
}
}()
s.mu.Lock()
prev, hadPrev := s.observations[obs.ServerID]
if hadPrev {
if prev.ObservedAt.After(obs.ObservedAt) {
// Out-of-order ingest: keep the newer one already
// stored. No mutation fired.
//
// Diagnostic counter for PCDD-DELAYED-HB-001. Not an
// authority input. Must never be read by publisher /
// controller / evidence minting path — it exists so
// tests and operators can see that a superseded
// heartbeat was observed and recorded-as-superseded,
// distinct from "silently dropped".
s.supersededCount++
s.mu.Unlock()
return nil, nil
}
}
// Health transitions, from this accepted report against the same
// server's previously stored fact for each slot it carries.
// slot's stored fact. INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53:
// timestamps order one sender's
// slot only; a later report from another slot cannot supersede it.
accepted := make([]SlotFact, 0, len(obs.Slots))
for _, slot := range obs.Slots {
old := ""
var newest time.Time
if hadPrev {
for _, p := range prev.Slots {
if slotKey(p) == slotKey(slot) {
old = p.UnhealthyReason
newest = slotObservedAt(p, prev)
break
}
}
}
if newest.After(slot.ObservedAt) {
s.supersededCount++
key := [3]string{obs.ServerID, slot.VolumeID, slot.ReplicaID}
s.supersededSlots[key]++
dropped = append(dropped, supersededReport{slot.VolumeID, slot.ReplicaID, slot.ObservedAt, newest, s.supersededSlots[key]})
continue
}
accepted = append(accepted, slot)
if old != slot.UnhealthyReason {
transitions = append(transitions, SlotHealthTransition{
VolumeID: slot.VolumeID, ReplicaID: slot.ReplicaID, Old: old, New: slot.UnhealthyReason,
})
}
}
if len(obs.Slots) > 0 && len(accepted) == 0 {
s.mu.Unlock()
return nil, nil
}
obs.Slots = accepted
if hadPrev {
obs.Slots = mergeServerSlots(prev.Slots, obs.Slots)
if prev.ObservedAt.After(obs.ObservedAt) {
// Preserve the newest server metadata without lending its
// timestamp or freshness to another process's slot.
obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server
}
}
s.observations[obs.ServerID] = obs
s.revision++
@@ -0,0 +1,153 @@
package authority
import (
"bytes"
"fmt"
"log"
"strings"
"testing"
"time"
)
type unlockedHeartbeatLog struct {
bytes.Buffer
store *ObservationStore
locked bool
}
func (w *unlockedHeartbeatLog) Write(p []byte) (int, error) {
if w.store.mu.TryLock() {
w.store.mu.Unlock()
} else {
w.locked = true
}
return w.Buffer.Write(p)
}
func TestObservationStore_SupersededSlotLogsAfterUnlock(t *testing.T) {
base := time.Unix(1000, 0)
s := NewObservationStore(FreshnessConfig{}, func() time.Time { return base })
w := &unlockedHeartbeatLog{store: s}
old := log.Writer()
log.SetOutput(w)
t.Cleanup(func() { log.SetOutput(old) })
for _, server := range []string{"one-host", "other-host"} {
for _, volume := range []string{"a", "b"} {
slot := healthySlot(volume, "r1")
if err := s.Ingest(Observation{ServerID: server, ObservedAt: base, Slots: []SlotFact{slot}}); err != nil {
t.Fatal(err)
}
}
}
for _, tc := range []struct{ server, volume string }{{"one-host", "a"}, {"one-host", "a"}, {"one-host", "b"}, {"other-host", "a"}} {
if err := s.Ingest(Observation{ServerID: tc.server, ObservedAt: base.Add(-time.Second), Slots: []SlotFact{healthySlot(tc.volume, "r1")}}); err != nil {
t.Fatal(err)
}
}
if w.locked {
t.Fatal("superseded diagnostic was emitted while the store lock was held")
}
lines := strings.Split(strings.TrimSpace(w.String()), "\n")
if len(lines) != 4 {
t.Fatalf("diagnostics=%q; want one line per dropped slot", w.String())
}
for i, want := range []string{
"server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
"server=one-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=2",
"server=one-host volume=b replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
"server=other-host volume=a replica=r1 sent_at=1970-01-01T00:16:39Z newest=1970-01-01T00:16:40Z total=1",
} {
if !strings.Contains(lines[i], "heartbeat superseded "+want) {
t.Errorf("diagnostic %d=%q; want %q", i, lines[i], want)
}
}
if s.SupersededSlotCount("one-host", "a", "r1") != 2 ||
s.SupersededSlotCount("one-host", "b", "r1") != 1 ||
s.SupersededSlotCount("other-host", "a", "r1") != 1 ||
s.SupersededSlotCount("other-host", "b", "r1") != 0 || s.SupersededCount() != 4 {
t.Fatal("per-slot diagnostics disagree with emitted totals or aggregate count")
}
}
// INV-OBS-SLOT-ORDER-001 / V1-SPEC r2.53: processes on one server order only their
// own (volume, replica) reports; another slot's later timestamp is irrelevant.
func TestObservationStore_InterleavedSendersOrderPerSlot(t *testing.T) {
for _, n := range []int{10, 100} {
t.Run(fmt.Sprintf("%d slots", n), func(t *testing.T) {
base := time.Unix(1000, 0)
now := base.Add(3 * time.Second)
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now })
for round := 0; round < 2; round++ {
for i := n - 1; i >= 0; i-- {
slot := healthySlot(fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1))
slot.DataAddr = fmt.Sprintf("round-%d-slot-%d", round, i)
at := base.Add(time.Duration(round)*time.Second + time.Duration(i)*time.Millisecond)
obs, err := HeartbeatToObservation(serverObs("one-host", at, slot))
if err != nil {
t.Fatal(err)
}
if err := s.Ingest(obs); err != nil {
t.Fatal(err)
}
}
}
for i := 0; i < n; i++ {
got, ok := s.SlotFactOnServer("one-host", fmt.Sprintf("v%d", i/2), fmt.Sprintf("r%d", i%2+1))
if !ok || got.DataAddr != fmt.Sprintf("round-1-slot-%d", i) {
t.Errorf("slot %d lost an independent sender's heartbeat: fact=%+v present=%v", i, got, ok)
}
}
if got := s.SupersededCount(); got != 0 {
t.Fatalf("other senders superseded %d slot reports", got)
}
})
}
}
func TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts(t *testing.T) {
base := time.Unix(1000, 0)
now := base.Add(4 * time.Second)
s := NewObservationStore(FreshnessConfig{FreshnessWindow: 10 * time.Second}, func() time.Time { return now })
report := func(at time.Duration, slots ...SlotFact) []SlotHealthTransition {
t.Helper()
tr, err := s.IngestWithHealthTransitions(Observation{ServerID: "one-host", ObservedAt: base.Add(at), Slots: slots})
if err != nil {
t.Fatal(err)
}
return tr
}
a, b, c := healthySlot("a", "r1"), healthySlot("b", "r1"), healthySlot("c", "r1")
report(3*time.Second, a)
report(time.Second, b)
a.UnhealthyReason, b.UnhealthyReason, c.UnhealthyReason = "stale", "new-b", "new-c"
mutations := 0
s.SetOnMutation(func() { mutations++ })
tr := report(2*time.Second, a, b, c)
if len(tr) != 2 || tr[0].VolumeID != "b" || tr[0].New != "new-b" || tr[1].VolumeID != "c" || tr[1].New != "new-c" {
t.Fatalf("mixed report transitions=%+v; want only b and c", tr)
}
if got, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok || got.UnhealthyReason != "" {
t.Fatalf("stale a replaced its newer fact: %+v, %v", got, ok)
}
if s.SupersededCount() != 1 || mutations != 1 {
t.Fatalf("mixed report: superseded=%d mutations=%d; want 1/1", s.SupersededCount(), mutations)
}
rev := s.Snapshot().revision
if tr := report(time.Second, a, b, c); len(tr) != 0 {
t.Fatalf("all-stale report emitted transitions: %+v", tr)
}
if s.SupersededCount() != 4 || mutations != 1 || s.Snapshot().revision != rev {
t.Fatalf("all-stale report: superseded=%d mutations=%d revision=%d; want 4/1/%d", s.SupersededCount(), mutations, s.Snapshot().revision, rev)
}
// The server's timestamp stays at its newest report; each accepted slot
// keeps its own expiry, including after a delayed mixed report.
now = base.Add(12500 * time.Millisecond)
if _, ok := s.SlotFactOnServer("one-host", "a", "r1"); !ok {
t.Fatal("a lost its later expiry to another slot's older report")
}
for _, volume := range []string{"b", "c"} {
if _, ok := s.SlotFactOnServer("one-host", volume, "r1"); ok {
t.Fatalf("%s inherited a's later freshness", volume)
}
}
}
+1 -1
View File
@@ -144,7 +144,7 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
}
if _, line, ok := p.workspaceLineLocked(volume); ok {
if s == nil || s.Ack == nil || s.Ack.Epoch != line.info.Epoch || s.Ack.ReplicaID != line.info.ReplicaID {
return fmt.Errorf("workspace delete: live authority requires clean revocation ACK")
return fmt.Errorf("workspace delete: live authority requires clean revocation ACK: revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete")
}
} else if pendingPlacement {
return fmt.Errorf("workspace delete: placement may have queued authority")
@@ -0,0 +1,85 @@
package chunkstore
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type attachLookupProjection struct{}
func (attachLookupProjection) Projection() frontend.Projection {
return frontend.Projection{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1, Healthy: true}
}
// V1-SPEC r2.55 gap 10; INV-WS-CLAIM-BEFORE-SERVE-001.
// Real gRPC lookup errors pass through SWFS and a fresh durable provider.
// An existing HEAD must never become a bootstrap claim or an I/O-ready volume.
func TestAttachLookupUnavailableIsNotAnAbsentHead(t *testing.T) {
for _, code := range []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.PermissionDenied, codes.Internal} {
t.Run(code.String(), func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
head := storage.ChunkHead{Gen: 7, Epoch: 3, Holder: "node/r1", State: storage.ChunkHeadActive}
entry, err := headEntry(head)
if err != nil {
t.Fatal(err)
}
f := &fakeFilerGRPC{lookupResp: &filerpb.LookupDirectoryEntryResponse{Entry: entry}}
swfs := startFakeFiler(t, f)
remote, err := NewChunkRemote(swfs, newFakeBlobs(), "/chunks/v1")
if err != nil {
t.Fatal(err)
}
before, err := remote.GetHead(ctx)
if err != nil || before.Gen != 7 {
t.Fatalf("pre-existing HEAD=%+v error=%v", before, err)
}
f.mu.Lock()
// The absence sentinel inside an Unavailable message is still an error.
f.lookupErr = status.Error(code, "lookup failed: "+filerNotFoundText)
f.mu.Unlock()
if h, err := remote.GetHead(ctx); err == nil || errors.Is(err, ErrNotFound) || status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) {
t.Fatalf("failed lookup became an absent HEAD: head=%+v error=%v", h, err)
}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16,
ChunkHolder: "node/r1",
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, attachLookupProjection{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := p.RecoverVolume(ctx, "v1"); status.Code(err) != code || !strings.Contains(err.Error(), "lookup failed: "+filerNotFoundText) {
t.Fatalf("attach error=%v; want preserved %s", err, code)
}
if err := p.AdmitsIO("v1"); err == nil {
t.Fatal("failed HEAD lookup admitted guest I/O")
}
f.mu.Lock()
created, updated := f.lastCreate, f.lastUpdate
f.lookupErr = nil
f.mu.Unlock()
if created != nil || updated != nil {
t.Fatalf("failed lookup attempted a HEAD CAS: create=%+v update=%+v", created, updated)
}
after, err := remote.GetHead(ctx)
if err != nil || after.Gen != head.Gen || after.Holder != head.Holder || after.Epoch != head.Epoch {
t.Fatalf("failed attach changed HEAD: %+v error=%v", after, err)
}
})
}
}
@@ -1285,6 +1285,7 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
// readAt + deadline, the last moment this fork can publish
// (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed.
readAt := c.now()
deadline := readAt.Add(c.deadline())
var shareToken string
if c.guard != nil { // the shared HEAD is the snapshot's, read below
if shareToken, err = c.guard.Begin(ctx, req.Source); err != nil {
@@ -1334,6 +1335,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
req.Target, req.Source, req.Snapshot, existing.Fork.SourceGen, snap.HeadGen)
}
} else {
if !c.now().Before(deadline) {
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; VOLUME not written", req.Target)
}
vol := VolumeInfo{Format: volumeFormat, VolumeID: req.Target, Geometry: snap.geo, Origin: origin, CreatedNs: c.now().UnixNano(),
Parent: &Parent{VolumeID: req.Source, Snapshot: req.Snapshot, Gen: snap.HeadGen}, Fork: record}
ve, err := volumeEntry(vol, req.RequestID)
@@ -1355,6 +1359,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
existing = vol
}
if !c.now().Before(deadline) {
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; manifest preparation not started", req.Target)
}
head, upgradeIDs, err := c.prepareLegacyHead(ctx, dstRoot, storage.ChunkHead{}, head, snap.geo)
defer c.dropManifestIntents(ctx, dstRoot, upgradeIDs)
if err != nil {
@@ -1365,7 +1372,9 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For
return ForkResult{}, err
}
he.Extended[extReq] = []byte(req.RequestID)
deadline := readAt.Add(c.deadline())
if !c.now().Before(deadline) {
return ForkResult{}, catErr(CodeDeadlineExceeded, true, nil, "fork %s: deadline passed; copy intent not written", req.Target)
}
id, err := putIntent(ctx, c.f, dstRoot, storage.ChunkIntent{Gen: 0, Epoch: 0, Holder: tag, Keys: headKeys(head), Segments: head.Segments, ChunkBytes: head.ChunkBytes,
DeadlineNs: deadline.UnixNano()})
if err != nil {
@@ -0,0 +1,233 @@
package chunkstore
import (
"context"
"errors"
"path"
"strings"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
// errCrashed is what a filer call returns once the process that issued it
// is dead.
var errCrashed = errors.New("crashed")
// crashFiler models a blockvolume killed in the middle of a catalog
// operation: at the chosen filer call it dies, before or after that call
// reaches the filer, and from then on no call of it reaches the filer, so
// none of its cleanup runs. Blob calls are not intercepted (snapshot create
// writes entries only).
type crashFiler struct {
manifestFilerBlobs
mu sync.Mutex
dead bool
match func(op, p string) bool // the call at which the process dies
after bool // the call reaches the filer, its reply is lost
}
func (c *crashFiler) gate(op, p string) (pass, die bool) {
c.mu.Lock()
defer c.mu.Unlock()
if c.dead {
return false, false
}
if c.match(op, p) {
c.dead = true
return c.after, true
}
return true, false
}
func (c *crashFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
if pass, _ := c.gate("lookup", path.Join(dir, name)); !pass {
return nil, errCrashed
}
return c.manifestFilerBlobs.LookupEntry(ctx, dir, name)
}
func (c *crashFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
pass, die := c.gate("create", path.Join(dir, e.GetName()))
if !pass {
return errCrashed
}
err := c.manifestFilerBlobs.CreateEntry(ctx, dir, e, oExcl)
if die {
return errCrashed
}
return err
}
func (c *crashFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
pass, die := c.gate("update", path.Join(dir, e.GetName()))
if !pass {
return errCrashed
}
err := c.manifestFilerBlobs.UpdateEntry(ctx, dir, e, expected)
if die {
return errCrashed
}
return err
}
func (c *crashFiler) ListEntries(ctx context.Context, dir, prefix, startAfter string, limit uint32) ([]*filerpb.Entry, error) {
if pass, _ := c.gate("list", dir); !pass {
return nil, errCrashed
}
return c.manifestFilerBlobs.ListEntries(ctx, dir, prefix, startAfter, limit)
}
func (c *crashFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
pass, die := c.gate("delete", path.Join(dir, name))
if !pass {
return errCrashed
}
err := c.manifestFilerBlobs.DeleteEntry(ctx, dir, name, expected)
if die {
return errCrashed
}
return err
}
// TestCatalogRestartAfterAbandonedSnapshot: a snapshot create of s1 whose
// process dies at each of its filer steps (after the name record, after the
// intent, with the attempt create lost before or after it applied, after the
// create before the intent is dropped), then a catalog restarted over the
// same filer. Whatever the step:
// - the create never answers success unless its attempt entry was
// written;
// - the list shows s1 only if its attempt entry was written, and then as
// the snapshot of the cut HEAD, never a partial one;
// - a retry with the same request id completes s1, listed once;
// - a new snapshot of another name is taken and listed;
// - when s1 is abandoned unpublished, its name record still holds the name
// (another request gets snapshot_exists) and blocks volume delete
// (volume_has_snapshots), and deleting s1 settles it: the name is free
// and the volume delete completes.
func TestCatalogRestartAfterAbandonedSnapshot(t *testing.T) {
isName := func(p string) bool { return p == path.Join(catBase, "v1", snapNamesDir, "s1") }
isIntent := func(p string) bool { return strings.HasPrefix(p, path.Join(catBase, "v1", intentsDir)+"/") }
isAttempt := func(p string) bool { return isSnapPath(p, "v1", "s1") }
for _, tc := range []struct {
name string
op string
at func(string) bool
after bool
published bool // the attempt entry was written before the crash
}{
{"after the name record", "create", isName, true, false},
{"after the intent", "create", isIntent, true, false},
{"attempt create lost before it applied", "create", isAttempt, false, false},
{"attempt create applied, reply lost", "create", isAttempt, true, true},
{"before the intent is dropped", "delete", isIntent, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
f, b, _, h := deleteFixture(t)
ctx := context.Background()
detachHead(t, f, b, "v1")
crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: tc.after,
match: func(op, p string) bool { return op == tc.op && tc.at(p) }}
dying, err := NewCatalog(crashed, catBase)
if err != nil {
t.Fatal(err)
}
// A crash before the attempt entry is written cannot return success;
// once it is written the create has succeeded (the intent drop
// after it is best effort), whatever the caller then hears.
if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil && !tc.published {
t.Fatal("the create returned success although its process died before publishing")
}
crashed.mu.Lock()
died := crashed.dead
crashed.mu.Unlock()
if !died {
t.Fatalf("the create never reached the step %q", tc.name)
}
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase) // the restarted process
if err != nil {
t.Fatal(err)
}
list := func() []SnapshotInfo {
t.Helper()
l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{})
if err != nil {
t.Fatal(err)
}
return l
}
switch l := list(); {
case !tc.published && len(l) != 0:
t.Fatalf("an unpublished snapshot is listed after the restart: %+v", l)
case tc.published && (len(l) != 1 || l[0].Name != "s1" || l[0].HeadGen != h.Gen || l[0].State != SnapActive):
t.Fatalf("after the restart the list is %+v; want s1 of HEAD gen %d, active", l, h.Gen)
}
if !tc.published {
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "other"}, h); CodeOf(err) != CodeSnapshotExists {
t.Fatalf("another request for the abandoned name: %v; want snapshot_exists (the name record holds it)", err)
}
if _, err := c.DeleteVolume(ctx, "v1", nil); CodeOf(err) != CodeVolumeHasSnapshots {
t.Fatalf("volume delete with the abandoned name record: %v; want volume_has_snapshots", err)
}
}
info, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h)
if err != nil || info.Name != "s1" || info.HeadGen != h.Gen {
t.Fatalf("retry with the same request id after the restart: %+v %v", info, err)
}
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s2", RequestID: "r2"}, h); err != nil {
t.Fatalf("the next snapshot after the restart: %v", err)
}
if l := list(); len(l) != 2 || l[0].Name != "s1" || l[1].Name != "s2" {
t.Fatalf("after the retry and the next snapshot the list is %+v; want s1, s2 once each", l)
}
for _, name := range []string{"s1", "s2"} {
if _, err := c.DeleteSnapshot(ctx, "v1", name); err != nil {
t.Fatalf("delete %s: %v", name, err)
}
}
if l := list(); len(l) != 0 {
t.Fatalf("after deleting both the list is %+v", l)
}
if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed {
t.Fatalf("volume delete after the snapshots are deleted: %+v %v", res, err)
}
})
}
}
// TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete: an abandoned,
// never-published s1 (the process died after its name record) is settled by
// deleting it without a retry: the name is then free for another request and
// the volume delete is no longer blocked by it.
func TestCatalogAbandonedUnpublishedSnapshotIsSettledByDelete(t *testing.T) {
f, b, _, h := deleteFixture(t)
ctx := context.Background()
detachHead(t, f, b, "v1")
crashed := &crashFiler{manifestFilerBlobs: manifestFilerBlobs{f, gcBlobs{b}}, after: true,
match: func(op, p string) bool { return op == "create" && p == path.Join(catBase, "v1", snapNamesDir, "s1") }}
dying, err := NewCatalog(crashed, catBase)
if err != nil {
t.Fatal(err)
}
if _, err := dying.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r1"}, h); err == nil {
t.Fatal("the create returned success although its process died")
}
c, err := NewCatalog(manifestFilerBlobs{f, gcBlobs{b}}, catBase)
if err != nil {
t.Fatal(err)
}
if st, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || st != SnapDeleting {
t.Fatalf("delete of the abandoned s1: %q %v", st, err)
}
if l, _, err := c.ListSnapshots(ctx, "v1", ListOptions{}); err != nil || len(l) != 0 {
t.Fatalf("list after settling: %+v %v", l, err)
}
if res, err := c.DeleteVolume(ctx, "v1", nil); err != nil || !res.Completed {
t.Fatalf("volume delete after settling the abandoned name: %+v %v", res, err)
}
}
@@ -2,6 +2,7 @@ package chunkstore
import (
"context"
"fmt"
"strings"
"testing"
"time"
@@ -75,3 +76,118 @@ func TestCatalog_PublishIsBoundedByTheDeadline(t *testing.T) {
f.stallCreate = nil
}
}
// A delayed source read must not create a target, and an expired attempt
// after VOLUME must not create a copy intent, even one it later deletes.
func TestFork_ExpiredAttemptWritesNoNewMetadata(t *testing.T) {
for _, origin := range []string{OriginFork, OriginRestore} {
for _, stage := range []string{"source_read", "volume_written", "live"} {
t.Run(origin+"/"+stage, func(t *testing.T) {
f, _, c, h := catalogFixture(t)
ctx := context.Background()
now := time.Unix(1800000000, 0)
c.SetClock(func() time.Time { return now })
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h); err != nil {
t.Fatal(err)
}
start := now
volumeWrites, intentWrites := 0, 0
f.afterLookup = func(p string) {
if stage == "source_read" && isSnapPath(p, "v1", "s1") {
now = start.Add(DefaultOpDeadline)
}
}
f.beforeCreate = func(p string) {
if p == catBase+"/v2/VOLUME" {
volumeWrites++
if stage == "volume_written" {
now = start.Add(DefaultOpDeadline)
}
}
if strings.HasPrefix(p, catBase+"/v2/intents/") {
intentWrites++
}
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
var err error
if origin == OriginFork {
_, err = c.Fork(ctx, req)
} else {
_, err = c.Restore(ctx, req)
}
f.afterLookup, f.beforeCreate = nil, nil
if stage == "live" {
if err != nil || volumeWrites != 1 || intentWrites != 1 {
t.Fatalf("live attempt: err=%v VOLUME=%d intents=%d", err, volumeWrites, intentWrites)
}
return
}
if CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("expired attempt: %v", err)
}
wantVolume := 0
if stage == "volume_written" {
wantVolume = 1
}
if volumeWrites != wantVolume || intentWrites != 0 {
t.Fatalf("expired attempt wrote VOLUME=%d intents=%d; want %d and 0", volumeWrites, intentWrites, wantVolume)
}
if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil {
t.Fatal("expired attempt published HEAD")
}
if intents := intentsOf(t, f, "v2"); len(intents) != 0 {
t.Fatalf("expired attempt left intents: %+v", intents)
}
})
}
}
}
// The frozen flat snapshot forces the manifest-upgrade path to create an
// intent before uploading its segment; count creates, even if later removed.
func TestFork_ExpiredLegacyPreparationWritesNoIntent(t *testing.T) {
for _, origin := range []string{OriginFork, OriginRestore} {
for _, expired := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/expired=%t", origin, expired), func(t *testing.T) {
f, c, r := preF4ForkFixture(t, false)
now := time.Unix(1800000000, 0)
start := now
c.SetClock(func() time.Time { return now })
intents := 0
f.beforeCreate = func(p string) {
if p == catBase+"/v3/VOLUME" && expired {
now = start.Add(DefaultOpDeadline)
}
if strings.HasPrefix(p, catBase+"/v3/intents/") {
intents++
}
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v3", RequestID: "legacy-deadline"}
var err error
if origin == OriginFork {
_, err = c.Fork(context.Background(), req)
} else {
_, err = c.Restore(context.Background(), req)
}
f.beforeCreate = nil
if expired {
if CodeOf(err) != CodeDeadlineExceeded || intents != 0 {
t.Fatalf("expired legacy attempt: err=%v intent creates=%d; want deadline and zero", err, intents)
}
if _, err := f.LookupEntry(context.Background(), catBase+"/v3", headName); err == nil {
t.Fatal("expired legacy attempt published HEAD")
}
} else {
if err != nil || intents != 2 {
t.Fatalf("live legacy attempt: err=%v intent creates=%d; want success and upgrade+copy intents", err, intents)
}
dst, err := NewChunkRemote(f, r.b, catBase+"/v3")
if err != nil {
t.Fatal(err)
}
assertLegacyImage(t, dst)
}
})
}
}
}
@@ -370,7 +370,7 @@ func TestFork_RefusalsAndDeadline(t *testing.T) {
t.Fatal("a fork past its deadline wrote a HEAD")
}
c.SetClock(time.Now)
// The VOLUME from the late attempt is reused by its own retry.
// A retry of the expired attempt succeeds under a fresh deadline.
if res, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v4", RequestID: "late"}); err != nil || res.Replayed {
t.Fatalf("retry after the late attempt: %+v %v", res, err)
}
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
@@ -178,9 +179,13 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) {
var pinnedAttempt string
stoppedFork := func(snap, target string) {
t.Helper()
cat.OpDeadline = time.Nanosecond
start := clock
cat.SetClock(func() time.Time { return clock })
original := cat.f
cat.f = expireForkVolumeFiler{Filer: original, target: path.Join(base, target, volumeName), expire: func() { clock = start.Add(DefaultOpDeadline) }}
_, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: snap, Target: target, RequestID: "f"})
cat.OpDeadline = 0
cat.f = original
cat.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock })
if CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("fork %s past its deadline: %v; want deadline_exceeded", target, err)
}
@@ -231,3 +236,19 @@ func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) {
}
}
}
// expireForkVolumeFiler advances only after the target identity was stored;
// the retention test therefore exercises an incomplete fork, not an absent one.
type expireForkVolumeFiler struct {
Filer
target string
expire func()
}
func (f expireForkVolumeFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, exclusive bool) error {
err := f.Filer.CreateEntry(ctx, dir, e, exclusive)
if err == nil && path.Join(dir, e.Name) == f.target {
f.expire()
}
return err
}
@@ -25,12 +25,16 @@ func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) {
}
req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}
clock := time.Now()
c.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances
c.OpDeadline = time.Nanosecond
c.SetClock(func() time.Time { return clock })
f.beforeCreate = func(p string) {
if p == catBase+"/v2/VOLUME" {
clock = clock.Add(DefaultOpDeadline)
}
}
if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded {
t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err)
}
c.OpDeadline = 0
f.beforeCreate = nil
if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil {
t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err)
}
@@ -1084,7 +1084,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R
}
report := Recover(h.storage, volumeID)
if report.Err != nil {
h.backend.SetOperational(false, report.Evidence)
h.backend.setRecoveryFailure(report.Evidence, report.Err)
return report, report.Err
}
if chunked {
@@ -0,0 +1,89 @@
package durable_test
import (
"bytes"
"context"
"errors"
"path/filepath"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// INV-FE-ERROR-RETRY-CLASS-001 / V1-SPEC r2.55 side (d), coverage A9.1.
// A real strict-W WAL integrity failure must survive recovery readiness gating
// as a permanent cause. Ordinary awaiting-recovery readiness stays retryable.
func TestRecoveryStoreFaultRemainsPermanentAtGuestIO(t *testing.T) {
root := t.TempDir()
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: root, BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
WALRecoveryTestDisableFlusher: true,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
s, err := p.EnsureStorage("v1")
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
b := p.Backend("v1")
if _, err := b.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) ||
frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady {
t.Fatalf("ordinary pre-recovery gate is not retryable not-ready: %v", err)
}
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if _, err := s.Write(5, block(0xA7)); err != nil {
t.Fatal(err)
}
ws, ok := s.(*storage.WALStore)
if !ok {
t.Fatalf("unexpected store %T", s)
}
if err := ws.SetWMode(storage.WModeStrict); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
restore := corruptWALWrite(t, filepath.Join(root, "v1.bin"), 0xA7)
t.Cleanup(restore)
if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrWALIntegrityFault) {
t.Fatalf("expected real WAL integrity recovery failure: %v", err)
}
n, err := b.Read(ctx, 5*4096, make([]byte, 4096))
if n != 0 || !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("failed recovery guest read: n=%d, want 0 and not-ready: %v", n, err)
}
if got := frontend.ClassifyBackendError(ctx, err); got != frontend.BackendErrorPermanent {
t.Errorf("store-fault recovery became guest retry class %v, want permanent: %v", got, err)
}
if !errors.Is(err, storage.ErrWALIntegrityFault) {
t.Errorf("guest error lost permanent WAL-integrity cause: %v", err)
}
// A later successful recovery clears the old cause. A subsequent ordinary
// readiness pause must not inherit a repaired fault's permanent class.
restore()
if _, err := p.RecoverVolume(ctx, "v1"); err != nil {
t.Fatalf("recovery after repair: %v", err)
}
want := block(0xA7)
got := make([]byte, len(want))
n, err = b.Read(ctx, 5*4096, got)
if err != nil || n != len(want) || !bytes.Equal(got, want) {
t.Fatalf("repaired acknowledged record through backend: n=%d, want %d; matching bytes=%t: %v", n, len(want), bytes.Equal(got, want), err)
}
b.SetOperational(false, "maintenance pause")
_, err = b.Read(ctx, 5*4096, make([]byte, 4096))
if !errors.Is(err, frontend.ErrNotReady) || errors.Is(err, storage.ErrWALIntegrityFault) ||
frontend.ClassifyBackendError(ctx, err) != frontend.BackendErrorNotReady {
t.Fatalf("ordinary pause retained the repaired recovery fault: %v", err)
}
}
@@ -206,6 +206,9 @@ type StorageBackend struct {
// could not follow the store's next LSN). While set, every I/O is
// refused, so a volume never serves without its observer. Under mu.
observerErr error
// recoveryErr retains the typed cause while the operational gate is shut.
// INV-FE-ERROR-RETRY-CLASS-001: permanent leaves survive readiness markers.
recoveryErr error // protected by mu; cleared only by successful readiness
// observerMu serializes moving the store's next LSN (the frontier
// seed) together with rebasing the observer, against installing an
// observer together with its rebase: whichever runs second sees the
@@ -494,6 +497,13 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) {
b.mu.Unlock()
}
func (b *StorageBackend) setRecoveryFailure(evidence string, cause error) {
b.mu.Lock()
b.setOperationalLocked(false, evidence)
b.recoveryErr = cause
b.mu.Unlock()
}
// FirstServing is closed the first time the backend admits I/O (for a chunk
// volume: after its storage claim succeeded) and never reopens. A later loss
// of readiness does not reopen it: the process exit of
@@ -503,6 +513,9 @@ func (b *StorageBackend) FirstServing() <-chan struct{} { return b.firstServing
// The caller owns mu; publication never calls the store or waits for I/O.
func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) {
flipped := !ok && b.operational.Load()
if ok {
b.recoveryErr = nil
}
b.opEvidence.Store(evidence)
b.operational.Store(ok)
if ok && !b.served {
@@ -914,6 +927,9 @@ func (b *StorageBackend) readyCheck() error {
closed := b.closed
chunkFenced := b.chunkFenced
observerErr := b.observerErr
recoveryErr := b.recoveryErr
operational := b.operational.Load()
ev, _ := b.opEvidence.Load().(string)
precopyPending := b.precopy != nil && b.precopy.active
b.mu.Unlock()
if closed {
@@ -928,9 +944,8 @@ func (b *StorageBackend) readyCheck() error {
if precopyPending {
return errPrecopyPaused
}
if !b.operational.Load() {
ev, _ := b.opEvidence.Load().(string)
return fmt.Errorf("%w: %s", frontend.ErrNotReady, ev)
if !operational {
return fmt.Errorf("%w: %s", errors.Join(frontend.ErrNotReady, recoveryErr), ev)
}
return nil
}
@@ -2,6 +2,7 @@ package master
import (
"context"
"strings"
"testing"
"time"
@@ -55,6 +56,10 @@ func TestMarkVolumeDeleting_RefusedWhileAssigned(t *testing.T) {
if status.Code(err) != codes.FailedPrecondition {
t.Fatalf("mark of an assigned volume: %v; want FailedPrecondition", err)
}
want := "revoke the line with its sealed generation (sw-block ops workspace revoke --epoch E --sealed-gen G) and wait for the recorded ACK, then delete"
if !strings.Contains(status.Convert(err).Message(), want) {
t.Fatalf("delete refusal lacks the clean-revocation cure: %v", err)
}
if h.Lifecycle().Deletions.Reserved("live") {
t.Fatal("a refused mark reserved the id")
}
@@ -69,6 +69,9 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-b", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101"}); err != nil {
t.Fatal(err)
}
if _, err = h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9202", CtrlAddr: "127.0.0.1:9102"}); err != nil {
t.Fatal(err)
}
seedVerifiedExistingReplicaPlacement(t, h)
if _, err = h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
@@ -81,7 +84,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
defer conn.Close()
client := control.NewWorkspaceServiceClient(conn)
id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-a", ReplicaId: line.ReplicaID, Epoch: line.Epoch}
lease, err := client.RenewWorkspaceLease(ctx, id)
_, err = client.RenewWorkspaceLease(ctx, id)
if err != nil {
t.Fatal(err)
}
@@ -147,7 +150,7 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
Format int `json:"format"`
Segments map[string]json.RawMessage `json:"segments"`
}
if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 2 || len(root.Segments) == 0 {
if err = json.Unmarshal(stored.Content, &root); err != nil || root.Format != 3 || len(root.Segments) == 0 {
t.Fatalf("CLEAN move must exercise upgraded segmented root: %s %v", stored.Content, err)
}
@@ -168,13 +171,23 @@ func TestIntegrationWorkspaceProductionDetachAndForcedMove(t *testing.T) {
t.Fatal(err)
}
} else {
// Actual master lease expiry, no test clock and no revocation ACK.
timer := time.NewTimer(time.Until(time.Unix(0, lease.ExpiresAtNs)) + 100*time.Millisecond + 20*time.Millisecond)
defer timer.Stop()
select {
case <-timer.C:
case <-ctx.Done():
t.Fatal(ctx.Err())
// The master owns the full horizon/deadline/skew barrier. Wait
// for its affirmative preview, not a locally copied expiry formula.
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
preview, err := client.PreviewWorkspaceMove(ctx, q)
if err != nil {
t.Fatal(err)
}
if preview.Admitted {
break
}
select {
case <-ticker.C:
case <-ctx.Done():
t.Fatalf("forced preview never admitted: %v (last reason %q)", ctx.Err(), preview.Reason)
}
}
q.Force = false
if _, err = client.MoveWorkspace(ctx, q); err == nil {
@@ -0,0 +1,82 @@
package volume
import (
"context"
"strings"
"testing"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// INV-WS-LEASE-001 / V1-SPEC r2.55 gap 9: invalid-reply fencing from a held,
// unexpired lease, rather than passing because a synthetic deadline expired.
func TestWorkspaceGuardFencesOnInvalidReply(t *testing.T) {
for _, tc := range []struct {
name string
change func(*control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact
}{
{"nil", func(*control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { return nil }},
{"volume", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.VolumeId = "other"; return r }},
{"replica", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.ReplicaId = "other"; return r }},
{"epoch", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.Epoch++; return r }},
{"zero validity", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.ValidForNs = 0; return r }},
{"negative validity", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact { r.ValidForNs = -1; return r }},
{"over maximum validity", func(r *control.WorkspaceLeaseFact) *control.WorkspaceLeaseFact {
r.ValidForNs = int64(30*time.Second) + 1
return r
}},
} {
t.Run(tc.name, func(t *testing.T) {
now := time.Now()
calls, stops, acks := 0, 0, 0
client := workspaceTestClient{
renew: func() (*control.WorkspaceLeaseFact, error) {
calls++
r := &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(10 * time.Second)}
if calls == 2 {
r = tc.change(r)
}
return r, nil
},
ack: func() error { acks++; return nil },
}
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client,
&control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", ServerId: "node", Epoch: 1},
func(context.Context) (uint64, error) { stops++; return 7, nil }, func() time.Time { return now })
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := g.Refresh(ctx); err != nil || !g.Held() || !g.Projection().Healthy {
t.Fatalf("valid unexpired lease was not held before injection: %v cause=%s", err, g.FenceCause())
}
if err := g.Refresh(ctx); err == nil || !strings.Contains(err.Error(), "invalid workspace lease reply") {
t.Fatalf("invalid reply did not trigger its own refusal: %v cause=%s", err, g.FenceCause())
}
if !strings.Contains(g.FenceCause(), "invalid lease reply") || g.Held() || g.Projection().Healthy || stops != 1 || acks != 0 {
t.Fatalf("invalid-reply fence: cause=%s held=%v healthy=%v stops=%d acks=%d", g.FenceCause(), g.Held(), g.Projection().Healthy, stops, acks)
}
if err := g.Refresh(ctx); err == nil || g.Held() || g.Projection().Healthy || calls != 2 || stops != 1 || acks != 0 {
t.Fatalf("fenced guard reopened or renewed: err=%v calls=%d stops=%d acks=%d", err, calls, stops, acks)
}
})
}
}
func TestWorkspaceGuardAcceptsMaximumValidReply(t *testing.T) {
now := time.Now()
client := workspaceTestClient{renew: func() (*control.WorkspaceLeaseFact, error) {
return &control.WorkspaceLeaseFact{VolumeId: "v", ReplicaId: "r", Epoch: 1, ValidForNs: int64(30 * time.Second)}, nil
}}
g, err := NewWorkspaceLeaseGuard(workspaceTestView{}, client,
&control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", ServerId: "node", Epoch: 1},
func(context.Context) (uint64, error) { t.Fatal("valid lease drained"); return 0, nil }, func() time.Time { return now })
if err != nil {
t.Fatal(err)
}
if err := g.Refresh(context.Background()); err != nil || !g.Held() || !g.Projection().Healthy {
t.Fatalf("maximum valid lease refused: %v cause=%s", err, g.FenceCause())
}
}
@@ -0,0 +1,248 @@
package storage
import (
"bytes"
"context"
"errors"
"sync"
"testing"
"time"
)
// Single-volume coverage gap 2 (cells P5.4, P6.4, P8.7, P9.4, P10.4, P11.3;
// V1-SPEC r2.55): the holder dies (kill -9) in the middle of a cut, at each
// stage, and restarts. Expected: HEAD is the old image (or, once the CAS
// applied, the new one), never a mix; every synced local write reads back
// after the restart; the next cut succeeds and publishes the volume as it
// is. The crash is modelled as a process death: the store's file is closed
// without any cleanup and every later remote mutation from the dead
// process is lost (crashRemote), so the remote keeps exactly what the dead
// cut had sent.
var errProcessDead = errors.New("injected: the process is dead")
// crashRemote forwards to the fake until killed; after that every remote
// call of the dead process fails without reaching the fake: a dead process
// neither writes nor reads.
type crashRemote struct {
*fakeChunkRemote
mu sync.Mutex
dead bool
puts int
onPut func(n int) // after the n-th successful Put
onCAS func(applied bool)
casSeen bool
beforeCAS bool // kill before the CAS is sent
}
func (r *crashRemote) isDead() bool { r.mu.Lock(); defer r.mu.Unlock(); return r.dead }
func (r *crashRemote) kill() { r.mu.Lock(); r.dead = true; r.mu.Unlock() }
func (r *crashRemote) Put(ctx context.Context, key string, data []byte) error {
if r.isDead() {
return errProcessDead
}
if err := r.fakeChunkRemote.Put(ctx, key, data); err != nil {
return err
}
r.mu.Lock()
r.puts++
n, hook := r.puts, r.onPut
r.mu.Unlock()
if hook != nil {
hook(n)
}
return nil
}
func (r *crashRemote) CASHead(ctx context.Context, expected chunkHeadVersion, next chunkHead) (uint64, error) {
if r.isDead() {
return 0, errProcessDead
}
r.mu.Lock()
before, hook := r.beforeCAS, r.onCAS
r.mu.Unlock()
if before && hook != nil {
hook(false)
return 0, errProcessDead
}
gen, err := r.fakeChunkRemote.CASHead(ctx, expected, next)
if err == nil && hook != nil {
hook(true)
return 0, errProcessDead // the reply never reaches the dead process
}
return gen, err
}
func (r *crashRemote) Delete(ctx context.Context, key string) error {
if r.isDead() {
return errProcessDead
}
return r.fakeChunkRemote.Delete(ctx, key)
}
func (r *crashRemote) PutIntent(ctx context.Context, in chunkIntent) (string, error) {
if r.isDead() {
return "", errProcessDead
}
return r.fakeChunkRemote.PutIntent(ctx, in)
}
func (r *crashRemote) Get(ctx context.Context, key string) ([]byte, error) {
if r.isDead() {
return nil, errProcessDead
}
return r.fakeChunkRemote.Get(ctx, key)
}
func (r *crashRemote) GetHead(ctx context.Context) (chunkHead, error) {
if r.isDead() {
return chunkHead{}, errProcessDead
}
return r.fakeChunkRemote.GetHead(ctx)
}
func (r *crashRemote) ListIntents(ctx context.Context) ([]chunkIntent, error) {
if r.isDead() {
return nil, errProcessDead
}
return r.fakeChunkRemote.ListIntents(ctx)
}
func (r *crashRemote) DeleteIntent(ctx context.Context, id string) error {
if r.isDead() {
return errProcessDead
}
return r.fakeChunkRemote.DeleteIntent(ctx, id)
}
// cutCrashImage is the volume's content as a byte image.
func cutCrashImage(t *testing.T, s *WALStore) []byte {
t.Helper()
img := make([]byte, 0, ctNumBlocks*ctBlockSize)
for lba := uint32(0); lba < ctNumBlocks; lba++ {
b, err := s.Read(lba)
if err != nil {
t.Fatalf("read LBA %d: %v", lba, err)
}
img = append(img, b...)
}
return img
}
func TestChunkCutCrashAtEachStage(t *testing.T) {
stages := []struct {
name string
// arm installs the kill at the stage; applied says whether the
// stage is past the HEAD CAS.
arm func(l *chunkLayerImpl, r *crashRemote, die func())
applied bool
}{
{"after admission", func(l *chunkLayerImpl, r *crashRemote, die func()) { l.testAfterAdmitHook = die }, false},
{"at the barrier, after Sync fixed H", func(l *chunkLayerImpl, r *crashRemote, die func()) {
l.testAfterBarrierSyncHook = func(uint64) { die() }
}, false},
{"during the upload, after the first chunk", func(l *chunkLayerImpl, r *crashRemote, die func()) {
r.onPut = func(n int) {
if n == 1 {
die()
}
}
}, false},
{"before the HEAD CAS is sent", func(l *chunkLayerImpl, r *crashRemote, die func()) {
r.beforeCAS = true
r.onCAS = func(bool) { die() }
}, false},
{"after the HEAD CAS applied, before its reply", func(l *chunkLayerImpl, r *crashRemote, die func()) {
r.onCAS = func(applied bool) {
if applied {
die()
}
}
}, true},
}
for _, st := range stages {
t.Run(st.name, func(t *testing.T) {
ctx := ctTimeout(t)
s, path, crashStore := crashableStore(t)
f := newFakeChunkRemote()
r := &crashRemote{fakeChunkRemote: f}
cfg := ctConfig(1)
l := mustAttach(t, s, r, cfg).(*chunkLayerImpl)
for lba := uint32(0); lba < ctNumBlocks; lba++ {
if _, err := s.Write(lba, makeBlock(ctBlockSize, byte(0x10+lba))); err != nil {
t.Fatal(err)
}
}
mustSyncFlush(t, s)
if _, err := l.Capture(ctx); err != nil {
t.Fatal(err)
}
old, _ := f.GetHead(ctx)
oldImage := f.imageOf(t, old)
// New writes, then the cut that dies.
for lba := uint32(4); lba < 12; lba++ { // chunks 1 and 2
if _, err := s.Write(lba, makeBlock(ctBlockSize, byte(0xC0+lba))); err != nil {
t.Fatal(err)
}
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
want := cutCrashImage(t, s)
die := func() {
r.kill()
crashStore()
}
r.mu.Lock()
r.puts = 0 // count this cut's uploads only
r.mu.Unlock()
st.arm(l, r, die)
// The dying cut gets its own short context: after the death its
// remote calls fail and it may retry them until its deadline (a
// real dead process does not); the restarted process below runs
// on fresh contexts.
dyingCtx, cancelDying := context.WithTimeout(context.Background(), 5*time.Second)
_, cutErr := l.Capture(dyingCtx)
cancelDying()
if !r.isDead() {
t.Fatalf("the stage %q was never reached (puts %d, cut error %v)", st.name, r.puts, cutErr)
}
if cutErr == nil {
t.Fatal("the cut succeeded although the process died during it")
}
if s.v3 != nil && s.v3.ownedMap != nil { // the dead process's map file
_ = s.v3.ownedMap.Close()
s.v3.ownedMap = nil
}
// Restart: the store recovers its WAL; HEAD is old or new, whole.
ctx = ctTimeout(t)
s2, _ := reopen(t, path)
head, _ := f.GetHead(ctx)
got := f.imageOf(t, head)
switch {
case st.applied && !bytes.Equal(got, want):
t.Fatalf("the CAS applied but HEAD (gen %d) is not the new image", head.Gen)
case !st.applied && (head.Gen != old.Gen || !bytes.Equal(got, oldImage)):
t.Fatalf("a cut that died before its CAS changed HEAD: gen %d -> %d", old.Gen, head.Gen)
}
if local := cutCrashImage(t, s2); !bytes.Equal(local, want) {
t.Fatal("a synced local write is lost after the crash and restart")
}
l2 := mustAttach(t, s2, f, cfg)
if _, err := l2.Capture(ctx); err != nil {
t.Fatalf("the first cut after the restart: %v", err)
}
final, _ := f.GetHead(ctx)
if !bytes.Equal(f.imageOf(t, final), want) {
t.Fatalf("the cut after the restart (gen %d) does not publish the volume as it is", final.Gen)
}
if intents, err := f.ListIntents(ctx); err == nil {
t.Logf("stage %q: HEAD gen %d -> crash -> %d -> %d after the next cut; %d intent(s) left", st.name, old.Gen, head.Gen, final.Gen, len(intents))
}
})
}
}
@@ -1,12 +1,6 @@
//go:build chunk_takeover_red
// RED tests for the takeover CAS at attach (W2 spec §6.3, P5). They are
// written by W2 and implemented by W4; the build tag keeps them out of the
// default suite until then. Run them with:
//
// go test -tags chunk_takeover_red -run TestChunkAttach_TakeOver ./core/storage/
//
// The implementation should remove the build tag.
// V1-SPEC r2.55 side (a), coverage cell P10.6;
// INV-WS-CLAIM-BEFORE-SERVE-001. The production attach path first claims
// HEAD, then attaches the chunk layer against that exact claim.
package storage
@@ -36,6 +30,11 @@ func TestChunkAttach_TakeOverRaisesEpoch(t *testing.T) {
s, _ := newChunkTestStore(t)
cfg := ctConfig(2)
cfg.FreshFromHead = true
claimed, err := ClaimChunkHead(ctTimeout(t), f, cfg)
if err != nil {
t.Fatal(err)
}
cfg.RestoreGuard = &ChunkHeadVersion{Gen: claimed.Gen, Epoch: claimed.Epoch}
mustAttach(t, s, f, cfg)
head := f.stats().head
@@ -50,6 +49,12 @@ func TestChunkAttach_TakeOverRaisesEpoch(t *testing.T) {
t.Fatalf("takeover changed chunk %d: %+v, want %+v", k, head.Chunks[k], v)
}
}
for lba := uint32(0); lba < ctNumBlocks; lba++ {
got, err := s.Read(lba)
if err != nil || !bytes.Equal(got, blockOf(takeoverImage(), lba)) {
t.Fatalf("takeover read LBA %d: bytes differ from seeded image, err=%v", lba, err)
}
}
// The old holder (epoch 1) can no longer commit.
if _, err := f.CASHead(ctTimeout(t), chunkHeadVersion{Gen: seeded.Gen, Epoch: 1}, seeded); !errors.Is(err, errChunkHeadPrecondition) {
t.Fatalf("old holder's CAS after takeover: %v, want errChunkHeadPrecondition", err)
@@ -86,7 +91,7 @@ func TestChunkAttach_TakeOverRacesOldHolder(t *testing.T) {
s, _ := newChunkTestStore(t)
cfg := ctConfig(2)
cfg.FreshFromHead = true
layer, err := attachChunkLayer(s, f, cfg)
claimed, err := ClaimChunkHead(ctTimeout(t), f, cfg)
f.mu.Lock()
ran := injected
f.mu.Unlock()
@@ -101,15 +106,24 @@ func TestChunkAttach_TakeOverRacesOldHolder(t *testing.T) {
if h := f.stats().head; h.Holder == cfg.Holder {
t.Fatalf("attach failed (%v) but HEAD names the new holder: %+v", err, h)
}
return
if !errors.Is(err, ErrChunkHeadPrecondition) {
t.Fatalf("competing publication was not a definite claim refusal: %v", err)
}
// Retry the definite refusal through the same claim seam; the
// successful retry must serve every byte of the competing image.
claimed, err = ClaimChunkHead(ctTimeout(t), f, cfg)
if err != nil {
t.Fatal(err)
}
}
t.Cleanup(func() { _ = layer.Close() })
cfg.RestoreGuard = &ChunkHeadVersion{Gen: claimed.Gen, Epoch: claimed.Epoch}
mustAttach(t, s, f, cfg)
head := f.stats().head
if head.Epoch != 2 || head.Holder != cfg.Holder {
if head.Epoch != 2 || head.Holder != cfg.Holder || head.RemoteLSN != 101 {
t.Fatalf("attach returned without taking over: HEAD epoch %d holder %q", head.Epoch, head.Holder)
}
want := f.imageOf(t, head)
want := newer
for lba := uint32(0); lba < ctNumBlocks; lba++ {
got, err := s.Read(lba)
if err != nil {
@@ -290,7 +290,16 @@ func TestSyncControlsIgnoreAmbientAllocation(t *testing.T) {
{"crash-matrix", "TestFdatasyncAcknowledgedWritesSurviveSIGKILL", "prezero"},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
// The crash-matrix child is fdatasync-bound and takes 1-35 s on a
// slow disk, so it runs until the parent test's deadline rather
// than a fixed budget.
var ctx context.Context
var cancel context.CancelFunc
if d, ok := t.Deadline(); ok {
ctx, cancel = context.WithDeadline(context.Background(), d.Add(-10*time.Second))
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+tc.test+"$")
cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=", "SWBLOCK_ALLOCATION="+tc.allocation, "SWBLOCK_PREZERO=0")
@@ -1,8 +0,0 @@
//go:build linux
package storage
const (
checkpointCrashHelperEnv = "SW_BLOCK_CHECKPOINT_CRASH_HELPER"
checkpointCrashPathEnv = "SW_BLOCK_CHECKPOINT_CRASH_PATH"
)
@@ -1,11 +0,0 @@
package storage
import (
"time"
)
func replaceFlusherForTest(s *WALStore, interval time.Duration) {
s.flusher.Stop()
s.flusher = newFlusher(s, flusherConfig{Interval: interval})
go s.flusher.run()
}
@@ -1,22 +0,0 @@
package storage
import (
"strings"
)
func walOffsetsByLBA(s *WALStore) map[uint64]uint64 {
offs := map[uint64]uint64{}
for _, e := range s.dm.snapshot() {
offs[e.LBA] = e.WALOffset
}
return offs
}
func holeWarning(s *WALStore) bool {
for _, w := range s.RecoveryWarnings() {
if strings.HasPrefix(w, WarningWALHoleSuspected+":") {
return true
}
}
return false
}
@@ -1,14 +1,10 @@
package storage
import (
"bytes"
"encoding/binary"
"hash/crc32"
"testing"
)
import "testing"
// crashRecoveryHardeningStore drops the store without a clean close: the
// committer stops, the owned map and the file descriptor close, nothing is
// flushed. Tests reopen the file afterwards to observe crash recovery.
func crashRecoveryHardeningStore(t *testing.T, s *WALStore) {
t.Helper()
s.committer.Stop()
@@ -22,44 +18,3 @@ func crashRecoveryHardeningStore(t *testing.T, s *WALStore) {
t.Fatal(err)
}
}
func recoverySnapshotEntriesByLBA(entries []snapshotEntry) map[uint64]snapshotEntry {
result := make(map[uint64]snapshotEntry, len(entries))
for _, entry := range entries {
result[entry.LBA] = entry
}
return result
}
func rewriteRecoveryRecordForTest(
t *testing.T,
s *WALStore,
recordSize uint64,
absoluteOffset int64,
mutate func([]byte),
) {
t.Helper()
record := make([]byte, recordSize)
if _, err := s.fd.ReadAt(record, absoluteOffset); err != nil {
t.Fatal(err)
}
mutate(record)
binary.LittleEndian.PutUint32(
record[len(record)-8:],
crc32.ChecksumIEEE(record[:len(record)-8]),
)
if _, err := s.fd.WriteAt(record, absoluteOffset); err != nil {
t.Fatal(err)
}
}
func assertRecoveryHardeningBlock(t *testing.T, s *WALStore, lba uint32, want []byte) {
t.Helper()
got, err := s.Read(lba)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatalf("current LBA %d mismatch", lba)
}
}
@@ -1,26 +0,0 @@
package storage
import (
"errors"
"testing"
)
// A failed fsync is sticky for the open store (the "fsyncgate" pattern: on
// Linux the kernel may already have dropped the dirty pages, so a later
// successful fsync proves nothing about them). After the first failure the
// store acknowledges no further Sync, accepts no further write and advances
// no checkpoint, with a typed SubstrateIO failure; only a reopen clears it.
var errInjectedFsync = errors.New("injected fsync failure")
func assertStickyFsync(t *testing.T, err error) {
t.Helper()
if !errors.Is(err, ErrFsyncFailed) {
t.Fatalf("err %v; want the sticky ErrFsyncFailed", err)
}
var rf *RecoveryFailure
if !errors.As(err, &rf) || rf.Kind != StorageRecoveryFailureSubstrateIO {
t.Fatalf("err %v; want a SubstrateIO RecoveryFailure (io_error)", err)
}
}
@@ -230,6 +230,8 @@ stateDiagram-v2
NameHeld --> Published: exclusive create snaps/name/attempt
NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path
Published --> Deleting: DeleteSnapshot or retention (forks do not hold it)
Published --> ForkTarget: deadline live before VOLUME, legacy preparation, copy intent and HEAD
ForkTarget --> ActiveTarget: exclusive HEAD create before deadline (fork or restore)
Deleting --> NameFreed: name record removed
Aborted --> NameFreed: name record removed
NameFreed --> [*]
+33 -5
View File
@@ -81,6 +81,32 @@ Recovery warnings such as `wal_hole_suspected` are recorded in Serving without c
blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves).
**Heartbeat observations, per server/volume/replica slot.**
`ObservationStore.ingest` compares each reported slot only with that slot's
stored timestamp (`slotObservedAt`). An older slot is dropped and counted;
an equal or newer slot is accepted. A mixed report merges accepted slots and
retains every other stored slot. An all-superseded nonempty report changes no
observation or health transition. Accepted slots keep their own freshness;
server metadata keeps its newest timestamp without lending it to another slot.
```mermaid
flowchart LR
Report[Receive heartbeat report] --> Compare{Each slot: stored timestamp newer?}
Compare -->|yes| Drop[Drop and count only that slot]
Compare -->|no| Accept[Accept that slot and its health transition]
Drop --> Mixed{Any accepted slots or an empty report?}
Accept --> Mixed
Mixed -->|yes| Merge[Merge accepted slots; retain other slots and newest server metadata]
Mixed -->|no| Keep[Keep stored observations unchanged]
```
| From | To | Event and guard | Enforced in | Protects |
|---|---|---|---|---|
| Stored observations | Stored observations (slot refused) | stored timestamp for this server/volume/replica is strictly newer than the report; drop and count only this slot | `core/authority/observation_store.go` `ingest`, `slotObservedAt` | `INV-OBS-SLOT-ORDER-001` |
| Stored observations | Stored observations (mixed report merged) | accept equal/newer slots against their own stored timestamp; merge only accepted slots, preserving other slots and independent freshness | `core/authority/observation_store.go` `ingest`, `mergeServerSlots` | `INV-OBS-SLOT-ORDER-001` |
| Stored observations | Stored observations (no mutation) | a nonempty report has no accepted slot; publish no observation mutation or health transition | `core/authority/observation_store.go` `ingest` | `INV-OBS-SLOT-ORDER-001` |
**Assignment line, per volume.**
| From | To | Event and guard | Enforced in | Protects |
@@ -349,7 +375,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
| name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` |
| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | deleting (retention, class `scheduled`) | the snapshot is not among the newest K of class `scheduled` (K from the newest one's `swb.schedule.keep`, default 7); other classes are planned without it | `core/frontend/chunkstore/retention.go` `planRetention` | `INV-SNAP-SCHEDULED-KEEP-001` |
| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, check start + deadline before the target `VOLUME`, legacy manifest preparation, copy intent and HEAD writes; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` |
| restore (Restoring) | Hydrating | M6.Restore.Restoring>Hydrating: the driver starts the walker, paced at a byte rate under the BackgroundFill class | `core/host/volume/chunk_restore.go` `runRestore`; `core/frontend/durable/provider_restore.go` `HydrateVolume`; `core/storage/chunk_hydrate_all.go` `HydrateAllAt` | `INV-RESTORE-HYDRATE-001`, `INV-RESTORE-DRIVER-001` |
| restore (Hydrating) | Owning | M6.Restore.Hydrating>Owning: batch cuts start once chunks are local; the walker and the batches may overlap | `core/host/volume/chunk_restore.go` `runRestore` | `INV-RESTORE-DRIVER-001` |
@@ -467,7 +493,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
315 rows: 244 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 300 new.
317 rows: 246 ACTIVE, 68 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 302 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -724,6 +750,7 @@ Notes:
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | ACTIVE |
| `INV-WS-DELETE-NEEDS-ACK-001` | A workspace volume with a live authority line is not marked deleting until that line has a clean revocation ACK. | M2 live authority: deletion refused until ACK | `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting` | `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`: refusal, cure and no deletion reservation) | — | ACTIVE |
| `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE |
| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE |
@@ -874,7 +901,7 @@ Notes:
| `INV-SNAP-SEAL-POINT-001` | A named snapshot request for a free name runs exactly one cut and stores the HEAD that cut installed as the snapshot; a retry of a recorded request replays that snapshot without cutting; if the cut fails (including a COW window abort) the request fails with that error and records no snapshot. | M5 Admit → Settled, then M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`); `TestChunkControl_SnapshotStoresTheCutHead` (`core/host/volume/chunk_control_adapter_test.go`) | — | ACTIVE |
| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after its cut's HEAD CAS is confirmed (every referenced chunk uploaded first) and its attempt entry is confirmed by its exclusive create or a read-back; an unknown outcome of either reports failure, and an unknown create keeps the snapshot's intent. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `createResolved` | `TestCatalog_SnapshotUncertainCreateKeepsIntent`, `TestCatalog_SnapshotAppliedResponseLostIsConfirmed` (`core/frontend/chunkstore/catalog_settle_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE |
| `INV-FORK-FROM-SEALED-001` | A fork reads only a published, active snapshot: a name with no published attempt or an aborted one is `snapshot_not_found`, a deleting one is `snapshot_deleting`, and every attempt of a fork, a retry included, reads the parent again. | M6 snapshot: published → fork | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `resolveSnap` | `TestFork_RefusalsAndDeadline` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_SweepTombstonesADeadSnapshotAttempt` (`core/frontend/chunkstore/catalog_held_create_test.go`); `TestCatalog_ForkAfterTheMarkRefuses` (`core/frontend/chunkstore/retention_review_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ChunkLifecycleFixed` models the snapshot as a name record plus an attempt path; no fork-from-unpublished property | ACTIVE |
| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE |
| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestFork_ExpiredAttemptWritesNoNewMetadata`, `TestFork_ExpiredLegacyPreparationWritesNoIntent` (`core/frontend/chunkstore/catalog_deadline_test.go`); `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | ACTIVE |
| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retention.go` `planRetention`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retention_test.go`) | — | ACTIVE |
| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE |
| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE |
@@ -911,7 +938,7 @@ Notes:
- `INV-GC-GRACE-RESTART-001`: "past the grace" means past the grace plus the clock-skew bound of `INV-GC-CLOCK-SKEW-001`. The restart on a rooted mark is enforced by reading; no test re-roots a candidate between marks. A deleted fork volume's keys get only the ordinary two-mark grace from their first unrooted mark, with no deleting-time root and no dedicated test.
- `INV-SNAP-SEAL-DURABLE-001`: whether a confirmed filer write has reached disk (filer fsync) is a deployment setting of the SeaweedFS filer, not checked by the code.
- `INV-FORK-FROM-SEALED-001`: the case of a name whose attempt is still in flight (name record present, attempt entry absent) is enforced by reading; no test forks during a held snapshot create.
- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved.
- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. The same deadline is checked before creating target VOLUME, its copy intent and its HEAD; an expired source read creates no target, and expiry after VOLUME leaves it retryable without a new copy intent. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved.
- Restore quantities: batch size N = `DefaultRestoreBatchChunks` (64 chunks per batch cut) and the walker pace = `DefaultRestoreBytesPerSecond` (64 MiB/s, plus the host limiter's BackgroundFill class), both in `core/host/volume/chunk_restore.go`. They move to the quantity table when it exists.
- `INV-SHARE-ACTIVATION-001`: the owner's seal calls `Begin` before the cut that produces the sealed HEAD, so a refused `Begin` cuts nothing.
- `INV-PUBLISH-SETTLED-001`: a publication is a cut, a detach, or an earlier unresolved CAS found applied; a no-op cut reports nothing, and with no hook nothing is queued. One registered drainer delivers; a report already dequeued when Close begins may still reach the hook, and Close waits for it.
@@ -930,6 +957,7 @@ Notes:
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE |
| `INV-OBS-SLOT-ORDER-001` | A heartbeat slot (server, volume, replica) is ordered only against that slot's own previous heartbeat: a later-stamped heartbeat of another slot of the same server never supersedes it. | M2 heartbeat observations: per-slot refusal / mixed merge / all-superseded no mutation (V1-SPEC r2.53) | `core/authority/observation_store.go` `ingest` (per-slot comparison), `slotObservedAt`; `SupersededSlotCount` (diagnostic only) | `TestObservationStore_InterleavedSendersOrderPerSlot`, `TestObservationStore_MixedSlotReportKeepsOnlyNewerFacts`, `TestObservationStore_SupersededSlotLogsAfterUnlock` (`core/authority/observation_store_slot_order_test.go`) | 1.0 limit: a backward wall-clock step longer than the freshness window expires that host's slots; 1.0.1: per-process sequence. | ACTIVE |
| `INV-OBS-SLOT-FROM-EXPECTED-SERVER-001` | A replica's slot in the assembled topology takes addresses and health only from a fresh fact reported by the server its expected slot names; another server's fact for the same replica is never used, so with none from that server the slot is a placeholder. | AUTHORITY/ORDER: observation to assignment line | `core/authority/snapshot_builder.go` `assembleVolumeTopology` | `TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer` (`core/authority/snapshot_slot_server_test.go`) | — (pure assembly; the unit test is the proof form) | ACTIVE |
| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE |
| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE |
@@ -1066,7 +1094,7 @@ A row that names a function existing only on an open pull request says so ("on #
| Term | Meaning | Field(s) | Deciding function (one per side) | Known second derivations to remove | Owner role |
|---|---|---|---|---|---|
| `TERM-HOLDER-001` Holder identity (the primary of a single-copy workspace volume only; supporting replicas are not holders) | The process that may act as primary of a single-copy workspace volume at an epoch is the pair (server id, replica id) at that epoch. A matching replica id or endpoint alone never names it, and a missing server id is refused. No local-root nonce joins it (V1-SPEC r2.45); one live process per volume on a host is the host lock (`TERM-ONE-PROCESS-001`). | `AssignmentFact` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/control.proto`; `server_id` on [#411](https://github.com/seaweedfs/seaweed-block/pull/411)); `WorkspaceIdentity` `server_id`, `replica_id`, `epoch` (`core/rpc/proto/workspace.proto`; `server_id` on #411); the published line's `PublishedLine.IssuedHost` (`core/authority/workspace_lease_view.go`) and the move journal's `WorkspaceMoveRecord.NewHost` (`core/authority/workspace.go`); the volume's `Config.ServerID`, `Config.ReplicaID` (`core/host/volume/host.go`, from `--server-id`, `--replica-id`); the HEAD `Holder`, written as `<server id>/<replica id>` (`cmd/blockvolume/chunk_remote.go` `chunkHolder`) | Master: `core/host/master/workspace_service.go` `services.holderMatches(volume, replica, server, epoch)`, on #411; it gates `RenewWorkspaceLease` and `AckWorkspaceRevoked`, after the host check of #416, and takes the line's owner server from `core/host/master/workspace_binding.go` `Host.workspaceLineOwner`, on #423, the one owner decision for current and historical lines (through `PublishedLine.Owner`, which the snapshot builder's `expectOwnerForLine` also calls). The line's owner server is carried in the published line; a move's line names the move's new host; placement names the owner only for the initial line; an unknown owner is sent empty and never adopted. A volume that has seen an epoch owned by one server never adopts that epoch for another (this covers replays). The safety rule is the refusal to adopt a line naming another server; fencing on a foreign line is defence in depth, and only a process that has adopted a lineage fences, on a strictly newer foreign line. Volume: `core/host/volume/assignment_holder.go` `Host.assignmentNamesSelf`, on #411; called by `applyFact` and `IsSuperseded`. | `Host.applyFact` adopts a fact on the replica id alone. `Host.IsSuperseded` ignores a same-replica line from another server. `Host.recordOtherLine` lets an older line overwrite a newer one. Lease renewals and revocation ACKs carry no server id. All four are removed by #411. The master's status frontends and CSI publish target take the freshest same-replica heartbeat from any server (`ObservationStore.SlotFact` via `statusFrontendsForAssignedVolume`), and the operator's primary node is the placement slot (`serverForReplica`). Both are removed by [#416](https://github.com/seaweedfs/seaweed-block/pull/416), stacked on #411. The master computed the line's owner server twice; #423 makes it one function. | authority (master side); volume host (volume side) |
| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. | authority (grant); volume host (guard) |
| `TERM-LEASE-NOW-001` Lease valid now | The holder may act on its workspace lease at this instant only while the guard has not fenced and host monotonic time is before the start of its last successful renewal plus the granted validity. The granted validity is the master expiry less half the clock-skew bound, capped by the configured TTL. Safety premise for v1.0, alongside one live process per holder (`TERM-ONE-PROCESS-001`): blockmaster's host slews its wall clock, not steps it, while volumes are served; a step larger than the configured skew bound while a lease is live is unsupported (see `docs/operator-guide.md`, Clock safety requirement). This closes coverage gap 8 by a documented premise, not a wall-step test. | `WorkspaceLease` `ExpiresAtNS`, `MaxClockSkewNS`, and the lease view's durable horizon and granted deadline (`core/authority/workspace_lease_view.go`); `WorkspaceLeaseFact` `valid_for_ns`, `expires_at_ns`, `revoking` (`core/rpc/proto/workspace.proto`); `WorkspaceLeaseGuard` `until`, `fenced` (`core/host/volume/workspace_lease.go`) | Holder: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.permits`. Master: `core/authority/workspace_lease_view.go` `Publisher.WorkspaceLeaseValidity` / `workspaceLeaseValidityAt` is shared by renewal admission, `leaseFact` and `AckWorkspaceRevocation`. `WorkspaceLeaseValidity` reads the publisher clock; its leaf calculation uses the larger configured/persisted skew and configured TTL. `Publisher.RenewWorkspaceLease`. `firstWorkspaceGrant` and `regrantWorkspaceLease` are reached only from it, and only it starts the extender `extendWorkspaceLease`. | `WorkspaceLeaseGuard.drain` checks `now < until` again inline before the ACK, and `WorkspaceLeaseGuard.Refresh` repeats the expiry check of `permits`: open (both should call one predicate). The host reply sanity bound in `Refresh` still repeats the publisher's default 30 s TTL: open. Not a duplicate: `Publisher.forcedMoveBarrierLocked` decides the opposite term, "the lease is over for the master" (the horizon and the deadline each plus the full skew bound), which a forced move and a re-grant need. Follow-up for 1.0.1: split `workspaceNow` into wall and monotonic sources so the barrier for in-memory lines uses monotonic time, and add a real independent wall-step test. No new clock seam is added in v1.0. | authority (grant); volume host (guard) |
| `TERM-SERVING-001` Serving / ready | A workspace primary claims HEAD, listens, reports ready and admits I/O only while its lease guard permits now and its durable backend is operational. Without a granted lease it holds at the gate and exits 75 after the start-time wait. | `frontend.Projection.Healthy`; the `StorageBackend` operational flag and its evidence, reported as `VolumeStatus.Operational` (`core/frontend/durable`); `StatusProjection.FrontendPrimaryReady` (and `NotReadyReason`, on [#410](https://github.com/seaweedfs/seaweed-block/pull/410)); the ALUA and ANA state; `HeartbeatSlot.frontends` | Authority side: `core/host/volume/projection_bridge.go` `AdapterProjectionView.projectionWithSupersede`, which ANDs in `WorkspaceLeaseGuard.permits` for workspace volumes. Storage side: the `StorageBackend` operational flag (`core/frontend/durable/storage_adapter.go`), written only by `SetOperational` and read by `readyCheck`. The one decision of both sides together is `StorageBackend.AdmitsIO` (the guarded AND), read by the status, the frontend start gate and every I/O: on #410 (today `StorageBackend.gate` on `main`). | `StatusServer.authorityProjection` derives `FrontendPrimaryReady` from the authority view alone, and it repeats the supersede and supporting tests that `Healthy` already contains. #410 adds the backend half in `statusProjection`; the repeated tests remain open. The frontends listen whether or not the backend admits I/O: #410 holds them in `awaitBackendAdmitsIO` until it does. #410 replaces its earlier `backendAdmitsIO` (which read only `VolumeStatus.Operational`) with `StorageBackend.AdmitsIO`. A later lease fence ends the process on [#409](https://github.com/seaweedfs/seaweed-block/pull/409). `projectionALUAProvider.ALUAState` and `projectionANAProvider.ANAState` (`cmd/blockvolume`) follow the projection only: open. The start-time wait (`chunkAuthorityWait`; `ProviderConfig.ChunkAssignmentTimeout`, 30 s by default) ends once, and the process then stays up without serving: #409 makes it exit 75. iSCSI reports a not-ready or busy backend as a medium error, while NVMe retries the same error: [#415](https://github.com/seaweedfs/seaweed-block/pull/415) (`frontend.ClassifyBackendError`). The heartbeat `Frontends` are set when the listeners start and cleared only at shutdown: open. | volume host |
| `TERM-STOP-SUPERSEDED-001` Superseded | A newer published line for this volume names another holder (another replica, or the same replica on another server) at or above this process's epoch and endpoint version. From then on the process is not healthy. | `Host.lastOther` (an `AssignmentFact`); the process's own epoch and endpoint version | Volume: `core/host/volume/host.go` `Host.IsSuperseded`. Its same-replica branch, and the ordered `recordOtherLine` it reads, are on #411. | The status repeat listed under `TERM-SERVING-001`. `Host.IsCurrentReplicaSuperseded` (on #409) and `Host.promotionReady` call `IsSuperseded` with other lineages. They are wrappers, not second derivations. | volume host |
| `TERM-STOP-LEASE-FENCED-001` Lease fenced / revoked | The lease guard has latched: its deadline passed, a reply was invalid or late, the lease is revoking, or the process is stopping. A fenced guard never reopens. The host drains, and only when the lease was revoked does it acknowledge with the HEAD generation. | `WorkspaceLeaseGuard` `fenced`, `cause`, `revoked` (`core/host/volume/workspace_lease.go`) | Volume: `core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard.fenceLocked`, the one writer of `fenced`; it is read through `permits`. | `Host.FenceWorkspaceLease` and `runWorkspaceLease` (`core/host/volume/workspace_runtime.go`) set `fenced` directly, with no cause, and keep a second latch, `Host.workspaceLeaseFenced`: open. On `main` a guard fence ends the process with status 0: #409 makes it exit 75. | volume host |
+17
View File
@@ -13,6 +13,18 @@ that runs it.
example the SeaweedFS master or filer node), with durable storage. A volume host holds no authority state.
- Why: a forced move after a host loss needs the authority record, the lease horizon and the lost range.
- If those lived on the lost host, the volume could not be moved anywhere.
- **SeaweedFS durability (a premise):** sw-block assumes SeaweedFS acknowledges a write only when it is durable;
configuring SeaweedFS for that is the SeaweedFS deployment's responsibility.
## Clock safety requirement
While volumes are served, blockmaster's host must keep its wall clock **slewed, not stepped**. Configure chrony to
allow `makestep` only at boot (for example, `makestep 1 3` for the initial updates), and do not run `ntpdate` from a
timer. Do not restart an initial-step clock configuration while leases are live. A wall-clock step larger than the
configured clock-skew bound while a lease is live is **outside the v1.0 supported envelope**.
This is a safety premise, not a tested wall-step guarantee. The host's monotonic lease deadline does not remove this
requirement on blockmaster's clock. See Part T `TERM-LEASE-NOW-001` in the [invariant contract](design/invariants.md).
## Install
@@ -54,6 +66,11 @@ one live blockvolume per volume ([one process per volume](releases/one-process-p
- **SeaweedFS space:** every cut and snapshot stores the chunks that changed since the previous one. Space comes
back only by GC and then a SeaweedFS vacuum (below).
Each volume process reports its own heartbeat slot (server, volume and replica).
The master orders each slot against that slot's previous report. In version 1.0,
a backward host-clock step longer than the freshness window (30 seconds by
default) can expire the host's slots; keep host clocks synchronized.
## Recovery point and sync policy
- **A stopped volume** keeps everything it acknowledged, on its host.
+22 -1
View File
@@ -403,6 +403,26 @@ and step 4 is refused with `live authority requires clean revocation ACK`. Nothi
was deleted. Start `blockvolume` again with the same flags and local root, then do
step 2 and continue. This recovery is not run by a test in this release.
## Snapshot names and retries
A snapshot request first takes its name, then publishes the snapshot. Three rules
follow from that order:
- **A name taken by an unfinished request is not listed, but it is held.**
`sw-block ops chunk snapshots` shows only published snapshots. If a snapshot request
was interrupted after it took its name (the process crashed, or the caller gave up),
the name does not appear in the list, yet another request for that name is refused
with `snapshot_exists`, and deleting the volume is refused with `volume v1 has
snapshots (NAME); delete them first`. Free it with
`sw-block ops chunk snapshot-delete --volume v1 --chunk-filer FILER --name NAME`,
or finish it by repeating the request with the same `--request-id`.
- **After `outcome_unknown`, repeat the request with the same `--request-id` within
5 minutes.** Later, the unfinished attempt may have been swept, and the request is
then refused with `this request's attempt was aborted; delete the name to reuse
it`: delete the name and take the snapshot again.
- **A `--request-id` protects against a duplicate only while its snapshot name
exists.** After `snapshot-delete`, repeating the same request takes a new snapshot.
## Symptoms
| You see | It means | Do |
@@ -411,7 +431,8 @@ step 2 and continue. This recovery is not run by a test in this release.
| detach answers `detach_aborted` | Nothing was published; the volume serves here again | Retry step 3 |
| detach answers `outcome_unknown` | The seal may have landed; I/O stays stopped | Retry step 3: it settles the outcome |
| volume-delete: `volume_in_use: ... live authority requires clean revocation ACK` | The volume was sealed (or only stopped) but never revoked and acknowledged; nothing was deleted | "Delete a volume", step 2 |
| volume-delete: `volume v1 has snapshots (s1); delete them first` | Snapshots still exist; nothing was deleted | "Delete a volume", step 3 |
| volume-delete: `volume v1 has snapshots (s1); delete them first` | Snapshots still exist, or a name is held by an unfinished request (such a name is not in the list); nothing was deleted | "Delete a volume", step 3; for a name that is not listed, "Snapshot names and retries" |
| snapshot: `snapshot_exists ... this request's attempt was aborted; delete the name to reuse it` | An earlier attempt of this request did not finish and was swept | `snapshot-delete` the name, then take the snapshot again |
| revoke: `workspace revoke: no matching lease` | `--replica`/`--epoch` are not the current holder | Read them again with `show` |
| move: `workspace clean move needs detached HEAD and matching revocation ACK` | No ACK yet, or its generation differs from HEAD | Wait for the ACK line (step 5); compare `G` with `ops chunk show` |
| move: `move target node "S2" is not registered` | `S2` is not under `nodes` | Add it to the cluster spec, restart blockmaster |