Merge branch 'main' into test/enable-takeover-data-check

This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-22 21:15:10 -08:00
commit deb448d583
14 files changed
+917 -128

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 != "" {
@@ -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,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)
}
})
}
}
@@ -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))
}
})
}
}
@@ -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)
}
}
+2
View File
@@ -13,6 +13,8 @@ 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.
## Install
+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 |