From 73707d9f6137916bfaea24a3c20877c41af43ca0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:04:54 -0800 Subject: [PATCH 01/35] test(storage): require initialized prezero files and crash readback --- seaweed-block/core/storage/data_sync_linux.go | 54 +++++++ .../core/storage/data_sync_linux_test.go | 153 ++++++++++++++++++ 2 files changed, 207 insertions(+) create mode 100644 seaweed-block/core/storage/data_sync_linux.go create mode 100644 seaweed-block/core/storage/data_sync_linux_test.go diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go new file mode 100644 index 0000000000..a572caae2a --- /dev/null +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -0,0 +1,54 @@ +//go:build linux + +package storage + +import ( + "fmt" + "golang.org/x/sys/unix" + "os" + "unsafe" +) + +// FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. +// Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone +// does not satisfy the initialized-file experiment's precondition. +func verifyInitializedFile(f *os.File) error { + info, err := f.Stat() + if err != nil { + return err + } + type extent struct { + Logical, Physical, Length uint64 + Reserved [2]uint64 + Flags uint32 + Reserved2 [3]uint32 + } + type mapping struct { + Start, Length uint64 + Flags, Mapped, Count, Reserved uint32 + Extents [128]extent + } + end := uint64(info.Size()) + var covered uint64 + for covered < end { + m := mapping{Start: covered, Length: end - covered, Flags: 1, Count: 128} + _, _, errno := unix.Syscall(unix.SYS_IOCTL, f.Fd(), 0xc020660b, uintptr(unsafe.Pointer(&m))) + if errno != 0 { + return fmt.Errorf("storage: FIEMAP: %w", errno) + } + if m.Mapped == 0 || m.Mapped > m.Count { + return fmt.Errorf("storage: uninitialized file at %d", covered) + } + for _, e := range m.Extents[:m.Mapped] { + if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4|0x800) != 0 { + return fmt.Errorf("storage: hole or unwritten extent at %d (logical=%d flags=%#x)", covered, e.Logical, e.Flags) + } + next := e.Logical + e.Length + if next <= covered { + return fmt.Errorf("storage: FIEMAP made no progress") + } + covered = next + } + } + return nil +} diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go new file mode 100644 index 0000000000..0e2c28eeed --- /dev/null +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -0,0 +1,153 @@ +//go:build linux + +package storage + +import ( + "bufio" + "bytes" + "context" + "fmt" + "golang.org/x/sys/unix" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" +) + +func TestPrezeroCreatesInitializedVolume(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", "1") + path := filepath.Join(t.TempDir(), "volume") + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = verifyInitializedFile(f); e != nil { + t.Fatalf("prezero must eliminate holes and unwritten extents: %v", e) + } + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(31) + if e != nil || !bytes.Equal(b, make([]byte, 4096)) { + t.Fatalf("new extent bytes: %v", e) + } +} + +func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { + f, e := os.CreateTemp(t.TempDir(), "volume") + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = f.Truncate(1 << 20); e != nil { + t.Fatal(e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("sparse file accepted") + } + if e = unix.Fallocate(int(f.Fd()), 0, 0, 1<<20); e != nil { + t.Fatal(e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("unwritten extents accepted") + } +} + +func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { + if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + panic(e) + } + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + panic(e) + } + for _, lba := range []uint32{0, 13, 31} { + if _, e = s.Write(lba, bytes.Repeat([]byte{byte(lba + 17)}, 4096)); e != nil { + panic(e) + } + } + if n, e := s.Sync(); e != nil || n < 3 { + panic(fmt.Sprintf("Sync=%d %v", n, e)) + } + if os.Getenv("SWBLOCK_TEST_EXTENT") == "1" { + if e = s.flusher.flushOnce(); e != nil { + panic(e) + } + } + fmt.Println("SYNC_ACKNOWLEDGED") + for { + time.Sleep(time.Hour) + } + } + for _, prezero := range []string{"0", "1"} { + for _, extent := range []string{"0", "1"} { + t.Run("prezero"+prezero+"/extent"+extent, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + var stderr bytes.Buffer + cmd.Stderr = &stderr + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + scan := bufio.NewScanner(out) + ready := false + for scan.Scan() { + if scan.Text() == "SYNC_ACKNOWLEDGED" { + ready = true + break + } + } + if !ready { + t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + e = cmd.Wait() + exit, ok := e.(*exec.ExitError) + if !ok { + t.Fatalf("not killed: %v", e) + } + status, ok := exit.Sys().(syscall.WaitStatus) + if !ok || status.Signal() != syscall.SIGKILL { + t.Fatalf("wrong exit: %v", e) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", prezero) + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + for _, lba := range []uint32{0, 13, 31} { + b, e := s.Read(lba) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { + t.Fatalf("acknowledged block%d differs: %v", lba, e) + } + } + }) + } + } +} From 2042e3422bc0fff2855179326556d03acefe3922 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:05:56 -0800 Subject: [PATCH 02/35] feat(storage): add opt-in data sync and initialized file experiments --- seaweed-block/core/storage/data_sync.go | 61 +++++++++++++++++++ seaweed-block/core/storage/data_sync_linux.go | 3 + seaweed-block/core/storage/data_sync_other.go | 14 +++++ seaweed-block/core/storage/wal_writer.go | 8 ++- seaweed-block/core/storage/walstore.go | 8 ++- seaweed-block/core/storage/walstore_v3.go | 3 + 6 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/storage/data_sync.go create mode 100644 seaweed-block/core/storage/data_sync_other.go diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go new file mode 100644 index 0000000000..91190f600d --- /dev/null +++ b/seaweed-block/core/storage/data_sync.go @@ -0,0 +1,61 @@ +package storage + +import ( + "fmt" + "io" + "log" + "os" +) + +// Experimental data-only sync applies to WAL/extent data. Descriptor slots, +// chunk maps, creation and directory operations retain full fsync. +func newDataFileSync(f *os.File) (func() error, error) { + switch mode := os.Getenv("SWBLOCK_SYNC"); mode { + case "", "fsync": + return f.Sync, nil + case "fdatasync": + if err := dataSyncSupported(); err != nil { + return nil, err + } + log.Printf("storage: experimental WAL/extent sync=fdatasync file=%s", f.Name()) + return func() error { return fdatasyncFile(f) }, nil + default: + return nil, fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) + } +} + +// Only newly-created files reach this hook: existing volume bytes are never +// rewritten. Writing zeros (not fallocate) converts unwritten extents too. +func prezeroNewStore(f *os.File, size int64) error { + switch mode := os.Getenv("SWBLOCK_PREZERO"); mode { + case "", "0": + return nil + case "1": + if err := dataSyncSupported(); err != nil { + return err + } + default: + return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", mode) + } + zero := make([]byte, 1<<20) + for off := int64(0); off < size; { + b := zero[:min(int64(len(zero)), size-off)] + n, err := f.WriteAt(b, off) + if err != nil { + return fmt.Errorf("storage: prezero: %w", err) + } + if n != len(b) { + return io.ErrShortWrite + } + off += int64(n) + } + // Allocation/size/extent metadata must be fully durable before the check. + if err := f.Sync(); err != nil { + return err + } + if err := verifyInitializedFile(f); err != nil { + return fmt.Errorf("storage: prezero verification: %w", err) + } + log.Printf("storage: prezero FIEMAP verified initialized file=%s bytes=%d", f.Name(), size) + return nil +} diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go index a572caae2a..6e37a9e181 100644 --- a/seaweed-block/core/storage/data_sync_linux.go +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -52,3 +52,6 @@ func verifyInitializedFile(f *os.File) error { } return nil } + +func dataSyncSupported() error { return nil } +func fdatasyncFile(f *os.File) error { return unix.Fdatasync(int(f.Fd())) } diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go new file mode 100644 index 0000000000..fd456efdff --- /dev/null +++ b/seaweed-block/core/storage/data_sync_other.go @@ -0,0 +1,14 @@ +//go:build !linux + +package storage + +import ( + "errors" + "os" +) + +func dataSyncSupported() error { + return errors.New("storage: fdatasync/prezero experiment requires Linux") +} +func fdatasyncFile(*os.File) error { return dataSyncSupported() } +func verifyInitializedFile(*os.File) error { return dataSyncSupported() } diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index 1b6bf33638..558eb8b064 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -479,7 +479,13 @@ func (w *walWriter) logicalTailValue() uint64 { } // fsync forces buffered data to durable storage. -func (w *walWriter) fsync() error { return w.fd.Sync() } +func (w *walWriter) fsync() error { + sync, err := newDataFileSync(w.fd) + if err != nil { + return err + } + return sync() +} // usedFraction returns the fraction of the WAL region currently in // use, in the range [0, 1]. Used by the admission controller to diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 754caec8d4..bba62eb0a8 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -309,6 +309,10 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada // init hook that runs before the committer and flusher goroutines start // (the v3 store attaches its state there). func openInitializedInternal(path string, f *os.File, sb *superblock, metadata BlockMetadata, init func(*WALStore) error) (*WALStore, error) { + dataSync, err := newDataFileSync(f) + if err != nil { + return nil, err + } dm := newDirtyMap(64) // 64 shards is plenty for Phase 07 demo workloads s := &WALStore{ @@ -333,9 +337,9 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B s.walMutation.Store(1) s.syncWALFile = func() error { s.walSyncCalls.Add(1) - return f.Sync() + return dataSync() } - s.syncExtentFile = f.Sync + s.syncExtentFile = dataSync if init != nil { if err := init(s); err != nil { return nil, err diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 99d911141e..716edeb1e9 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -269,6 +269,9 @@ func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSiz return nil, err } err = fd.Truncate(totalSize) + if err == nil { + err = prezeroNewStore(fd, totalSize) + } if err == nil && chunkBlocks != 0 { var m *chunkLSNMapV3 m, err = createChunkLSNMapV3(path+".chunkmap", d, chunkBlocks) From 781e842ef196af0c3aaf91f4e99a93da7ff35840 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:06:31 -0800 Subject: [PATCH 03/35] test(storage): expose syscall probe and record sync contract --- .../core/storage/data_sync_linux_test.go | 27 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 6 +++++ 2 files changed, 33 insertions(+) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 0e2c28eeed..9643077fe5 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -151,3 +151,30 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { } } } + +// Run under strace with the experiment environment unset/set to verify the +// syscall boundary independently of the selected function's Go identity. +func TestDataSyncSyscallProbe(t *testing.T) { + s, e := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + if _, e = s.Write(7, bytes.Repeat([]byte{0x6d}, 4096)); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if e = s.flusher.flushOnce(); e != nil { + t.Fatal(e) + } + b, e := s.Read(7) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{0x6d}, 4096)) { + t.Fatalf("readback: %v", e) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9068b36a7b..7c12d9c6bd 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -527,6 +527,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### Experimental data-file synchronization + +| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | +|---|---|---|---|---|---|---| +| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_PREZERO=1` writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | + ## Part C. Change rules How a fix or a feature is calibrated against this model: From 94a9aac74f5249a3181c1ce917a0bb5e022a9fb2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:08:56 -0800 Subject: [PATCH 04/35] test(storage): cover strict and lagged sync crash paths --- .../core/storage/data_sync_linux_test.go | 127 ++++++++++-------- 1 file changed, 69 insertions(+), 58 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 9643077fe5..520495e46d 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -64,7 +64,11 @@ func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { - s, e := CreateWALStore(path, 32, 4096) + opts := WALStoreOptions{} + if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { + opts.WMode = WModeStrict + } + s, e := CreateWALStoreWithOptions(path, 32, 4096, opts) if e != nil { panic(e) } @@ -90,72 +94,79 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { time.Sleep(time.Hour) } } - for _, prezero := range []string{"0", "1"} { - for _, extent := range []string{"0", "1"} { - t.Run("prezero"+prezero+"/extent"+extent, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "volume") - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") - cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent) - out, e := cmd.StdoutPipe() - if e != nil { - t.Fatal(e) - } - var stderr bytes.Buffer - cmd.Stderr = &stderr - if e = cmd.Start(); e != nil { - t.Fatal(e) - } - defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() - scan := bufio.NewScanner(out) - ready := false - for scan.Scan() { - if scan.Text() == "SYNC_ACKNOWLEDGED" { - ready = true - break + for _, strict := range []string{"0", "1"} { + for _, prezero := range []string{"0", "1"} { + for _, extent := range []string{"0", "1"} { + t.Run("strict"+strict+"/prezero"+prezero+"/extent"+extent, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) } - } - if !ready { - t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) - } - if e = cmd.Process.Kill(); e != nil { - t.Fatal(e) - } - e = cmd.Wait() - exit, ok := e.(*exec.ExitError) - if !ok { - t.Fatalf("not killed: %v", e) - } - status, ok := exit.Sys().(syscall.WaitStatus) - if !ok || status.Signal() != syscall.SIGKILL { - t.Fatalf("wrong exit: %v", e) - } - t.Setenv("SWBLOCK_SYNC", "fdatasync") - t.Setenv("SWBLOCK_PREZERO", prezero) - s, e := OpenWALStore(path) - if e != nil { - t.Fatal(e) - } - defer s.Close() - if _, e = s.Recover(); e != nil { - t.Fatal(e) - } - for _, lba := range []uint32{0, 13, 31} { - b, e := s.Read(lba) - if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { - t.Fatalf("acknowledged block%d differs: %v", lba, e) + var stderr bytes.Buffer + cmd.Stderr = &stderr + if e = cmd.Start(); e != nil { + t.Fatal(e) } - } - }) + defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + scan := bufio.NewScanner(out) + ready := false + for scan.Scan() { + if scan.Text() == "SYNC_ACKNOWLEDGED" { + ready = true + break + } + } + if !ready { + t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + e = cmd.Wait() + exit, ok := e.(*exec.ExitError) + if !ok { + t.Fatalf("not killed: %v", e) + } + status, ok := exit.Sys().(syscall.WaitStatus) + if !ok || status.Signal() != syscall.SIGKILL { + t.Fatalf("wrong exit: %v", e) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", prezero) + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + for _, lba := range []uint32{0, 13, 31} { + b, e := s.Read(lba) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { + t.Fatalf("acknowledged block%d differs: %v", lba, e) + } + } + }) + } } + } } // Run under strace with the experiment environment unset/set to verify the // syscall boundary independently of the selected function's Go identity. func TestDataSyncSyscallProbe(t *testing.T) { - s, e := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + opts := WALStoreOptions{} + if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { + opts.WMode = WModeStrict + } + s, e := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 32, 4096, opts) if e != nil { t.Fatal(e) } From 6121830f795128a61f43ffc0d52594bfe1f15e59 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:14:33 -0800 Subject: [PATCH 05/35] feat(storage): expose sparse fallocate and prezero allocation arms --- seaweed-block/core/storage/data_sync.go | 31 ++++++++++++++++--- seaweed-block/core/storage/data_sync_linux.go | 8 +++-- .../core/storage/data_sync_linux_test.go | 30 ++++++++++++++++++ seaweed-block/core/storage/data_sync_other.go | 3 ++ 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 91190f600d..89105d9272 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -27,15 +27,38 @@ func newDataFileSync(f *os.File) (func() error, error) { // Only newly-created files reach this hook: existing volume bytes are never // rewritten. Writing zeros (not fallocate) converts unwritten extents too. func prezeroNewStore(f *os.File, size int64) error { - switch mode := os.Getenv("SWBLOCK_PREZERO"); mode { - case "", "0": + mode := os.Getenv("SWBLOCK_ALLOCATION") + prezero := os.Getenv("SWBLOCK_PREZERO") + if prezero != "" && prezero != "0" && prezero != "1" { + return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) + } + if prezero == "1" { + if mode != "" && mode != "prezero" { + return fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) + } + mode = "prezero" + } + switch mode { + case "", "sparse": return nil - case "1": + case "fallocate": + if err := fallocateFile(f, size); err != nil { + return err + } + if err := f.Sync(); err != nil { + return err + } + if err := verifyAllocatedFile(f, false); err != nil { + return err + } + log.Printf("storage: FIEMAP verified allocated file=%s bytes=%d (unwritten extents allowed)", f.Name(), size) + return nil + case "prezero": if err := dataSyncSupported(); err != nil { return err } default: - return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", mode) + return fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) } zero := make([]byte, 1<<20) for off := int64(0); off < size; { diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go index 6e37a9e181..cbc07c8832 100644 --- a/seaweed-block/core/storage/data_sync_linux.go +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -12,7 +12,9 @@ import ( // FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. // Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone // does not satisfy the initialized-file experiment's precondition. -func verifyInitializedFile(f *os.File) error { +func verifyInitializedFile(f *os.File) error { return verifyAllocatedFile(f, true) } + +func verifyAllocatedFile(f *os.File, written bool) error { info, err := f.Stat() if err != nil { return err @@ -40,7 +42,7 @@ func verifyInitializedFile(f *os.File) error { return fmt.Errorf("storage: uninitialized file at %d", covered) } for _, e := range m.Extents[:m.Mapped] { - if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4|0x800) != 0 { + if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4) != 0 || (written && e.Flags&0x800 != 0) { return fmt.Errorf("storage: hole or unwritten extent at %d (logical=%d flags=%#x)", covered, e.Logical, e.Flags) } next := e.Logical + e.Length @@ -55,3 +57,5 @@ func verifyInitializedFile(f *os.File) error { func dataSyncSupported() error { return nil } func fdatasyncFile(f *os.File) error { return unix.Fdatasync(int(f.Fd())) } + +func fallocateFile(f *os.File, size int64) error { return unix.Fallocate(int(f.Fd()), 0, 0, size) } diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 520495e46d..0c76a670a2 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -189,3 +189,33 @@ func TestDataSyncSyscallProbe(t *testing.T) { t.Fatalf("readback: %v", e) } } + +func TestFallocateCreatesAllocatedUnwrittenVolume(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", "0") + t.Setenv("SWBLOCK_ALLOCATION", "fallocate") + path := filepath.Join(t.TempDir(), "volume") + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = verifyAllocatedFile(f, false); e != nil { + t.Fatalf("fallocate left holes: %v", e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("fallocate unexpectedly reports every extent written") + } + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(31) + if e != nil || !bytes.Equal(b, make([]byte, 4096)) { + t.Fatalf("unwritten extent bytes: %v", e) + } +} diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go index fd456efdff..8469247cfe 100644 --- a/seaweed-block/core/storage/data_sync_other.go +++ b/seaweed-block/core/storage/data_sync_other.go @@ -12,3 +12,6 @@ func dataSyncSupported() error { } func fdatasyncFile(*os.File) error { return dataSyncSupported() } func verifyInitializedFile(*os.File) error { return dataSyncSupported() } + +func fallocateFile(*os.File, int64) error { return dataSyncSupported() } +func verifyAllocatedFile(*os.File, bool) error { return dataSyncSupported() } From 9fc77218b2c9677c7923b9d38350f75be58a7e0e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 01:15:39 -0800 Subject: [PATCH 06/35] test(storage): add isolated block replay helper for sync controls --- .../storage/data_sync_replay_linux_test.go | 148 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/storage/data_sync_replay_linux_test.go diff --git a/seaweed-block/core/storage/data_sync_replay_linux_test.go b/seaweed-block/core/storage/data_sync_replay_linux_test.go new file mode 100644 index 0000000000..758c95ffe8 --- /dev/null +++ b/seaweed-block/core/storage/data_sync_replay_linux_test.go @@ -0,0 +1,148 @@ +//go:build linux + +package storage + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "testing" +) + +// External dm-log-writes harness calls prepare/write, replays only through +// the post-sync ACK mark onto a fresh device, then calls verify. Without that +// block-layer harness this helper is not a power-loss test. +func TestDataSyncPowerLossReplayHelper(t *testing.T) { + root := os.Getenv("SWBLOCK_REPLAY_ROOT") + if root == "" { + t.Skip("requires isolated dm-log-writes replay harness") + } + phase, kind := os.Getenv("SWBLOCK_REPLAY_PHASE"), os.Getenv("SWBLOCK_REPLAY_CASE") + path := filepath.Join(root, "probe") + payload := bytes.Repeat([]byte{0x7d}, 4096) + if kind == "wal" { + switch phase { + case "prepare": + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + if e = s.Close(); e != nil { + t.Fatal(e) + } + case "write": + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + if _, e = s.Write(13, payload); e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") != "1" { + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + } + // Deliberately no Close: only the explicit Sync precedes the ACK mark. + case "verify": + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(13) + if e != nil || !bytes.Equal(b, payload) { + t.Fatalf("REPLAY_BYTES_MISMATCH WAL: %v", e) + } + default: + t.Fatalf("unknown replay phase %q", phase) + } + } else { + switch phase { + case "prepare": + f, e := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) + if e != nil { + t.Fatal(e) + } + defer f.Close() + switch kind { + case "written": + if _, e = f.WriteAt(make([]byte, 1<<20), 0); e != nil { + t.Fatal(e) + } + case "unwritten": + if e = fallocateFile(f, 1<<20); e != nil { + t.Fatal(e) + } + case "hole": + if e = f.Truncate(1 << 20); e != nil { + t.Fatal(e) + } + case "growth": + if _, e = f.WriteAt(make([]byte, 4096), 0); e != nil { + t.Fatal(e) + } + default: + t.Fatalf("unknown replay case %q", kind) + } + if e = f.Sync(); e != nil { + t.Fatal(e) + } + case "write": + f, e := os.OpenFile(path, os.O_RDWR, 0) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if _, e = f.WriteAt(payload, 128<<10); e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") != "1" { + if kind == "growth" { + e = f.Sync() + } else { + var sync func() error + sync, e = newDataFileSync(f) + if e == nil { + e = sync() + } + } + if e != nil { + t.Fatal(e) + } + } + case "verify": + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + b := make([]byte, 4096) + n, e := f.ReadAt(b, 128<<10) + if e != nil || n != len(b) || !bytes.Equal(b, payload) { + t.Fatalf("REPLAY_BYTES_MISMATCH %s: n=%d err=%v", kind, n, e) + } + default: + t.Fatalf("unknown replay phase %q", phase) + } + } + if phase == "prepare" { + d, e := os.Open(root) + if e != nil { + t.Fatal(e) + } + defer d.Close() + if e = d.Sync(); e != nil { + t.Fatal(e) + } + } + fmt.Printf("REPLAY_%s_OK %s\n", phase, kind) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7c12d9c6bd..3801ba765a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_PREZERO=1` writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|fallocate|prezero` selects allocation at create; fallocate retains unwritten extents. `SWBLOCK_PREZERO=1` aliases prezero, which writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | ## Part C. Change rules From fe0cd8448ccc3b81a0b503355b381bdc7f451fb8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:02:20 -0800 Subject: [PATCH 07/35] Start the new holder's lease when a workspace move is issued A move issue cleared the lease and the new holder's lease was created only by its first renewal. A holder that died between its grant and its first renewal left the volume with no lease, so no move was ever admitted again, not even a forced one. A holder that died after renewing but before claiming HEAD was stuck too: HEAD still named its predecessor and the forced move refused it. The issue write now starts the new holder's lease (horizon issue + 1.5*TTL, granted deadline issue + TTL, the same values a first grant uses), so an unclaimed grant expires like any other lease and a forced move is admitted after that lease's expiry plus the skew bound, never on a predecessor's lease. The holder's first renewal is an ordinary renewal of that lease, with no extra write. A forced move also accepts a HEAD that still names the predecessor when it is unchanged since the move to the expected holder was issued (same generation and remote LSN, older epoch). Clean moves are unchanged. Blockmaster reads HEAD for a forced move only after its lease admission holds, so the HEAD the move and its lost range rest on can no longer be changed by the expired holder. A holder resuming after the forced move is refused at attach by its lease-gated projection. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 6 +- seaweed-block/core/authority/workspace.go | 128 +++++++-- .../workspace_forced_admission_test.go | 36 +++ .../authority/workspace_lease_horizon_test.go | 17 +- .../core/authority/workspace_lease_view.go | 21 +- .../workspace_unclaimed_grant_test.go | 271 ++++++++++++++++++ .../master/workspace_paused_grantee_test.go | 184 ++++++++++++ .../core/host/master/workspace_service.go | 9 + .../master/workspace_unclaimed_grant_test.go | 190 ++++++++++++ seaweed-block/docs/design/invariants.md | 10 +- 10 files changed, 823 insertions(+), 49 deletions(-) create mode 100644 seaweed-block/core/authority/workspace_forced_admission_test.go create mode 100644 seaweed-block/core/authority/workspace_unclaimed_grant_test.go create mode 100644 seaweed-block/core/host/master/workspace_paused_grantee_test.go create mode 100644 seaweed-block/core/host/master/workspace_unclaimed_grant_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 52f8d7fe1f..fcac948db0 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -478,9 +478,10 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } var issuedWorkspace *WorkspaceState var reservedEpoch uint64 + var issuedAt time.Time if grant != nil { var err error - issuedWorkspace, reservedEpoch, err = p.prepareWorkspaceMoveLocked(ask, *grant) + issuedWorkspace, reservedEpoch, issuedAt, err = p.prepareWorkspaceMoveLocked(ask, *grant) if err != nil { p.mu.Unlock() return err @@ -611,7 +612,8 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.state[k] = assignmentState{info: next, present: true} p.refreshLeaseViewLocked(ask.VolumeID) if issuedWorkspace != nil { - p.setLeaseDeadlineLocked(ask.VolumeID, time.Time{}, false) // the issued move clears the lease + // The issued move starts the new holder's lease (issuedAt+TTL grant). + p.setLeaseDeadlineLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL), false) } // Snapshot subscribers under lock, release the lock BEFORE diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 6d6301e1b3..a1f4c1877d 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -270,29 +270,95 @@ func sameWorkspaceRequest(r WorkspaceMoveRecord, q WorkspaceMoveRequest) bool { r.TargetDataAddr == q.TargetDataAddr && r.TargetCtrlAddr == q.TargetCtrlAddr } +// WorkspaceForcedMoveAdmitted reports whether a forced move of volume away +// from holder at epoch is admitted now: the lease expiry and the granted or +// restart deadline, each plus the clock-skew margin, have passed. A caller +// reads HEAD only after this returns nil, so the HEAD a forced move checks +// can no longer be changed by a holder of that epoch's grants. The move +// itself checks admission again. A request id the journal already holds is +// left to MoveWorkspace: its replay never uses a new HEAD. +func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, requestID, holder string, epoch uint64) error { + if err := ctx.Err(); err != nil { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + _, line, ok := p.workspaceLineLocked(volume) + s := p.workspace[volume] + if s != nil { + for _, r := range s.Moves { + if r.RequestID == requestID { + return nil + } + } + } + if !ok || line.info.Epoch != epoch || line.info.ReplicaID != holder || s == nil || s.Lease == nil { + return fmt.Errorf("workspace move: missing or changed authority/lease") + } + _, err := p.forcedMoveAdmissionLocked(volume, s.Lease) + return err +} + +// forcedMoveAdmissionLocked returns the audit bound of the lost range when a +// forced move is admitted. Caller holds p.mu. +func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLease) (int64, error) { + now := p.workspaceNow() + skew := p.workspaceSkew(lease) + deadline := p.leaseDeadlineLocked(volume) + if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { + return 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + // The audit bound only, in wall time: the admission above keeps both + // predicates (the deadline's monotonic reading included). + lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() + if d := deadline.Add(skew).UnixNano(); d > lostUntil { + lostUntil = d + } + return lostUntil, nil +} + +// headUnclaimedSinceIssue reports whether h is still the HEAD the move to the +// expected holder was issued against, so that holder never claimed it (every +// HEAD write advances Gen). Only a forced move may use it: the expected +// holder's grant has expired, so it can no longer claim. +func headUnclaimedSinceIssue(s *WorkspaceState, q WorkspaceMoveRequest, h WorkspaceHead) bool { + for i := len(s.Moves) - 1; i >= 0; i-- { + r := s.Moves[i] + if !r.Issued { + continue + } + return r.NewEpoch == q.ExpectedEpoch && r.NewHost == q.ExpectedHost && r.NewReplicaID == q.ExpectedReplicaID && + h.Gen != 0 && h.Gen == r.HeadGen && h.RemoteLSN == r.RemoteLSN && h.Epoch < q.ExpectedEpoch + } + return false +} + +// issueWorkspaceMove marks the move issued and starts the new holder's lease +// in the same write as the new epoch, so a holder that dies before its first +// renewal still leaves a lease that expires and admits a forced move. +func (p *Publisher) issueWorkspaceMove(s *WorkspaceState, idx int, now time.Time) { + r := &s.Moves[idx] + r.Issued = true + s.Lease, _ = p.newWorkspaceLease(r.NewReplicaID, r.NewEpoch, now) + s.Ack = nil +} + // Called only under Publisher.mu. First persist a reservation with the OLD // assignment. The subsequent authority write includes that same journal record. // A crash at either boundary cannot expose an epoch without its grant record. -func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGrant) (*WorkspaceState, uint64, error) { +// The returned time is the issue time the new holder's lease starts from. +func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGrant) (*WorkspaceState, uint64, time.Time, error) { q, h := g.request, g.head _, line, ok := p.workspaceLineLocked(q.VolumeID) s := cloneWorkspace(p.workspace[q.VolumeID]) if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil { - return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease") + return nil, 0, time.Time{}, fmt.Errorf("workspace move: missing or changed authority/lease") } var lostUntil int64 if q.Kind == "forced" { - now := p.workspaceNow() - skew := p.workspaceSkew(s.Lease) - deadline := p.leaseDeadlineLocked(q.VolumeID) - if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { - return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") - } - // The audit bound only, in wall time: the admission above keeps both - // predicates (the deadline's monotonic reading included). - lostUntil = time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).UnixNano() - if d := deadline.Add(skew).UnixNano(); d > lostUntil { - lostUntil = d + var err error + if lostUntil, err = p.forcedMoveAdmissionLocked(q.VolumeID, s.Lease); err != nil { + return nil, 0, time.Time{}, err } } // A restart may resume the identical durable reservation; it never grants @@ -300,7 +366,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra for idx, r := range s.Moves { if r.RequestID == q.RequestID { if r.Issued || !sameWorkspaceRequest(r, q) { - return nil, 0, fmt.Errorf("workspace move reservation differs") + return nil, 0, time.Time{}, fmt.Errorf("workspace move reservation differs") } // A forced reservation issues only with the exact range recorded // before it; a missing one (a reservation older than lost ranges, @@ -308,21 +374,26 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra // request records a fresh range. if r.Kind == "forced" { if _, ok := p.lostRangeLocked(q.VolumeID, r.RequestID, r.NewEpoch); !ok { - return nil, 0, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) + return nil, 0, time.Time{}, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) } } - s.Moves[idx].Issued = true - s.Lease = nil - s.Ack = nil - return s, r.NewEpoch, nil + now := p.workspaceNow() + p.issueWorkspaceMove(s, idx, now) + return s, r.NewEpoch, now, nil } } - if h.Gen == 0 || h.Epoch != q.ExpectedEpoch || h.Holder != q.ExpectedHost+"/"+q.ExpectedReplicaID { - return nil, 0, fmt.Errorf("workspace move: HEAD not owned by expected holder") + owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID + if !owned && q.Kind == "forced" { + // A holder that died between its grant and its claim left HEAD + // naming its predecessor. + owned = headUnclaimedSinceIssue(s, q, h) + } + if !owned { + return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") } if q.Kind == "clean" { if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen { - return nil, 0, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") + return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } } max := maxPublishedEpochForVolume(p.state, q.VolumeID) @@ -332,22 +403,21 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra } } if max == ^uint64(0) { - return nil, 0, fmt.Errorf("workspace epoch exhausted") + return nil, 0, time.Time{}, fmt.Errorf("workspace epoch exhausted") } r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} if q.Kind == "forced" { lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { - return nil, 0, err + return nil, 0, time.Time{}, err } } s.Moves = append(s.Moves, r) if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil { - return nil, 0, err + return nil, 0, time.Time{}, err } - s.Moves[len(s.Moves)-1].Issued = true - s.Lease = nil - s.Ack = nil - return s, r.NewEpoch, nil + now := p.workspaceNow() + p.issueWorkspaceMove(s, len(s.Moves)-1, now) + return s, r.NewEpoch, now, nil } diff --git a/seaweed-block/core/authority/workspace_forced_admission_test.go b/seaweed-block/core/authority/workspace_forced_admission_test.go new file mode 100644 index 0000000000..39329f88fc --- /dev/null +++ b/seaweed-block/core/authority/workspace_forced_admission_test.go @@ -0,0 +1,36 @@ +package authority + +import ( + "context" + "strings" + "testing" + "time" +) + +// WorkspaceForcedMoveAdmitted gives the move's own answer: refused before +// the lease expiry plus skew, admitted at it; a journaled request id is left +// to MoveWorkspace (its replay uses no new HEAD). +func TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + barrier := issued.Add(grantTTL + grantTTL/2 + p.workspaceSkew(p.WorkspaceState("v").Lease)) + now = barrier.Add(-time.Nanosecond) + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("admitted before expiry+skew: %v", err) + } + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 1); err == nil || !strings.Contains(err.Error(), "missing or changed authority/lease") { + t.Fatalf("admitted a stale epoch: %v", err) + } + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "clean", "r", 1); err != nil { + t.Fatalf("a journaled request id must be left to MoveWorkspace: %v", err) + } + now = barrier + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err != nil { + t.Fatal("refused after expiry+skew:", err) + } + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 2a43a9c5b9..7d35415762 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -186,8 +186,10 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { t.Fatal(err) } check("clean move issued") - if p.leaseDeadlineLockedForTest("v") != (time.Time{}) { - t.Fatal("move issue kept the old deadline") + // The issue replaces the old holder's deadline with the new holder's + // first grant: issue time (10 s) + TTL. + if got := p.leaseDeadlineLockedForTest("v"); !got.Equal(c.sec(40)) { + t.Fatalf("move issue deadline %s; want the new holder's issue+TTL %s", got, c.sec(40)) } // w: forced move whose issue write fails after the reservation persisted. c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20) @@ -940,10 +942,13 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if extensions.Load() == 0 { t.Fatal("no horizon-extension write was observed") } - if st := p.WorkspaceState(vol(forcedVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" { + // An issued move starts the new holder's lease at the new epoch. + if st := p.WorkspaceState(vol(forcedVol)); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" || + st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { t.Fatalf("forced move not issued: %+v", st) } - if st := p.WorkspaceState(vol(cleanVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" { + if st := p.WorkspaceState(vol(cleanVol)); st == nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" || + st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { t.Fatalf("clean move not issued: %+v", st) } assertLeaseViewMatches(t, p, "after concurrency") @@ -959,8 +964,8 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } for i := 0; i < n; i++ { st := p.WorkspaceState(vol(i)) - if st == nil || st.Lease == nil { - continue // a completed move cleared the lease (out of S1's scope) + if st == nil || st.Lease == nil || st.Lease.Epoch != 1 { + continue // a completed move started the next epoch's lease (out of S1's scope) } if onDisk[vol(i)] < st.Lease.ExpiresAtNS || st.Lease.ExpiresAtNS < maxGrant[i].Load() { t.Fatalf("%s: S1 broken: disk %d, published horizon %d, max grant %d", vol(i), onDisk[vol(i)], st.Lease.ExpiresAtNS, maxGrant[i].Load()) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 6cfc82d8a5..d6b57dcab9 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -78,7 +78,8 @@ func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { return time.Time{} } -// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue) or, +// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue: the +// new holder's lease starts with the grant issue+TTL) or, // with raise, raises it to at least t (a grant). Caller holds p.mu. func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise bool) { d := p.deriveLeaseLocked(volume) @@ -201,7 +202,8 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri } // firstWorkspaceGrant creates a lease synchronously under p.mu (one write per -// assignment epoch). A host whose first renewal fails does not fence: it has +// assignment epoch) for an epoch that has none: a move issue already started +// its holder's lease. A host whose first renewal fails does not fence: it has // no deadline yet and retries. The durable horizon starts at now+1.5*TTL. func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { p.mu.Lock() @@ -226,17 +228,22 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri p.mu.Unlock() return WorkspaceLease{}, fmt.Errorf("workspace lease: created concurrently; retry") } - now := p.workspaceNow() - skew := int64(p.workspaceSkew(nil)) - grant := now.Add(p.workspaceTTL) - s.Lease = &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: skew} + lease, grant := p.newWorkspaceLease(holder, epoch, p.workspaceNow()) + s.Lease = lease if err := p.persistWorkspaceLocked(volume, s); err != nil { p.mu.Unlock() return WorkspaceLease{}, err } p.setLeaseDeadlineLocked(volume, grant, true) p.mu.Unlock() - return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: skew}, nil + return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil +} + +// newWorkspaceLease starts a lease at now: the durable horizon is +// now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a +// move issue start a lease this way. +func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) { + return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } // extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go new file mode 100644 index 0000000000..e2b88b87f7 --- /dev/null +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -0,0 +1,271 @@ +package authority + +import ( + "context" + "strings" + "sync/atomic" + "testing" + "time" +) + +// countPutStore counts authority writes. +type countPutStore struct { + AuthorityStore + puts atomic.Int64 +} + +func (s *countPutStore) Put(r DurableRecord) error { + s.puts.Add(1) + return s.AuthorityStore.Put(r) +} + +const grantTTL = time.Second + +// The predecessor's detached HEAD: the grantee of the clean move below never +// claims it, so HEAD keeps naming the predecessor. +var predecessorHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/r", RemoteLSN: 42, Detached: true} + +// cleanMoveToGrantee binds v to r at epoch 1, then moves it cleanly from +// old-node to new-node (epoch 2) at the returned issue time. +func cleanMoveToGrantee(t *testing.T, store AuthorityStore, now *time.Time) (*Publisher, time.Time) { + t.Helper() + ctx := context.Background() + p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return *now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + *now = now.Add(100 * time.Millisecond) + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + r, err := p.MoveWorkspace(ctx, req, predecessorHead) + if err != nil || !r.Issued || r.NewEpoch != 2 { + t.Fatal("clean move to the grantee:", r, err) + } + return p, *now +} + +// assertGranteeLease checks the lease the move issue started: the grantee's +// identity at the new epoch, horizon issue+1.5*TTL, not revoking, no ACK. +func assertGranteeLease(t *testing.T, p *Publisher, issued time.Time) { + t.Helper() + st := p.WorkspaceState("v") + want := WorkspaceLease{ReplicaID: "r", Epoch: 2, ExpiresAtNS: issued.Add(grantTTL + grantTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))} + if st == nil || st.Lease == nil || *st.Lease != want || st.Ack != nil { + t.Fatalf("move issue must start the grantee's lease %+v; state %+v", want, st) + } +} + +func forcedFromGrantee(id string) WorkspaceMoveRequest { + return WorkspaceMoveRequest{RequestID: id, VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} +} + +// A grantee that dies between its grant and its HEAD claim never renews: +// the lease the move issue started expires, and a forced move to a third +// host is admitted after its expiry plus the skew margin, never before. The +// same holds when blockmaster restarts between the issue and the forced move. +func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) { + for _, restart := range []bool{false, true} { + name := "same-master" + if restart { + name = "restart" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + assertGranteeLease(t, p, issued) + assertLeaseViewMatches(t, p, "after issue") + if lease, ok := p.WorkspaceLeaseReply("v"); !ok || lease.Epoch != 2 || lease.ExpiresAtNS != issued.Add(grantTTL).UnixNano() { + t.Fatalf("reported lease after issue: %+v %v; want the issue+TTL grant", lease, ok) + } + if restart { + now = now.Add(200 * time.Millisecond) + p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + assertGranteeLease(t, p, issued) + assertLeaseViewMatches(t, p, "after restart") + } + skew := p.workspaceSkew(p.WorkspaceState("v").Lease) + // The horizon (issue+1.5*TTL) is the later bound: the deadline is + // issue+TTL, or restart+TTL after a restart 0.2*TTL later. + barrier := issued.Add(grantTTL + grantTTL/2 + skew) + // The predecessor's lease (renewed 0.1 s before the issue) has + // expired plus skew by then: only the grant's lease may admit. + if old := issued.Add(-100*time.Millisecond + grantTTL + grantTTL/2 + skew); !barrier.Add(-time.Nanosecond).After(old) { + t.Fatal("test clock does not separate the predecessor's barrier from the grant's") + } + now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("forced move before expiry+skew: %v", err) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { + t.Fatal("early refusal changed authority or journal", line) + } + now = barrier + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead) + if err != nil { + t.Fatal("forced move after expiry+skew:", err) + } + if !r.Issued || r.NewEpoch != 3 || r.NewHost != "third-node" || r.HeadGen != predecessorHead.Gen || r.RemoteLSN != predecessorHead.RemoteLSN { + t.Fatalf("forced grant %+v", r) + } + lost := p.WorkspaceLostRanges("v") + if len(lost) != 1 || lost[0].NewEpoch != 3 || lost[0].OldEpoch != 2 || lost[0].LostAfterLSN != predecessorHead.RemoteLSN { + t.Fatalf("lost range %+v", lost) + } + if st := p.WorkspaceState("v"); st.Lease == nil || st.Lease.Epoch != 3 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("forced issue must start the next holder's lease: %+v", st.Lease) + } + assertLeaseViewMatches(t, p, "after forced move") + }) + } +} + +// The HEAD rule: a forced move from a grantee that never claimed HEAD accepts +// the predecessor's HEAD only when it is unchanged since the issue (same Gen +// and RemoteLSN, an older epoch). Clean moves never accept it. +func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + + // Clean: even with the grantee's revocation ACK naming that HEAD + // generation, the predecessor's HEAD is not the grantee's. + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 2); err != nil { + t.Fatal("revoke the grantee's issued lease:", err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + clean := forcedFromGrantee("clean-2") + clean.Kind, clean.Force = "clean", false + if _, err := p.MoveWorkspace(ctx, clean, predecessorHead); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { + t.Fatalf("clean move accepted the predecessor's HEAD: %v", err) + } + + now = issued.Add(10 * grantTTL) + changed := map[string]WorkspaceHead{} + h := predecessorHead + h.Gen++ + changed["gen advanced"] = h + h = predecessorHead + h.RemoteLSN++ + changed["remote LSN differs"] = h + h = predecessorHead + h.Epoch = 2 + changed["epoch not older"] = h + h = predecessorHead + h.Gen = 0 + changed["no HEAD"] = h + for what, h := range changed { + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-"+what), h); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { + t.Fatalf("%s: forced move accepted %+v: %v", what, h, err) + } + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { + t.Fatal("a refused HEAD changed authority or journal", line) + } + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead) + if err != nil || r.NewEpoch != 3 { + t.Fatal("forced move with the unchanged predecessor HEAD:", r, err) + } + // A chain: the epoch-3 grantee dies unclaimed too; HEAD is still the + // same predecessor HEAD, recorded by both moves. + now = now.Add(10 * grantTTL) + next := forcedFromGrantee("forced-again") + next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 + if r, err := p.MoveWorkspace(ctx, next, predecessorHead); err != nil || r.NewEpoch != 4 { + t.Fatal("second unclaimed grant:", r, err) + } +} + +// The grantee's first renewal is an ordinary renewal of the lease the issue +// started: no authority write, no new epoch; the old epoch stays refused. +func TestWorkspaceUnclaimedGrantGranteeRenewsNormally(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + store := &countPutStore{AuthorityStore: disk} + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, store, &now) + writes := store.puts.Load() + now = issued.Add(100 * time.Millisecond) + l, err := p.RenewWorkspaceLease(ctx, "v", "r", 2) + if err != nil { + t.Fatal("grantee's first renewal:", err) + } + if l.Epoch != 2 || l.ReplicaID != "r" || l.ExpiresAtNS != now.Add(grantTTL).UnixNano() { + t.Fatalf("first renewal %+v", l) + } + if store.puts.Load() != writes { + t.Fatalf("first renewal wrote %d authority records; the issue already persisted the lease", store.puts.Load()-writes) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("old epoch renewed after the move") + } + // Past 0.25*TTL the renewal starts an extension of the issued lease. + now = issued.Add(grantTTL / 2) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal(err) + } + st := p.WorkspaceState("v") + for wait := time.Now().Add(5 * time.Second); time.Now().Before(wait) && (st.Lease == nil || st.Lease.ExpiresAtNS == issued.Add(grantTTL+grantTTL/2).UnixNano()); st = p.WorkspaceState("v") { + time.Sleep(5 * time.Millisecond) + } + p.CloseWorkspaceExtenders() + if st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("issued lease not extended: %+v", st.Lease) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(st.Moves) != 1 { + t.Fatal("renewals changed authority", line) + } + assertLeaseViewMatches(t, p, "after renewals") +} + +// A forced reservation resumed after a crash issues through the replay path, +// which starts the new holder's lease the same way. +func TestWorkspaceReplayedIssueStartsGranteeLease(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + fault := &workspaceFailStore{AuthorityStore: disk} + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(fault), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + now = now.Add(3 * grantTTL) + req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/r", RemoteLSN: 42} + fault.failIssue = true + if _, err := p.MoveWorkspace(ctx, req, head); err == nil { + t.Fatal("injected crash ignored") + } + loaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + now = now.Add(2 * grantTTL) // past the restart deadline plus skew + r, err := loaded.MoveWorkspace(ctx, req, WorkspaceHead{}) + if err != nil || !r.Issued || r.NewEpoch != 2 { + t.Fatal("replayed issue:", r, err) + } + assertGranteeLease(t, loaded, now) + assertLeaseViewMatches(t, loaded, "after replayed issue") + if _, err := loaded.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("grantee renewal after the replayed issue:", err) + } + // Unrenewed after this, the replayed grant expires like any other. + now = now.Add(grantTTL + grantTTL/2 + loaded.workspaceSkew(nil)) + next := WorkspaceMoveRequest{RequestID: "m2", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + if r, err := loaded.MoveWorkspace(ctx, next, head); err != nil || r.NewEpoch != 3 { + t.Fatal("forced move after the replayed grant expired:", r, err) + } +} diff --git a/seaweed-block/core/host/master/workspace_paused_grantee_test.go b/seaweed-block/core/host/master/workspace_paused_grantee_test.go new file mode 100644 index 0000000000..30d4749b97 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -0,0 +1,184 @@ +package master + +import ( + "bytes" + "context" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A grantee renews its issued lease, then pauses before claiming HEAD. The +// forced move away from it is admitted only after the GRANT's lease expiry +// plus skew (the predecessor's older lease never satisfies it), and is +// granted on the predecessor's unchanged HEAD. The grantee resumes before +// the new owner claims: HEAD's epoch has not moved yet, so the epoch alone +// would let it claim; the authority check at attach (its lease-gated +// projection) refuses it. The new owner then claims at the higher epoch. +func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Error(err) + } + }) + const ttl = 3 * time.Second + start := time.Now() + masterNow, hostNow := start, start + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(ttl, func() time.Time { return masterNow })) + seedSkewPublisher(t, p, dir) // v bound to r at epoch 1 + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + oldBarrier := time.Unix(0, p.WorkspaceState("v").Lease.ExpiresAtNS) + + remote := storage.NewMemChunkRemote() + readHead := func() authority.WorkspaceHead { + t.Helper() + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + } + open := func(holder string, view frontend.ProjectionView) *durable.DurableProvider { + t.Helper() + prov, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkHolder: holder, ChunkAssignmentTimeout: 2 * time.Second, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = prov.Close() }) + if _, err := prov.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := prov.RecoverVolume(ctx, "v"); err != nil { + t.Fatalf("%s recovery: %v", holder, err) + } + return prov + } + healthy := func(epoch uint64) restoreProjection { + return restoreProjection{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: epoch, EndpointVersion: 1, Healthy: true}} + } + + // The predecessor writes, cuts and detaches; the clean move grants new-node. + oldProv := open("old-node/r", healthy(1)) + b, err := oldProv.Open(ctx, "v") + if err != nil { + t.Fatal(err) + } + if n, err := b.Write(ctx, 0, bytes.Repeat([]byte{0xA5}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + if err := b.Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := oldProv.CaptureVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + detached, _, err := oldProv.DetachVolume(ctx, "v") + if err != nil || detached.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach: %+v %v", detached.Head, err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", authority.WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: detached.Head.Gen}); err != nil { + t.Fatal(err) + } + // The lease reply's validity is measured on the real clock: keep the + // fake clocks at real time for the move and the grantee's renewal. + masterNow = time.Now() + if min := start.Add(500 * time.Millisecond); masterNow.Before(min) { + masterNow = min + } + hostNow = masterNow + clean, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"}, readHead()) + if err != nil || clean.NewEpoch != 2 { + t.Fatal("clean move:", clean, err) + } + predecessor := readHead() + + // The grantee renews (its guard is valid), then pauses before its claim. + guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}}, skewLeaseClient{p}, + &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow }) + if err != nil { + t.Fatal(err) + } + if err := guard.Refresh(ctx); err != nil { + t.Fatal("grantee renewal:", err) + } + if !guard.Projection().Healthy { + t.Fatal("grantee not serving after its renewal") + } + lease := p.WorkspaceState("v").Lease + if lease == nil || lease.Epoch != 2 { + t.Fatalf("grantee lease %+v", lease) + } + skew := time.Duration(lease.MaxClockSkewNS) + grantBarrier := time.Unix(0, lease.ExpiresAtNS).Add(skew) + forced := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, + TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + + // After the predecessor's lease (plus skew) but before the grant's: refused. + masterNow = oldBarrier.Add(skew).Add(grantBarrier.Sub(oldBarrier.Add(skew)) / 2) + if !masterNow.After(oldBarrier.Add(skew)) || !masterNow.Before(grantBarrier) { + t.Fatalf("test clock: %s not between %s and %s", masterNow, oldBarrier.Add(skew), grantBarrier) + } + if _, err := p.MoveWorkspace(ctx, forced, readHead()); err == nil { + t.Fatal("forced move admitted on the predecessor's lease before the grant's lease expired") + } + masterNow = grantBarrier + r, err := p.MoveWorkspace(ctx, forced, readHead()) + if err != nil || r.NewEpoch != 3 || r.HeadGen != predecessor.Gen { + t.Fatal("forced move after the grant's lease expired:", r, err) + } + + // The grantee resumes before the new owner claims. Its attach is refused. + hostNow = masterNow + if guard.Projection().Healthy { + t.Fatal("the paused grantee still serves after the forced move") + } + granteeProv := open("new-node/r", guard) + deadline := time.Now().Add(300 * time.Millisecond) + for time.Now().Before(deadline) { + if h := readHead(); h != predecessor { + t.Fatalf("the paused grantee claimed HEAD after the forced move: %+v, was %+v", h, predecessor) + } + time.Sleep(20 * time.Millisecond) + } + if bk, err := granteeProv.Open(ctx, "v"); err == nil { + if n, err := bk.Write(ctx, 0, make([]byte, 4096)); err == nil && n == 4096 { + if err := bk.Sync(ctx); err == nil { + if _, err := granteeProv.CaptureVolume(ctx, "v"); err == nil { + t.Fatal("the paused grantee published a cut after the forced move") + } + } + } + } + if h := readHead(); h != predecessor { + t.Fatalf("HEAD changed by the paused grantee: %+v", h) + } + + // The new owner claims at the higher epoch. + open("third-node/r", healthy(3)) + if h := readHead(); h.Epoch != 3 || h.Holder != "third-node/r" || h.RemoteLSN != predecessor.RemoteLSN { + t.Fatalf("HEAD after the new owner's claim: %+v", h) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index fabe00514c..44b7ab10bf 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -136,6 +136,15 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } + // A forced move reads HEAD only after its lease admission holds: once + // the expected holder's grants have expired, it can no longer change + // HEAD, so the HEAD read below is the one the move and its lost range + // rest on. The publisher re-checks admission when it issues the move. + if q.GetKind() == "forced" { + if err := s.host.Publisher().WorkspaceForcedMoveAdmitted(ctx, q.GetVolumeId(), q.GetRequestId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()); err != nil { + return nil, workspaceError(err) + } + } // Always bound the configured reader, even when the caller omitted a deadline. readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() diff --git a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go new file mode 100644 index 0000000000..3a6b4defa4 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go @@ -0,0 +1,190 @@ +package master + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// seedDetachedHead installs the predecessor's detached final cut. +func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, holder string, epoch, lsn uint64) storage.ChunkHead { + t.Helper() + h := storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: lsn, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: holder, Epoch: epoch, Gen: 1}} + gen, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, h) + if err != nil { + t.Fatal(err) + } + h.Gen = gen + return h +} + +// A clean move grants vol-a to node-b, whose host dies before its first +// renewal and so before it claims HEAD: HEAD still names node-a. A forced +// move to node-c is refused before the lease the issue started has expired +// plus the skew bound, without reading HEAD; after it, it reads HEAD (only +// then) and is granted on the predecessor's unchanged HEAD. A late claim by +// the dead grantee never displaces the new owner's higher epoch. +func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { + // The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s. + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + var reads atomic.Int64 + var lastReadNS atomic.Int64 + reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) { + reads.Add(1) + lastReadNS.Store(time.Now().UnixNano()) + h, err := remote.GetHead(ctx) + if err != nil { + return authority.WorkspaceHead{}, err + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil + } + const skew = 100 * time.Millisecond + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + + for _, server := range []string{"node-a", "node-b", "node-c"} { + if _, err = m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err = lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + dst := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + third := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-c", DataAddr: "127.0.0.1:39200", CtrlAddr: "127.0.0.1:39100"} + for _, b := range []*control.WorkspaceBinding{src, dst, third} { + if _, err = ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err = ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-a", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-a", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch} + if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil { + t.Fatal(err) + } + + // node-a detaches its final cut and ACKs; the clean move grants node-b. + seed := seedDetachedHead(t, ctx, remote, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) + if _, err = ws.RevokeWorkspace(ctx, oldID); err != nil { + t.Fatal(err) + } + if _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: oldID, HeadGen: seed.Gen}); err != nil { + t.Fatal(err) + } + clean, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"}) + if err != nil { + t.Fatal("clean move:", err) + } + grantee := clean.GetNewEpoch() + st := m.Publisher().WorkspaceState("vol-a") + if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking { + t.Fatalf("the issued move must start node-b's lease: %+v", st) + } + barrier := time.Unix(0, st.Lease.ExpiresAtNS).Add(skew) + if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee { + t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err) + } + + // node-b dies before renewing or claiming. Before expiry plus skew the + // forced move is refused, and HEAD is not read for it. + forced := &control.WorkspaceMove{RequestId: "forced-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: grantee, TargetReplicaId: "r1", + TargetServerId: "node-c", TargetDataAddr: third.DataAddr, TargetCtrlAddr: third.CtrlAddr, Kind: "forced", Force: true} + before := reads.Load() + if _, err := ws.MoveWorkspace(ctx, forced); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("forced move before the issued lease expired: %v", err) + } + if n := reads.Load() - before; n != 0 { + t.Fatalf("HEAD read %d times for a forced move whose admission had not passed", n) + } + + select { + case <-time.After(time.Until(barrier) + 50*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + grant, err := ws.MoveWorkspace(ctx, forced) + if err != nil { + t.Fatal("forced move after the issued lease expired:", err) + } + if reads.Load() == before || time.Unix(0, lastReadNS.Load()).Before(barrier) { + t.Fatalf("the forced move's HEAD was not read after admission (reads %d, last read %s, barrier %s)", reads.Load()-before, time.Unix(0, lastReadNS.Load()), barrier) + } + line, _ := m.Publisher().VolumeAuthorityLine("vol-a") + if !grant.Issued || grant.NewEpoch != grantee+1 || line.Epoch != grant.NewEpoch || grant.HeadGen != seed.Gen || grant.RemoteLsn != seed.RemoteLSN { + t.Fatalf("forced grant %+v line %+v; want epoch %d on HEAD gen %d lsn %d", grant, line, grantee+1, seed.Gen, seed.RemoteLSN) + } + if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: grantee}); err == nil { + t.Fatal("the dead grantee's epoch renewed after the forced move") + } + + // A late grantee claim. (b) Its CAS lands after the forced move's HEAD + // read but before the new owner claims: the new owner still takes HEAD + // at the higher epoch, and the grantee is fenced afterwards. + granteeCfg := storage.ChunkLayerConfig{Epoch: grantee, Holder: "node-b/r1"} + ownerCfg := storage.ChunkLayerConfig{Epoch: grant.NewEpoch, Holder: "node-c/r1"} + late, err := storage.ClaimChunkHead(ctx, remote, granteeCfg) + if err != nil { + t.Fatal("late grantee claim landing first:", err) + } + owned, err := storage.ClaimChunkHead(ctx, remote, ownerCfg) + if err != nil || owned.Epoch != grant.NewEpoch || owned.Holder != "node-c/r1" || owned.RemoteLSN != seed.RemoteLSN { + t.Fatalf("new owner's claim over the late grantee: %+v %v", owned, err) + } + if _, err := storage.ClaimChunkHead(ctx, remote, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("grantee re-claim after the new owner: %v; want fenced", err) + } + stale := late + stale.State = storage.ChunkHeadActive + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: late.Gen, Epoch: late.Epoch}, stale); !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("grantee HEAD write after the new owner: %v; want a CAS precondition failure", err) + } + // (a) The new owner claims first; the late grantee claim is fenced. + fresh := storage.NewMemChunkRemote() + seedDetachedHead(t, ctx, fresh, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) + if _, err := storage.ClaimChunkHead(ctx, fresh, ownerCfg); err != nil { + t.Fatal(err) + } + if _, err := storage.ClaimChunkHead(ctx, fresh, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("late grantee claim after the new owner: %v; want fenced", err) + } + for _, r := range []*storage.MemChunkRemote{remote, fresh} { + if h, err := r.GetHead(ctx); err != nil || h.Epoch != grant.NewEpoch || h.Holder != "node-c/r1" { + t.Fatalf("HEAD after the late claim: %+v %v; want the new owner", h, err) + } + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 873827ed7d..5872e8378b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -88,15 +88,15 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's, or, when that holder never claimed it, still the HEAD its move was issued against (same generation and remote LSN, older epoch; forced moves only) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), so a holder that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | ### M3 Replica role and peer state @@ -386,7 +386,7 @@ Notes: | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | @@ -430,7 +430,7 @@ Notes: | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `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-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 granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | Notes: From 199bb65fc697c1d8749b319381996aa63605bd3d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:47:11 -0800 Subject: [PATCH 08/35] Publish the issued lease atomically and accept any older-epoch HEAD A move issue published the new epoch's lease view and then, in a separate lease-lock section, replaced the deadline with issue + TTL. A renewal of the new epoch landing between the two raised the deadline, and the issue then lowered it under the outstanding grant, so later renewals inside that grant were refused. The view and the initial deadline are now published in one section, and the issue never lowers a deadline. A forced move now accepts any HEAD at an epoch below the expected one, read after admission, with the lost range from that HEAD's RemoteLSN. Requiring the HEAD generation and LSN recorded at the issue refused the volume for good when an earlier holder's in-flight claim landed after the next move was issued and that move's holder then died unclaimed. A HEAD at the expected or a higher epoch that is not the expected holder's is still refused; clean moves are unchanged. Comments now say what admission guarantees: the expired holder starts no new claim or cut, but a claim already sent may still land. The paused-holder test witnesses the refused attach decision instead of watching HEAD for a fixed time, and the design document and invariants record the issue-to-lease transition, the forced HEAD rule and the open model check. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 12 ++- seaweed-block/core/authority/workspace.go | 33 +++----- .../authority/workspace_issue_publish_test.go | 62 ++++++++++++++ .../core/authority/workspace_lease_view.go | 22 ++++- .../workspace_unclaimed_grant_test.go | 80 ++++++++++++++----- .../master/workspace_paused_grantee_test.go | 80 +++++++++++++++---- .../core/host/master/workspace_service.go | 9 ++- .../docs/design/agent-workspace-design.md | 14 +++- seaweed-block/docs/design/invariants.md | 14 ++-- 9 files changed, 253 insertions(+), 73 deletions(-) create mode 100644 seaweed-block/core/authority/workspace_issue_publish_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index fcac948db0..85e5bd9bcf 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -172,6 +172,10 @@ type Publisher struct { leaseClosing bool extWG sync.WaitGroup extendFailures map[string]int // guarded by mu + + // testAfterIssuePublish, when set by a test, runs under mu right after + // an issued move's lease view is published. + testAfterIssuePublish func(volume string) } // PublicationAdmission surrounds an ordinary mint with local ownership/lifetime @@ -610,10 +614,14 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } p.state[k] = assignmentState{info: next, present: true} - p.refreshLeaseViewLocked(ask.VolumeID) if issuedWorkspace != nil { // The issued move starts the new holder's lease (issuedAt+TTL grant). - p.setLeaseDeadlineLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL), false) + p.publishIssuedLeaseLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL)) + if hook := p.testAfterIssuePublish; hook != nil { + hook(ask.VolumeID) + } + } else { + p.refreshLeaseViewLocked(ask.VolumeID) } // Snapshot subscribers under lock, release the lock BEFORE diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index a1f4c1877d..b197774f0d 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -273,9 +273,11 @@ func sameWorkspaceRequest(r WorkspaceMoveRecord, q WorkspaceMoveRequest) bool { // WorkspaceForcedMoveAdmitted reports whether a forced move of volume away // from holder at epoch is admitted now: the lease expiry and the granted or // restart deadline, each plus the clock-skew margin, have passed. A caller -// reads HEAD only after this returns nil, so the HEAD a forced move checks -// can no longer be changed by a holder of that epoch's grants. The move -// itself checks admission again. A request id the journal already holds is +// reads HEAD only after this returns nil: by then the holder's own lease has +// expired, so it starts no new claim or cut. HEAD is not frozen: a claim the +// holder or an earlier one sent may still land (ownership only, RemoteLSN +// unchanged), and the next holder's higher-epoch claim supersedes it. The +// move itself checks admission again. A request id the journal already holds is // left to MoveWorkspace: its replay never uses a new HEAD. func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, requestID, holder string, epoch uint64) error { if err := ctx.Err(); err != nil { @@ -317,22 +319,6 @@ func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLea return lostUntil, nil } -// headUnclaimedSinceIssue reports whether h is still the HEAD the move to the -// expected holder was issued against, so that holder never claimed it (every -// HEAD write advances Gen). Only a forced move may use it: the expected -// holder's grant has expired, so it can no longer claim. -func headUnclaimedSinceIssue(s *WorkspaceState, q WorkspaceMoveRequest, h WorkspaceHead) bool { - for i := len(s.Moves) - 1; i >= 0; i-- { - r := s.Moves[i] - if !r.Issued { - continue - } - return r.NewEpoch == q.ExpectedEpoch && r.NewHost == q.ExpectedHost && r.NewReplicaID == q.ExpectedReplicaID && - h.Gen != 0 && h.Gen == r.HeadGen && h.RemoteLSN == r.RemoteLSN && h.Epoch < q.ExpectedEpoch - } - return false -} - // issueWorkspaceMove marks the move issued and starts the new holder's lease // in the same write as the new epoch, so a holder that dies before its first // renewal still leaves a lease that expires and admits a forced move. @@ -384,9 +370,12 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra } owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID if !owned && q.Kind == "forced" { - // A holder that died between its grant and its claim left HEAD - // naming its predecessor. - owned = headUnclaimedSinceIssue(s, q, h) + // Admitted (the expected holder's lease has expired) and HEAD read + // after that: a HEAD at an older epoch means the expected holder + // never claimed it, or an earlier holder's late claim landed. The + // lost range starts at this HEAD's RemoteLSN. A HEAD at the expected + // or a higher epoch that is not the expected holder's stays refused. + owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch } if !owned { return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") diff --git a/seaweed-block/core/authority/workspace_issue_publish_test.go b/seaweed-block/core/authority/workspace_issue_publish_test.go new file mode 100644 index 0000000000..3c650a87dc --- /dev/null +++ b/seaweed-block/core/authority/workspace_issue_publish_test.go @@ -0,0 +1,62 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// A renewal of the new epoch that lands right after an issued move is +// published (the seam runs under the publisher lock, where only the leaf +// renewal path can run) raises the deadline; the issue must not lower it +// afterwards, or a later renewal inside that outstanding grant is refused. +func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + now = now.Add(100 * time.Millisecond) + issued := now + var grant WorkspaceLease + var hooked int + p.testAfterIssuePublish = func(volume string) { + hooked++ + now = issued.Add(200 * time.Millisecond) + l, err := p.RenewWorkspaceLease(ctx, volume, "r", 2) + if err != nil { + t.Errorf("renewal of the new epoch at the issue publication: %v", err) + return + } + grant = l + } + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if r, err := p.MoveWorkspace(ctx, req, predecessorHead); err != nil || r.NewEpoch != 2 { + t.Fatal("clean move:", r, err) + } + p.testAfterIssuePublish = nil + if hooked != 1 || grant.Epoch != 2 || grant.ExpiresAtNS != issued.Add(200*time.Millisecond+grantTTL).UnixNano() { + t.Fatalf("seam ran %d times, grant %+v", hooked, grant) + } + if got := p.leaseDeadlineLockedForTest("v"); got.UnixNano() < grant.ExpiresAtNS { + t.Fatalf("the issue lowered the deadline to %s below the outstanding grant %s", got, time.Unix(0, grant.ExpiresAtNS)) + } + // Past issue+TTL but inside the outstanding grant: the holder still renews. + now = issued.Add(grantTTL + 50*time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("renewal inside the outstanding grant:", err) + } + assertLeaseViewMatches(t, p, "after issue and renewal") + p.CloseWorkspaceExtenders() +} diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index d6b57dcab9..758c86766b 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -68,6 +68,25 @@ func (p *Publisher) refreshLeaseViewLocked(volume string) { lv.d = d } +// publishIssuedLeaseLocked publishes an issued move's derived view (the new +// epoch and the new holder's lease) and that lease's initial deadline in one +// leaseMu section: a renewal of the new epoch sees both or neither, so the +// issue never lowers a deadline a renewal has raised. Caller holds p.mu. +func (p *Publisher) publishIssuedLeaseLocked(volume string, deadline time.Time) { + d := p.deriveLeaseLocked(volume) + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil { + lv = &leaseView{} + p.leaseViews[volume] = lv + } + lv.d = d + if deadline.After(lv.deadline) { + lv.deadline = deadline + } +} + // leaseDeadlineLocked reads the granted deadline. Caller holds p.mu. func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { p.leaseMu.Lock() @@ -78,8 +97,7 @@ func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { return time.Time{} } -// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue: the -// new holder's lease starts with the grant issue+TTL) or, +// setLeaseDeadlineLocked replaces the deadline (restart rule) or, // with raise, raises it to at least t (a grant). Caller holds p.mu. func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise bool) { d := p.deriveLeaseLocked(volume) diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go index e2b88b87f7..d57b36760e 100644 --- a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -129,9 +129,11 @@ func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) { } } -// The HEAD rule: a forced move from a grantee that never claimed HEAD accepts -// the predecessor's HEAD only when it is unchanged since the issue (same Gen -// and RemoteLSN, an older epoch). Clean moves never accept it. +// The HEAD rule: after admission, a forced move from a grantee that never +// claimed HEAD accepts any HEAD at an older epoch (its Gen and RemoteLSN may +// have moved, e.g. by an earlier holder's late claim); the lost range starts +// at that HEAD's RemoteLSN. A HEAD at the expected or a higher epoch that is +// not the grantee's, or no HEAD, is refused. Clean moves never accept it. func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { ctx := context.Background() disk, _ := newTempStore(t) @@ -153,20 +155,16 @@ func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { } now = issued.Add(10 * grantTTL) - changed := map[string]WorkspaceHead{} + refused := map[string]WorkspaceHead{} h := predecessorHead - h.Gen++ - changed["gen advanced"] = h - h = predecessorHead - h.RemoteLSN++ - changed["remote LSN differs"] = h - h = predecessorHead h.Epoch = 2 - changed["epoch not older"] = h + refused["expected epoch, another holder"] = h + h = WorkspaceHead{Gen: 9, Epoch: 3, Holder: "third-node/r", RemoteLSN: 50} + refused["epoch above expected"] = h h = predecessorHead h.Gen = 0 - changed["no HEAD"] = h - for what, h := range changed { + refused["no HEAD"] = h + for what, h := range refused { if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-"+what), h); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { t.Fatalf("%s: forced move accepted %+v: %v", what, h, err) } @@ -174,16 +172,21 @@ func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { t.Fatal("a refused HEAD changed authority or journal", line) } - r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead) - if err != nil || r.NewEpoch != 3 { - t.Fatal("forced move with the unchanged predecessor HEAD:", r, err) + // An older-epoch HEAD whose Gen and RemoteLSN moved since the issue. + moved := predecessorHead + moved.Gen, moved.RemoteLSN = predecessorHead.Gen+1, predecessorHead.RemoteLSN+8 + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), moved) + if err != nil || r.NewEpoch != 3 || r.HeadGen != moved.Gen || r.RemoteLSN != moved.RemoteLSN { + t.Fatal("forced move with an older-epoch HEAD:", r, err) } - // A chain: the epoch-3 grantee dies unclaimed too; HEAD is still the - // same predecessor HEAD, recorded by both moves. + if lost := p.WorkspaceLostRanges("v"); len(lost) != 1 || lost[0].LostAfterLSN != moved.RemoteLSN { + t.Fatalf("lost range must start at the fresh HEAD's RemoteLSN: %+v", lost) + } + // A chain: the epoch-3 grantee dies unclaimed too. now = now.Add(10 * grantTTL) next := forcedFromGrantee("forced-again") next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 - if r, err := p.MoveWorkspace(ctx, next, predecessorHead); err != nil || r.NewEpoch != 4 { + if r, err := p.MoveWorkspace(ctx, next, moved); err != nil || r.NewEpoch != 4 { t.Fatal("second unclaimed grant:", r, err) } } @@ -269,3 +272,42 @@ func TestWorkspaceReplayedIssueStartsGranteeLease(t *testing.T) { t.Fatal("forced move after the replayed grant expired:", r, err) } } + +// The double fault: grantee 1 renews and sends its HEAD claim, then stalls; +// its lease expires and a forced move grants grantee 2 against the +// predecessor's HEAD; grantee 1's in-flight claim lands afterwards (HEAD +// moves to its epoch and the next generation); grantee 2 dies unclaimed. +// The next forced move must still be admitted on that older-epoch HEAD, with +// the lost range from its RemoteLSN; never refused for good. +func TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + now = issued.Add(100 * time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("grantee 1 renewal:", err) + } + // Grantee 1's claim is in flight; it renews no more. + now = now.Add(10 * grantTTL) + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-1"), predecessorHead) + if err != nil || r.NewEpoch != 3 { + t.Fatal("forced move to grantee 2:", r, err) + } + late := WorkspaceHead{Gen: predecessorHead.Gen + 1, Epoch: 2, Holder: "new-node/r", RemoteLSN: predecessorHead.RemoteLSN} + // Grantee 2 dies unclaimed. + now = now.Add(10 * grantTTL) + next := forcedFromGrantee("forced-2") + next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 + r, err = p.MoveWorkspace(ctx, next, late) + if err != nil || r.NewEpoch != 4 || r.HeadGen != late.Gen || r.RemoteLSN != late.RemoteLSN { + t.Fatal("forced move after grantee 1's late claim and grantee 2's death:", r, err) + } + lost := p.WorkspaceLostRanges("v") + if len(lost) != 2 || lost[1].NewEpoch != 4 || lost[1].LostAfterLSN != late.RemoteLSN { + t.Fatalf("lost ranges %+v", lost) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 4 { + t.Fatal("authority line", line) + } +} diff --git a/seaweed-block/core/host/master/workspace_paused_grantee_test.go b/seaweed-block/core/host/master/workspace_paused_grantee_test.go index 30d4749b97..69af179701 100644 --- a/seaweed-block/core/host/master/workspace_paused_grantee_test.go +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -3,6 +3,7 @@ package master import ( "bytes" "context" + "sync" "testing" "time" @@ -14,6 +15,47 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) +// attachWitness records each projection read: the first refused read (not +// healthy) with the HEAD current at that instant, and whether any read was +// healthy. +type attachWitness struct { + base frontend.ProjectionView + head func() authority.WorkspaceHead + + mu sync.Mutex + refusals int + firstAt authority.WorkspaceHead + healthy bool +} + +func (w *attachWitness) Projection() frontend.Projection { + p := w.base.Projection() + var h authority.WorkspaceHead + if !p.Healthy { + h = w.head() + } + w.mu.Lock() + defer w.mu.Unlock() + if p.Healthy { + w.healthy = true + } else if w.refusals++; w.refusals == 1 { + w.firstAt = h + } + return p +} + +func (w *attachWitness) first() (authority.WorkspaceHead, int) { + w.mu.Lock() + defer w.mu.Unlock() + return w.firstAt, w.refusals +} + +func (w *attachWitness) admitted() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.healthy +} + // A grantee renews its issued lease, then pauses before claiming HEAD. The // forced move away from it is admitted only after the GRANT's lease expiry // plus skew (the predecessor's older lease never satisfies it), and is @@ -155,25 +197,33 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { if guard.Projection().Healthy { t.Fatal("the paused grantee still serves after the forced move") } - granteeProv := open("new-node/r", guard) - deadline := time.Now().Add(300 * time.Millisecond) - for time.Now().Before(deadline) { - if h := readHead(); h != predecessor { - t.Fatalf("the paused grantee claimed HEAD after the forced move: %+v, was %+v", h, predecessor) + // The attach decision is witnessed, not waited for: recovery runs the + // first attach attempt synchronously, and every admission read of the + // projection records the HEAD current at that instant. Close then + // settles the deferred attempts, so none can land afterwards. + witness := &attachWitness{base: guard, head: func() authority.WorkspaceHead { + h, err := remote.GetHead(context.Background()) // also read off the test goroutine: no t.Fatal + if err != nil { + return authority.WorkspaceHead{} } - time.Sleep(20 * time.Millisecond) + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + }} + granteeProv := open("new-node/r", witness) + refusedAt, refusals := witness.first() + if refusals == 0 || refusedAt != predecessor { + t.Fatalf("no witnessed refused attach decision while the predecessor HEAD was current (refusals %d, HEAD %+v)", refusals, refusedAt) } - if bk, err := granteeProv.Open(ctx, "v"); err == nil { - if n, err := bk.Write(ctx, 0, make([]byte, 4096)); err == nil && n == 4096 { - if err := bk.Sync(ctx); err == nil { - if _, err := granteeProv.CaptureVolume(ctx, "v"); err == nil { - t.Fatal("the paused grantee published a cut after the forced move") - } - } - } + if witness.admitted() { + t.Fatal("the paused grantee's attach read a healthy projection after the forced move") } if h := readHead(); h != predecessor { - t.Fatalf("HEAD changed by the paused grantee: %+v", h) + t.Fatalf("the paused grantee claimed HEAD after the forced move: %+v, was %+v", h, predecessor) + } + if err := granteeProv.Close(); err != nil { + t.Fatal(err) + } + if h := readHead(); h != predecessor || witness.admitted() { + t.Fatalf("HEAD changed by the paused grantee before its provider settled: %+v", h) } // The new owner claims at the higher epoch. diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 44b7ab10bf..4f51bf89d7 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -136,10 +136,11 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } - // A forced move reads HEAD only after its lease admission holds: once - // the expected holder's grants have expired, it can no longer change - // HEAD, so the HEAD read below is the one the move and its lost range - // rest on. The publisher re-checks admission when it issues the move. + // A forced move reads HEAD only after its lease admission holds: the + // expected holder's lease has then expired, so it starts no new claim or + // cut before this read. A claim it already sent may still land after it + // (WorkspaceForcedMoveAdmitted). The publisher re-checks admission when + // it issues the move. if q.GetKind() == "forced" { if err := s.host.Publisher().WorkspaceForcedMoveAdmitted(ctx, q.GetVolumeId(), q.GetRequestId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()); err != nil { return nil, workspaceError(err) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 97e3a0a084..0a06dc8f5b 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -245,6 +245,8 @@ The attempt path is never removed, so a late create can never land after a delet **FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. +**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's expiry and deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim. + **Takeover** (`core/storage/chunk_restore.go` `ClaimChunkHead`, called before the chunk layer attaches in `core/frontend/durable/provider_chunk.go`): read HEAD; fence if HEAD has a higher epoch or another holder at the same epoch; seed the local LSN frontier from HEAD (`PrepareRestore`); CAS HEAD to the new epoch and holder with `State = active`; on an unknown outcome, succeed only if a re-read shows the exact proposal. I/O opens afterwards; blocks load lazily on first read. ```mermaid @@ -266,7 +268,14 @@ sequenceDiagram A->>A: self-fence when ValidForNs runs out M->>M: wait for expiry, restart deadline and skew bound, then mint epoch e+1 end + M->>M: the issue write also starts B's lease (horizon issue+1.5·TTL, deadline issue+TTL) M->>B: assignment at epoch e+1 and a lease + opt B dies before renewing or claiming (HEAD still at epoch e) + M->>M: wait for B's lease expiry, deadline and skew bound + M->>F: GetHead (only after that admission) + M->>M: HEAD epoch is older than e+1, so mint epoch e+2 for host C, lost range from that HEAD's RemoteLSN + Note over B,F: a claim B already sent may still land at e+1, C's claim at e+2 supersedes it, and a returning B is refused at attach (expired lease) and by the higher HEAD epoch + end B->>F: GetHead B->>B: refuse if HEAD epoch is higher, else seed the local frontier from HEAD B->>F: CASHead expected {current gen, e}, next {epoch e+1, holder B, active} @@ -284,13 +293,14 @@ Lease states: ```mermaid stateDiagram-v2 state "Lease (blockmaster)" as L { - [*] --> Granted: Renew + [*] --> Granted: first Renew after bind + [*] --> Granted: move issue starts the new holder's lease Granted --> Granted: Renew before horizon and deadline (from memory) Granted --> Revoking: BeginWorkspaceRevocation Revoking --> Acked: host acks detached HEAD gen while the lease is valid Acked --> Moved: CLEAN move Granted --> Expired: horizon or deadline passes - Expired --> Moved: FORCED move after expiry + skew bound + Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) } ``` diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5872e8378b..e60c026e60 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -95,8 +95,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's, or, when that holder never claimed it, still the HEAD its move was issued against (same generation and remote LSN, older epoch; forced moves only) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), so a holder that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001` | ### M3 Replica role and peer state @@ -383,9 +383,9 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE | | `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | @@ -427,16 +427,16 @@ Notes: | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `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-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 granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `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` (`core/authority/workspace_unclaimed_grant_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-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace` | `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 | Notes: - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). -- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. +- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. ### B.5 Workspace: the cut pipeline From f9b8487012609f1e2382e5eebcaf768c15822807 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:14:30 -0800 Subject: [PATCH 09/35] Guard the issued lease publication as one lease-lock hold The behavioural test runs its renewal after the publication helper returns, so a helper split into two lease-lock sections (refresh the view, then set the deadline) still passes it: nothing in the gap between the sections can be intercepted without a production hook. Add a source-structure guard, like the existing non-forgeability scan: the helper takes the lease lock exactly once, holds it to return, assigns both the derived view and the deadline under it, and calls no other publisher method that takes the lease lock, directly or transitively. Co-Authored-By: Claude Opus 5.5 --- .../workspace_issue_publish_structure_test.go | 166 ++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 seaweed-block/core/authority/workspace_issue_publish_structure_test.go diff --git a/seaweed-block/core/authority/workspace_issue_publish_structure_test.go b/seaweed-block/core/authority/workspace_issue_publish_structure_test.go new file mode 100644 index 0000000000..c9ca23bcb6 --- /dev/null +++ b/seaweed-block/core/authority/workspace_issue_publish_structure_test.go @@ -0,0 +1,166 @@ +package authority + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// publisherMethods parses this package's production files and returns every +// *Publisher method declaration by name. +func publisherMethods(t *testing.T) map[string]*ast.FuncDecl { + t.Helper() + paths, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + out := map[string]*ast.FuncDecl{} + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + src, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(fset, path, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Recv == nil || len(fn.Recv.List) != 1 || fn.Body == nil { + continue + } + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if id, ok := typ.(*ast.Ident); ok && id.Name == "Publisher" { + out[fn.Name.Name] = fn + } + } + } + return out +} + +// leaseMuCall reports whether call is .leaseMu.(). +func leaseMuCall(call *ast.CallExpr, method string) bool { + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != method { + return false + } + inner, ok := sel.X.(*ast.SelectorExpr) + return ok && inner.Sel.Name == "leaseMu" +} + +// The issued move's lease view and its initial deadline are published in +// ONE leaseMu hold (INV-LEASE-VIEW-001): a renewal of the new epoch sees both +// or neither. Structural guard: publishIssuedLeaseLocked takes leaseMu +// exactly once, holds it (deferred unlock) across both the derived-view and +// the deadline assignment, and calls no other Publisher method that takes +// leaseMu, directly or transitively. A split into two sections (for example +// refreshLeaseViewLocked then setLeaseDeadlineLocked) fails it. +func TestWorkspaceIssuePublishIsOneLeaseHold(t *testing.T) { + methods := publisherMethods(t) + callees := map[string][]string{} + direct := map[string]bool{} + for name, fn := range methods { + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if leaseMuCall(call, "Lock") { + direct[name] = true + } else if sel, ok := call.Fun.(*ast.SelectorExpr); ok { + if _, isMethod := methods[sel.Sel.Name]; isMethod { + callees[name] = append(callees[name], sel.Sel.Name) + } + } + return true + }) + } + takes := map[string]bool{} + for name := range direct { + takes[name] = true + } + for changed := true; changed; { + changed = false + for name, cs := range callees { + for _, c := range cs { + if takes[c] && !takes[name] { + takes[name], changed = true, true + } + } + } + } + // The analysis is not vacuous: the two halves of a split publication + // are known lease-taking methods. + for _, name := range []string{"refreshLeaseViewLocked", "setLeaseDeadlineLocked", "leaseDeadlineLocked"} { + if !takes[name] { + t.Fatalf("structure scan does not see %s take leaseMu; the guard would be vacuous", name) + } + } + + fn := methods["publishIssuedLeaseLocked"] + if fn == nil { + t.Fatal("publishIssuedLeaseLocked not found") + } + var locks, unlocks, deferredUnlocks int + var lockPos token.Pos + var viewSet, deadlineSet []token.Pos + var lockingCallees []string + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.DeferStmt: + if leaseMuCall(x.Call, "Unlock") { + deferredUnlocks++ + return false + } + case *ast.CallExpr: + switch { + case leaseMuCall(x, "Lock"): + locks++ + lockPos = x.Pos() + case leaseMuCall(x, "Unlock"): + unlocks++ + default: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && takes[sel.Sel.Name] { + lockingCallees = append(lockingCallees, sel.Sel.Name) + } + } + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok { + switch sel.Sel.Name { + case "d": + viewSet = append(viewSet, x.Pos()) + case "deadline": + deadlineSet = append(deadlineSet, x.Pos()) + } + } + } + } + return true + }) + if locks != 1 || deferredUnlocks != 1 || unlocks != 0 { + t.Fatalf("publishIssuedLeaseLocked must take leaseMu exactly once and hold it to return (defer Unlock): Lock %d, deferred Unlock %d, explicit Unlock %d", locks, deferredUnlocks, unlocks) + } + if len(lockingCallees) != 0 { + t.Fatalf("publishIssuedLeaseLocked calls methods that take leaseMu (a second lease hold): %v", lockingCallees) + } + if len(viewSet) == 0 || len(deadlineSet) == 0 { + t.Fatalf("publishIssuedLeaseLocked must set both the derived view (lv.d: %d) and the deadline (lv.deadline: %d)", len(viewSet), len(deadlineSet)) + } + for _, pos := range append(append([]token.Pos{}, viewSet...), deadlineSet...) { + if pos < lockPos { + t.Fatal("publishIssuedLeaseLocked sets the view or the deadline before taking leaseMu") + } + } +} From c400b28f5fb1015fc80c50f75e1782aa46201326 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:31:51 -0800 Subject: [PATCH 10/35] test: reproduce cross-session replica byte regression --- .../apply_gate_cross_session_test.go | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 seaweed-block/core/replication/apply_gate_cross_session_test.go diff --git a/seaweed-block/core/replication/apply_gate_cross_session_test.go b/seaweed-block/core/replication/apply_gate_cross_session_test.go new file mode 100644 index 0000000000..15570d87e8 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_cross_session_test.go @@ -0,0 +1,48 @@ +package replication + +import ( + "bytes" + "testing" +) + +// Both sessions are initialized before either writes the contested LBA. +// This fixes the ordering without relying on a probabilistic goroutine race. +func TestApplyGate_OverlappingSessionsNeverRegressBytes(t *testing.T) { + for _, live := range []bool{false, true} { + name := "recovery_then_older_recovery" + if live { + name = "live_then_older_recovery" + } + t.Run(name, func(t *testing.T) { + gate, store := newGate(t) + older, newer := recoveryLineage(10, 120), recoveryLineage(11, 120) + if err := gate.ApplyRecovery(older, 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if err := gate.ApplyRecovery(newer, 1, makeData(2), 2); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0xBB}, blockSize) + apply := gate.ApplyRecovery + if live { + apply = gate.ApplyLive + } + if err := apply(newer, 5, want, 120); err != nil { + t.Fatal(err) + } + if err := gate.ApplyRecovery(older, 5, bytes.Repeat([]byte{0xAA}, blockSize), 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(5) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("cross-session stale recovery regressed bytes: got %x want %x", got[:8], want[:8]) + } + if !gate.SessionRecoveryCoverage(older.SessionID, 5) { + t.Fatal("stale recovery did not advance its own coverage") + } + }) + } +} From 67e0cf0bbe7a7661134795c5a91d6748d4d7418e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:34:31 -0800 Subject: [PATCH 11/35] test: pin duplicate recovery preparation and delayed probe schedules --- .../core/adapter/recovery_dedup_test.go | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 seaweed-block/core/adapter/recovery_dedup_test.go diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go new file mode 100644 index 0000000000..86ed57f6ed --- /dev/null +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -0,0 +1,65 @@ +package adapter + +import ( + "sync" + "testing" + + "github.com/seaweedfs/seaweed-block/core/engine" +) + +func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResult) { + t.Helper() + exec := newMockExecutor() + exec.autoClose = false + // The automatic probe is irrelevant to this controlled delivery schedule. + // Its wrong-replica result is rejected regardless of when it returns. + exec.probeResults["r1"] = ProbeResult{ReplicaID: "other"} + a := NewVolumeReplicaAdapter(exec) + a.OnAssignment(AssignmentInfo{VolumeID: "vol1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + probe := ProbeResult{ReplicaID: "r1", Success: true, EndpointVersion: 1, TransportEpoch: 1, + ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} + a.OnProbeResult(probe) + t.Cleanup(func() { + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + }) + return a, exec, probe +} + +func TestAdapter_OneRecoveryPreparedWithinProbeBatch(t *testing.T) { + a, exec, probe := dedupAdapter(t) + sid := exec.latestSessionID("StartCatchUp") + // A failed start permits a new probe to retry. Both reachability and facts + // in that one probe must see the first newly prepared recovery session. + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: sid, FailureKind: engine.RecoveryFailureStartTimeout}) + a.OnProbeResult(probe) + if got := countStarts(exec, "StartCatchUp"); got != 2 { + t.Fatalf("one probe batch emitted duplicate recovery: starts=%d want initial+one retry", got) + } +} + +func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { + for _, n := range []int{8, 5} { + t.Run(string(rune('0'+n)), func(t *testing.T) { + a, exec, probe := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + if p := a.Projection(); p.Mode != engine.ModeHealthy { + t.Fatalf("precondition not healthy: %+v", p) + } + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { defer wg.Done(); <-start; a.OnProbeResult(probe) }() + } + close(start) + wg.Wait() + if got := countStarts(exec, "StartCatchUp"); got != 1 { + t.Fatalf("identical delayed probes restarted healthy recovery: starts=%d path=%v", got, a.CommandLog()) + } + if p := a.Projection(); p.Mode != engine.ModeHealthy { + t.Fatalf("old facts regressed healthy replica: %+v", p) + } + }) + } +} From 14d724e3de7b23948390a3387411598d58bcd6be Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:39:56 -0800 Subject: [PATCH 12/35] test: witness an admitted old wire frame overtaken by a newer session --- .../apply_gate_wire_overlap_test.go | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 seaweed-block/core/replication/apply_gate_wire_overlap_test.go diff --git a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go new file mode 100644 index 0000000000..e6a0040e50 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go @@ -0,0 +1,95 @@ +package replication + +import ( + "bytes" + "net" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type heldAdmittedRecovery struct { + *ReplicaApplyGate + entered, release chan struct{} + done chan error +} + +func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + if l.SessionID == 1 && lsn == 95 { + close(h.entered) + <-h.release + err := h.ReplicaApplyGate.ApplyRecovery(l, lba, data, lsn) + h.done <- err + return err + } + return h.ReplicaApplyGate.ApplyRecovery(l, lba, data, lsn) +} + +// An old frame can pass the listener's lineage check before a newer session +// advances that check, then reach the apply gate after the newer write. +func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { + store := storage.NewBlockStore(64, blockSize) + h := &heldAdmittedRecovery{ReplicaApplyGate: NewReplicaApplyGate(store), entered: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1)} + listener, err := transport.NewReplicaListenerWithApplyHook("127.0.0.1:0", store, h) + if err != nil { + t.Fatal(err) + } + listener.Serve() + var once sync.Once + release := func() { once.Do(func() { close(h.release) }) } + t.Cleanup(func() { release(); listener.Stop() }) + dial := func() net.Conn { + c, err := net.DialTimeout("tcp", listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + return c + } + send := func(c net.Conn, kind byte, payload []byte) { + if err := transport.WriteMsg(c, kind, payload); err != nil { + t.Fatal(err) + } + } + barrier := func(c net.Conn, l transport.RecoveryLineage) { + send(c, transport.MsgBarrierReq, transport.EncodeLineage(l)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + old, newer := recoveryLineage(1, 120), recoveryLineage(2, 120) + c1, c2 := dial(), dial() + send(c1, transport.MsgRecoveryLaneStart, transport.EncodeLineage(old)) + send(c1, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: old, LBA: 0, Data: makeData(1), LSN: 1})) + barrier(c1, old) // initialize the old session before the competing apply + send(c1, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: old, LBA: 5, Data: makeData(0xAA), LSN: 95})) + select { + case <-h.entered: + case <-time.After(3 * time.Second): + t.Fatal("old frame never reached post-admission hook") + } + send(c2, transport.MsgRecoveryLaneStart, transport.EncodeLineage(newer)) + want := bytes.Repeat([]byte{0xBB}, blockSize) + send(c2, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: newer, LBA: 5, Data: want, LSN: 120})) + barrier(c2, newer) + release() + select { + case err := <-h.done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("admitted old frame did not settle") + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("admitted old wire session regressed bytes: err=%v", err) + } +} From 056c80a957f143367d35a30e40f07528aa091fd8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:44:32 -0800 Subject: [PATCH 13/35] test: expose missing production replica apply-gate wiring --- .../replication_ingress_apply_test.go | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go new file mode 100644 index 0000000000..eb37cc413b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestReplicationIngressSharesApplyVersionsAcrossSessions(t *testing.T) { + store := storage.NewBlockStore(64, 4096) + r := newReplicationIngress(flags{dataAddr: "127.0.0.1:0", volumeID: "vol1"}, store) + if err := r.AdmitAsReplica(1); err != nil { + t.Fatal(err) + } + t.Cleanup(r.Stop) + want := bytes.Repeat([]byte{0xBB}, 4096) + ship := func(session, lsn uint64, data []byte, recovery bool) { + c, err := net.DialTimeout("tcp", r.listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + lineage := transport.RecoveryLineage{SessionID: session, Epoch: 1, EndpointVersion: 1, TargetLSN: 120} + send := func(kind byte, data []byte) { + if err := transport.WriteMsg(c, kind, data); err != nil { + t.Fatal(err) + } + } + if recovery { + send(transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)) + } + send(transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 5, Data: data, LSN: lsn})) + send(transport.MsgBarrierReq, transport.EncodeLineage(lineage)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + ship(1, 120, want, false) + ship(2, 95, bytes.Repeat([]byte{0xAA}, 4096), true) + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("production ingress allowed cross-session byte regression: err=%v", err) + } +} From 364118a28e77bd21f001bfc4b0c2c0796b5b8399 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 03:46:11 -0800 Subject: [PATCH 14/35] fix: deduplicate recovery observations and share replica apply versions --- .../cmd/blockvolume/replication_ingress.go | 8 ++- seaweed-block/core/adapter/adapter.go | 32 +++++----- seaweed-block/core/adapter/normalize.go | 22 +++---- .../core/adapter/recovery_dedup_test.go | 15 ++++- seaweed-block/core/calibration/scenarios.go | 32 +++++----- .../core/calibration/scenarios_test.go | 2 +- seaweed-block/core/engine/apply.go | 4 +- .../core/engine/recovery_probe_order_test.go | 28 +++++++++ seaweed-block/core/replication/apply_gate.go | 62 +++++++++---------- .../apply_gate_cross_session_test.go | 58 +++++++++++++++++ .../core/replication/apply_gate_test.go | 13 ++-- seaweed-block/core/transport/replica.go | 8 ++- seaweed-block/docs/design/block-design.md | 2 + seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/spec/README.md | 3 + seaweed-block/docs/spec/ReplicaApplyOrder.tla | 44 +++++++++++++ .../spec/cfg/R292_red_delayed_prepare.cfg | 5 ++ .../docs/spec/cfg/R292_red_probe_rollback.cfg | 5 ++ .../spec/cfg/R292_red_session_versions.cfg | 5 ++ seaweed-block/docs/spec/cfg/R292_safe.cfg | 5 ++ seaweed-block/docs/spec/run.sh | 1 + 21 files changed, 274 insertions(+), 86 deletions(-) create mode 100644 seaweed-block/core/engine/recovery_probe_order_test.go create mode 100644 seaweed-block/docs/spec/ReplicaApplyOrder.tla create mode 100644 seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg create mode 100644 seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg create mode 100644 seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg create mode 100644 seaweed-block/docs/spec/cfg/R292_safe.cfg diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 89ab03da31..5ecd7a8eec 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -18,6 +19,7 @@ type replicationIngress struct { mu sync.Mutex addr, volumeID, floorPath string store storage.LogicalStorage + applyGate *replication.ReplicaApplyGate dualLane bool // rf1Only, when set, refuses every role with replica slots with this reason // (walstore-chunk). The host latches the error: no role is adopted, not Healthy. @@ -86,8 +88,12 @@ func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { listener := r.listener fresh := listener == nil if fresh { + // One version map per replica store, surviving listener role transitions. + if r.applyGate == nil { + r.applyGate = replication.NewReplicaApplyGate(r.store) + } var err error - listener, err = transport.NewReplicaListenerWithFloor(r.addr, r.store, r.volumeID, r.floorPath) + listener, err = transport.NewReplicaListenerWithFloorAndApplyHook(r.addr, r.store, r.volumeID, r.floorPath, r.applyGate) if err != nil { return err } diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index bc79ef4505..9798315423 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -384,8 +384,9 @@ func (a *VolumeReplicaAdapter) applyBatchAndExecute(events []engine.Event, event log.EventKind = eventKind } - var cmds []engine.Command + var queued []queuedCommand for _, ev := range events { + var cmds []engine.Command result := engine.Apply(&a.state, ev) a.trace = append(a.trace, result.Trace...) log.Projection = result.Projection @@ -407,21 +408,22 @@ func (a *VolumeReplicaAdapter) applyBatchAndExecute(events []engine.Event, event log.Commands = append(log.Commands, kind) cmds = append(cmds, cmd) } - } - // Feed session lifecycle events back into engine while still under lock - // (these are synchronous, no external calls). - sessionEvents, queued := a.prepareQueuedCommands(cmds) - for _, sev := range sessionEvents { - sr := engine.Apply(&a.state, sev) - a.trace = append(a.trace, sr.Trace...) - log.Projection = sr.Projection - log.Trace = append(log.Trace, sr.Trace...) - for _, cmd := range sr.Commands { - kind := engine.CommandKind(cmd) - a.cmdLog = append(a.cmdLog, kind) - log.Commands = append(log.Commands, kind) - queued = append(queued, queuedCommand{cmd: cmd}) + // Reserve recovery before applying the next event in this observation. + // Otherwise both reachability and facts can emit a Start for an idle slot. + sessionEvents, prepared := a.prepareQueuedCommands(cmds) + queued = append(queued, prepared...) + for _, sev := range sessionEvents { + sr := engine.Apply(&a.state, sev) + a.trace = append(a.trace, sr.Trace...) + log.Projection = sr.Projection + log.Trace = append(log.Trace, sr.Trace...) + for _, cmd := range sr.Commands { + kind := engine.CommandKind(cmd) + a.cmdLog = append(a.cmdLog, kind) + log.Commands = append(log.Commands, kind) + queued = append(queued, queuedCommand{cmd: cmd}) + } } } a.mu.Unlock() diff --git a/seaweed-block/core/adapter/normalize.go b/seaweed-block/core/adapter/normalize.go index 341a2ce314..082ab4e768 100644 --- a/seaweed-block/core/adapter/normalize.go +++ b/seaweed-block/core/adapter/normalize.go @@ -111,8 +111,11 @@ func NormalizeAssignment(a AssignmentInfo) engine.Event { // NormalizeProbe converts a probe result into engine events. // A successful probe produces up to 2 events: -// 1. ProbeSucceeded (reachability) -// 2. RecoveryFactsObserved (R/S/H boundaries) +// 1. RecoveryFactsObserved (R/S/H boundaries) +// 2. ProbeSucceeded (reachability) +// +// Fresh boundaries precede reachability so its decision cannot reserve a +// recovery using the previous probe's retention window. // // A failed probe produces 1 event: // 1. ProbeFailed @@ -132,6 +135,12 @@ func NormalizeProbe(p ProbeResult) []engine.Event { } events := []engine.Event{ + engine.RecoveryFactsObserved{ + ReplicaID: p.ReplicaID, + EndpointVersion: p.EndpointVersion, + TransportEpoch: p.TransportEpoch, + R: p.ReplicaFlushedLSN, S: p.PrimaryTailLSN, H: p.PrimaryHeadLSN, + }, engine.ProbeSucceeded{ ReplicaID: p.ReplicaID, EndpointVersion: p.EndpointVersion, @@ -139,15 +148,6 @@ func NormalizeProbe(p ProbeResult) []engine.Event { }, } - events = append(events, engine.RecoveryFactsObserved{ - ReplicaID: p.ReplicaID, - EndpointVersion: p.EndpointVersion, - TransportEpoch: p.TransportEpoch, - R: p.ReplicaFlushedLSN, - S: p.PrimaryTailLSN, - H: p.PrimaryHeadLSN, - }) - return events } diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index 86ed57f6ed..f195941461 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -1,6 +1,7 @@ package adapter import ( + "strconv" "sync" "testing" @@ -20,7 +21,7 @@ func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResu ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} a.OnProbeResult(probe) t.Cleanup(func() { - a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: max(exec.latestSessionID("StartCatchUp"), exec.latestSessionID("StartRebuild")), Success: true, AchievedLSN: 100}) }) return a, exec, probe } @@ -37,9 +38,19 @@ func TestAdapter_OneRecoveryPreparedWithinProbeBatch(t *testing.T) { } } +func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { + a, exec, probe := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), FailureKind: engine.RecoveryFailureStartTimeout}) + probe.PrimaryTailLSN = 60 // the former catch-up prefix is now recycled + a.OnProbeResult(probe) + if catchup, rebuild := countStarts(exec, "StartCatchUp"), countStarts(exec, "StartRebuild"); catchup != 1 || rebuild != 1 { + t.Fatalf("probe reserved recovery from stale bounds: catchup=%d rebuild=%d", catchup, rebuild) + } +} + func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { for _, n := range []int{8, 5} { - t.Run(string(rune('0'+n)), func(t *testing.T) { + t.Run(strconv.Itoa(n), func(t *testing.T) { a, exec, probe := dedupAdapter(t) a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) diff --git a/seaweed-block/core/calibration/scenarios.go b/seaweed-block/core/calibration/scenarios.go index 1b69b5378f..94c364e74c 100644 --- a/seaweed-block/core/calibration/scenarios.go +++ b/seaweed-block/core/calibration/scenarios.go @@ -1,6 +1,7 @@ package calibration import ( + "fmt" "strings" "time" @@ -302,6 +303,7 @@ func (*scenarioC5OrderStable) Expect() Expected { DataIntegrityExpected: true, } } + // perturbation is one of the concrete interleaving patterns C5 runs. // Each produces the SAME underlying facts on the SAME replica (r1) // but delivers events to the adapter in a different order, timing, or @@ -324,11 +326,11 @@ func (*scenarioC5OrderStable) Expect() Expected { type perturbation int const ( - pertBaseline perturbation = iota // assign + wait - pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives - pertPreAssignStorm // 8 concurrent pre-assign probes, then assign - pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent) - pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait + pertBaseline perturbation = iota // assign + wait + pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives + pertPreAssignStorm // 8 concurrent pre-assign probes, then assign + pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent) + pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait ) func (*scenarioC5OrderStable) Run() (Observed, error) { @@ -345,6 +347,7 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { sameDecision := true sameFinalMode := true sameRecoverySig := true + var divergentPath []string sameCloseCount := true dataOK := true @@ -381,6 +384,9 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { } if sig != firstSig { sameRecoverySig = false + if divergentPath == nil { + divergentPath = append([]string{fmt.Sprintf("perturbation=%d baseline=%v", p, first.CommandPath)}, obs.CommandPath...) + } } if obs.CloseEventCount != first.CloseEventCount { sameCloseCount = false @@ -401,10 +407,9 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { } if !sameRecoverySig { // Pollute the command path marker so the reader cannot miss - // that the recovery signature drifted. The baseline first-run - // path is preserved alongside the marker so divergence-log - // authors can still see what the first run looked like. - out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, first.CommandPath...) + // that the recovery signature drifted. Preserve the actual divergent + // perturbation and path alongside the baseline. + out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, divergentPath...) } if !sameCloseCount { // Set CloseEventCount to a negative sentinel so the JSON @@ -446,13 +451,8 @@ func extractRecoverySignature(path []string) recoverySignature { // R/S/H); only the delivery shape — timing, ordering, concurrency, // assignment idempotence — varies. // -// All post-assignment probe variations are deliberately omitted: a -// probe fired with pre-captured facts after the engine has converged -// would deliver STALE R to the engine and legitimately trigger -// re-recovery. Treating that as a C5 failure would conflate engine -// correctness with A1/A4. Treating it as a C5 success would require -// gating the engine's fact-processing, which is a route change that -// belongs outside Phase 06. +// Delayed same-identity probes cannot lower completed durable R; the +// concurrent variants exercise both pending and post-completion delivery. func applyPerturbation(h *harness, p perturbation) { _, _, pH := h.primaryStore.Boundaries() rR, rS, _ := h.replicaStore.Boundaries() diff --git a/seaweed-block/core/calibration/scenarios_test.go b/seaweed-block/core/calibration/scenarios_test.go index 6ea75164a2..0ad50a4fc9 100644 --- a/seaweed-block/core/calibration/scenarios_test.go +++ b/seaweed-block/core/calibration/scenarios_test.go @@ -124,7 +124,7 @@ func TestC5_OrderStableAcrossRuns(t *testing.T) { // Recovery-signature divergence is signaled by a sentinel element // prepended to CommandPath. The scenario run must not hit this. if len(obs.CommandPath) > 0 && obs.CommandPath[0] == "DIVERGED_ACROSS_RUNS_RECOVERY_SIG" { - t.Fatalf("C5: recovery signature drifted across runs; first-run path=%v", obs.CommandPath[1:]) + t.Fatalf("C5: recovery signature drifted across runs; divergent perturbation/path=%v", obs.CommandPath[1:]) } // CloseEventCount sentinel: negative is used to flag cross-run // drift in the number of SessionClosedCompleted events. A legit diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 9616689808..161ff88729 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -295,7 +295,9 @@ func applyRecoveryFacts(st *ReplicaState, e RecoveryFactsObserved, r *ApplyResul trace("stale_recovery_facts", reason) return } - st.Recovery.R = e.R + // Within one identity, delayed probes cannot undo completed durable work. + // An identity-changing assignment resets the recovery facts. + st.Recovery.R = max(st.Recovery.R, e.R) st.Recovery.S = e.S st.Recovery.H = e.H diff --git a/seaweed-block/core/engine/recovery_probe_order_test.go b/seaweed-block/core/engine/recovery_probe_order_test.go new file mode 100644 index 0000000000..011329815b --- /dev/null +++ b/seaweed-block/core/engine/recovery_probe_order_test.go @@ -0,0 +1,28 @@ +package engine + +import "testing" + +func TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity(t *testing.T) { + st := &ReplicaState{} + assignAndProbe(st) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100}) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + assertNoCommand(t, r, "StartCatchUp") + if st.Recovery.R != 100 { + t.Fatalf("old probe lowered completed R: %d", st.Recovery.R) + } + // A higher primary head remains real new work, starting after durable R. + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 150}) + start := findStartCatchUp(t, r.Commands) + if start.FromLSN != 101 || start.EffectiveFrontierHint() != 150 { + t.Fatalf("new work lost or replayed completed prefix: %+v", start) + } + // Replacement identity must not inherit the old replica's progress floor. + Apply(st, AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 2}) + Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2}) + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2, R: 0, S: 10, H: 150}) + assertHasCommand(t, r, "StartRebuild") +} diff --git a/seaweed-block/core/replication/apply_gate.go b/seaweed-block/core/replication/apply_gate.go index 368df4e62c..0adb09402c 100644 --- a/seaweed-block/core/replication/apply_gate.go +++ b/seaweed-block/core/replication/apply_gate.go @@ -52,8 +52,8 @@ import ( // Per-LBA applied LSN source (Option C hybrid, kickoff §2.5 #1): // at session init, query `store.AppliedLSNs()` for substrate- // reported per-LBA latest-applied-LSN seed; substrates returning -// `ErrAppliedLSNsNotTracked` (BlockStore) fall back to session-only -// tracking, seeded from live + recovery applies during the session. +// `ErrAppliedLSNsNotTracked` (BlockStore) fall back to replica-lifetime +// tracking, seeded from live + recovery applies across sessions. // // Pinned invariants (T4d mini-plan §4 #6): // - INV-REPL-NO-PER-LBA-DATA-REGRESSION (goal-level) @@ -65,20 +65,17 @@ import ( type ReplicaApplyGate struct { store storage.LogicalStorage - mu sync.Mutex - sessions map[uint64]*applyGateSession // keyed by lineage.SessionID + mu sync.Mutex + sessions map[uint64]*applyGateSession // keyed by lineage.SessionID + appliedLSN map[uint32]uint64 // replica-wide, shared by every lane and session } // applyGateSession is the per-recovery-session state. Per round-44 // 2-map split: liveTouched + recoveryCovered are distinct because // the same physical LBA can appear in both (live lane wrote it AND -// recovery lane saw it during the session). appliedLSN is the -// stale-skip discriminator. +// recovery lane saw it during the session). The stale-skip discriminator +// is replica-wide and survives CloseSession. type applyGateSession struct { - // appliedLSN: highest LSN successfully applied to each LBA - // (across both lanes). The stale-skip discriminator. - appliedLSN map[uint32]uint64 - // liveTouched: LBAs the live lane wrote during this session. // Recovery must yield to these (live-wins via per-LBA LSN check). liveTouched map[uint32]bool @@ -93,13 +90,14 @@ type applyGateSession struct { // // Called by: replica-side wiring code that constructs the // `transport.ReplicaListener` with an `ApplyHook` option. -// Owns: per-session state maps; substrate query at session init. +// Owns: per-session coverage, replica-wide applied LSNs; substrate seed queries. // Borrows: store handle (caller retains; gate calls ApplyEntry + // AppliedLSNs through the interface). func NewReplicaApplyGate(store storage.LogicalStorage) *ReplicaApplyGate { return &ReplicaApplyGate{ - store: store, - sessions: make(map[uint64]*applyGateSession), + store: store, + sessions: make(map[uint64]*applyGateSession), + appliedLSN: make(map[uint32]uint64), } } @@ -167,7 +165,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat g.mu.Lock() defer g.mu.Unlock() - if existing, ok := sess.appliedLSN[lba]; ok && lsn <= existing { + if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { // Stale: skip data write but ADVANCE recoveryCovered. sess.recoveryCovered[lba] = true return nil @@ -176,7 +174,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat if err := g.store.ApplyEntry(lba, data, lsn); err != nil { return fmt.Errorf("apply gate: recovery substrate.ApplyEntry lba=%d lsn=%d: %w", lba, lsn, err) } - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = lsn sess.recoveryCovered[lba] = true return nil } @@ -192,7 +190,7 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] g.mu.Lock() defer g.mu.Unlock() - if existing, ok := sess.appliedLSN[lba]; ok && lsn <= existing { + if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { // Stale: fail-loud. Caller logs + drops conn. return fmt.Errorf("apply gate: live-lane stale entry lba=%d lsn=%d <= applied=%d (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD)", lba, lsn, existing) @@ -202,17 +200,17 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] if err := g.store.ApplyEntry(lba, data, lsn); err != nil { return fmt.Errorf("apply gate: live substrate.ApplyEntry lba=%d lsn=%d: %w", lba, lsn, err) } - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = lsn sess.liveTouched[lba] = true return nil } // initSessionLocked builds a fresh session state. Called with g.mu -// held. Seeds appliedLSN from substrate AppliedLSNs() (Option C -// hybrid); falls back to empty map on `ErrAppliedLSNsNotTracked`. +// held. Merge substrate seeds into the replica-wide map without lowering +// LSNs already applied by another lane or session. Untracked substrates +// retain the gate's replica-lifetime history. func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession { sess := &applyGateSession{ - appliedLSN: make(map[uint32]uint64), liveTouched: make(map[uint32]bool), recoveryCovered: make(map[uint32]bool), } @@ -220,21 +218,21 @@ func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession if err != nil { // ErrAppliedLSNsNotTracked is the documented sentinel (Option // C hybrid). Anything else is an unexpected substrate error; - // log and proceed with empty map (gate's session-only - // tracking will fill in via subsequent applies). - log.Printf("apply gate: session %d substrate AppliedLSNs unavailable (%v); falling back to session-only tracking", sessionID, err) + // log and retain the replica-lifetime map; subsequent applies + // extend it only after the physical write succeeds. + log.Printf("apply gate: session %d substrate AppliedLSNs unavailable (%v); retaining replica-lifetime tracking", sessionID, err) return sess } for lba, lsn := range seed { - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) } return sess } // CloseSession clears per-session state. Called by replica-side // wiring on session teardown (lineage advance to a new session, -// peer disconnect, etc.). Optional — leaving stale sessions in the -// map costs memory but doesn't affect correctness for fresh sessions. +// peer disconnect, etc.). Only coverage is released: the replica-wide +// applied-LSN map must survive session teardown. // // Called by: replica-side session-lifecycle hook (post-T4d-2: the // existing acceptMutationLineage advance path is the natural close @@ -246,7 +244,7 @@ func (g *ReplicaApplyGate) CloseSession(sessionID uint64) { g.mu.Unlock() } -// SessionState exposes per-session state for assertion-only +// SessionState exposes replica-wide version count and per-session coverage for assertion-only // inspection in tests + diagnostics. Returns a snapshot; caller- // owned (mutation does not affect gate state). // @@ -258,7 +256,7 @@ func (g *ReplicaApplyGate) SessionState(sessionID uint64) (appliedLSN, liveTouch if !ok { return 0, 0, 0, false } - return len(sess.appliedLSN), len(sess.liveTouched), len(sess.recoveryCovered), true + return len(g.appliedLSN), len(sess.liveTouched), len(sess.recoveryCovered), true } // SessionRecoveryCoverage returns true iff the given LBA was @@ -276,17 +274,17 @@ func (g *ReplicaApplyGate) SessionRecoveryCoverage(sessionID uint64, lba uint32) return sess.recoveryCovered[lba] } -// SessionAppliedLSN returns the gate's tracked applied LSN for an -// LBA in this session. Returns 0 + false if not tracked. +// SessionAppliedLSN returns the replica-wide applied LSN visible to a +// registered session. Returns 0 + false if either is not tracked. // // Called by: tests pinning per-LBA stale-skip discrimination. func (g *ReplicaApplyGate) SessionAppliedLSN(sessionID uint64, lba uint32) (uint64, bool) { g.mu.Lock() defer g.mu.Unlock() - sess, ok := g.sessions[sessionID] + _, ok := g.sessions[sessionID] if !ok { return 0, false } - lsn, present := sess.appliedLSN[lba] + lsn, present := g.appliedLSN[lba] return lsn, present } diff --git a/seaweed-block/core/replication/apply_gate_cross_session_test.go b/seaweed-block/core/replication/apply_gate_cross_session_test.go index 15570d87e8..fdecae23d5 100644 --- a/seaweed-block/core/replication/apply_gate_cross_session_test.go +++ b/seaweed-block/core/replication/apply_gate_cross_session_test.go @@ -2,7 +2,10 @@ package replication import ( "bytes" + "errors" "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" ) // Both sessions are initialized before either writes the contested LBA. @@ -46,3 +49,58 @@ func TestApplyGate_OverlappingSessionsNeverRegressBytes(t *testing.T) { }) } } + +func TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion(t *testing.T) { + store := &fakeStoreWithSeed{BlockStore: storage.NewBlockStore(64, blockSize), seed: map[uint32]uint64{5: 1}} + gate := NewReplicaApplyGate(store) + want := bytes.Repeat([]byte{0xBB}, blockSize) + if err := gate.ApplyLive(liveLineage(1), 5, want, 120); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if _, _, _, found := gate.SessionState(1); found { + t.Fatal("closed session coverage retained") + } + if err := gate.ApplyRecovery(recoveryLineage(2, 120), 5, makeData(0xAA), 95); err != nil { + t.Fatal(err) + } + if err := gate.ApplyLive(liveLineage(3), 5, makeData(0xCC), 100); err == nil { + t.Fatal("cross-session stale live write was accepted") + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("teardown/reseed regressed replica bytes: err=%v", err) + } + if !gate.SessionRecoveryCoverage(2, 5) || gate.SessionRecoveryCoverage(3, 5) { + t.Fatal("stale skip/fail mixed lane coverage") + } +} + +type failOnceApplyStore struct { + *storage.BlockStore + fail bool +} + +func (s *failOnceApplyStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { + if s.fail { + s.fail = false + return errSubstrateBoom + } + return s.BlockStore.ApplyEntry(lba, data, lsn) +} + +func TestApplyGate_FailedWriteDoesNotPublishReplicaVersion(t *testing.T) { + store := &failOnceApplyStore{BlockStore: storage.NewBlockStore(64, blockSize), fail: true} + gate := NewReplicaApplyGate(store) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); !errors.Is(err, errSubstrateBoom) { + t.Fatalf("physical error lost: %v", err) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(2, 120), 5, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("failed write falsely blocked recovery: err=%v", err) + } +} diff --git a/seaweed-block/core/replication/apply_gate_test.go b/seaweed-block/core/replication/apply_gate_test.go index 7179d26bd9..b629eb0b68 100644 --- a/seaweed-block/core/replication/apply_gate_test.go +++ b/seaweed-block/core/replication/apply_gate_test.go @@ -230,18 +230,21 @@ func TestApplyGate_LiveLane_StaleEntry_DoesNotAdvanceRecoveryCovered(t *testing. // --- Lane independence: two sessions, different lanes --- -func TestApplyGate_LiveAndRecovery_DistinctSessions_Independent(t *testing.T) { +func TestApplyGate_LiveAndRecovery_DistinctCoverageSharedVersion(t *testing.T) { gate, _ := newGate(t) live := liveLineage(50) recov := recoveryLineage(7, 100) gate.ApplyLive(live, 5, makeData(0xBB), 100) - gate.ApplyRecovery(recov, 5, makeData(0xAA), 30) // recovery sees its own session + gate.ApplyRecovery(recov, 5, makeData(0xAA), 30) // stale across sessions - // Recovery session sees its own appliedLSN (just set: 30). + // Both sessions see the replica-wide version, with separate coverage. lsn, ok := gate.SessionAppliedLSN(7, 5) - if !ok || lsn != 30 { - t.Errorf("recovery session appliedLSN[5] = (%d, %v), want (30, true)", lsn, ok) + if !ok || lsn != 100 { + t.Errorf("recovery appliedLSN[5] = (%d, %v), want (100, true)", lsn, ok) + } + if !gate.SessionRecoveryCoverage(7, 5) || gate.SessionRecoveryCoverage(50, 5) { + t.Fatal("cross-session version sharing mixed recovery coverage") } // Live session sees its own appliedLSN (set: 100). diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 204709474a..13fec7a963 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -104,6 +104,12 @@ func NewReplicaListener(addr string, store storage.LogicalStorage) (*ReplicaList // it takes effect; a missing or invalid record refuses construction. An // empty floorPath (non-durable memback) keeps the floor in memory. func NewReplicaListenerWithFloor(addr string, store storage.LogicalStorage, volumeID, floorPath string) (*ReplicaListener, error) { + return NewReplicaListenerWithFloorAndApplyHook(addr, store, volumeID, floorPath, nil) +} + +// NewReplicaListenerWithFloorAndApplyHook preserves role and durable-floor +// admission while using the volume's shared apply ordering gate. +func NewReplicaListenerWithFloorAndApplyHook(addr string, store storage.LogicalStorage, volumeID, floorPath string, hook ApplyHook) (*ReplicaListener, error) { var floor uint64 if floorPath != "" { var err error @@ -111,7 +117,7 @@ func NewReplicaListenerWithFloor(addr string, store storage.LogicalStorage, volu return nil, err } } - r, err := NewReplicaListenerWithApplyHook(addr, store, nil) + r, err := NewReplicaListenerWithApplyHook(addr, store, hook) if err != nil { return nil, err } diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index dae9c48a72..41a572dd55 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -297,6 +297,8 @@ stateDiagram-v2 Unknown --> Healthy: probe and barrier succeed Healthy --> Degraded: barrier or ship failure Degraded --> CatchingUp: gap within the primary's WAL + CatchingUp --> CatchingUp: identical recovery facts retain the prepared session + Healthy --> Healthy: delayed probe retains completed durable R CatchingUp --> Healthy: caught up to the target CatchingUp --> Degraded: catch-up fails Degraded --> Healthy: recovers diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 244ff464cd..57d5a0fcb7 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -127,12 +127,16 @@ stateDiagram-v2 | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | +**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. + **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| | `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each probe observation reserves at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | +| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion` | `ReplicaApplyOrder` NoRegression | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | | `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 98c2c668f4..5e92eb1847 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -317,3 +317,6 @@ end-to-end wall-clock latency guarantee. Keep long model runs off tp04. `HostBudget.tla` abstracts cooperating process slots, COW reservation and joined release. Config `HostBudget.cfg` checks three owners/two slots; `HostBudget_early_release.cfg` must violate HeldUntilJoined. It excludes degraded static fallback and does not prove filesystem locks, rates or physical-I/O deadlines. Native subprocess tests cover lock lifetime. HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. +## Replica apply ordering + +`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression` and `NoDuplicateRecovery`; the three `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. diff --git a/seaweed-block/docs/spec/ReplicaApplyOrder.tla b/seaweed-block/docs/spec/ReplicaApplyOrder.tla new file mode 100644 index 0000000000..f277cbd544 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaApplyOrder.tla @@ -0,0 +1,44 @@ +------------------------- MODULE ReplicaApplyOrder ------------------------- +EXTENDS Integers, TLC + +\* Two admitted sessions, one LBA, three versions. Bytes are represented by +\* their LSN. Storage faults, restart persistence and authority are external +\* obligations; this model checks successful apply ordering and probe dedupe. +CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts +VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR +vars == <> +Max(a,b) == IF a > b THEN a ELSE b +Init == /\ applied = 0 /\ local = [s \in 1..2 |-> 0] + /\ bytes = 0 /\ seen = 0 /\ stage = 0 + /\ active = FALSE /\ starts = 0 /\ replicaR = 0 + +\* One shared mutex covers stale check, physical apply and version publication. +Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] + IN /\ bytes' = IF n > floor THEN n ELSE bytes + /\ applied' = Max(applied,n) + /\ local' = [local EXCEPT ![s] = Max(@,n)] + /\ seen' = Max(seen,n) + /\ UNCHANGED <> + +\* A probe's two semantic events must observe the same reserved session. +FirstEvent == /\ stage = 0 /\ stage' = 1 /\ starts' = 1 + /\ active' = PrepareEachEvent + /\ UNCHANGED <> +SecondEvent == /\ stage = 1 /\ stage' = 2 + /\ starts' = IF active THEN starts ELSE starts + 1 + /\ active' = TRUE + /\ UNCHANGED <> +Complete == /\ stage = 2 /\ stage' = 3 /\ replicaR' = 3 + /\ active' = FALSE + /\ UNCHANGED <> +DelayedProbe == /\ stage = 3 /\ stage' = 4 + /\ replicaR' = IF MonotoneFacts THEN replicaR ELSE 1 + /\ starts' = IF replicaR' < 3 THEN starts + 1 ELSE starts + /\ active' = (replicaR' < 3) + /\ UNCHANGED <> +Next == (\E s \in 1..2, n \in 1..3 : Apply(s,n)) + \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe +Spec == Init /\ [][Next]_vars +NoRegression == bytes = seen +NoDuplicateRecovery == starts <= 1 +============================================================================= diff --git a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg new file mode 100644 index 0000000000..a8d99dad2a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = FALSE + MonotoneFacts = TRUE +INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg new file mode 100644 index 0000000000..b01f07b424 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = FALSE +INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg new file mode 100644 index 0000000000..efc9f01d4c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = FALSE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE +INVARIANT NoRegression diff --git a/seaweed-block/docs/spec/cfg/R292_safe.cfg b/seaweed-block/docs/spec/cfg/R292_safe.cfg new file mode 100644 index 0000000000..d631657e24 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_safe.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE +INVARIANTS NoRegression NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 05391d8a5e..4bfc7d0b46 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,7 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; S9_*) spec=RetentionGCTiming ;; *) echo "run.sh: no spec for config '$cfg'" >&2; exit 2 ;; From 68da02fb5f019ec798fea030ba8f9f9a3356cd86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:00:32 -0800 Subject: [PATCH 15/35] fix: preserve missing probe confidence with retained durable progress --- seaweed-block/core/engine/apply.go | 11 ++++++++ .../core/engine/recovery_probe_order_test.go | 15 ++++++++++ seaweed-block/core/engine/state.go | 3 ++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/README.md | 2 +- seaweed-block/docs/spec/ReplicaApplyOrder.tla | 28 +++++++++++++------ .../spec/cfg/R292_red_delayed_prepare.cfg | 1 + .../docs/spec/cfg/R292_red_probe_rollback.cfg | 1 + .../spec/cfg/R292_red_session_versions.cfg | 1 + .../spec/cfg/R292_red_unknown_confidence.cfg | 6 ++++ seaweed-block/docs/spec/cfg/R292_safe.cfg | 3 +- 11 files changed, 61 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 161ff88729..6d1af8d7ec 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -298,6 +298,7 @@ func applyRecoveryFacts(st *ReplicaState, e RecoveryFactsObserved, r *ApplyResul // Within one identity, delayed probes cannot undo completed durable work. // An identity-changing assignment resets the recovery facts. st.Recovery.R = max(st.Recovery.R, e.R) + st.Recovery.FactsMissing = !e.ProgressFact().PrimaryBoundsKnown st.Recovery.S = e.S st.Recovery.H = e.H @@ -311,6 +312,10 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra return } fact := e.ProgressFact() + if st.Recovery.FactsMissing { + st.Recovery.S, st.Recovery.H = fact.PrimaryS, fact.PrimaryH + st.Recovery.FactsMissing = false + } updateDurableAckLagState(st, fact) if fact.ReplicaR > st.Recovery.DurableAckR || !st.Recovery.DurableAckKnown { st.Recovery.DurableAckR = fact.ReplicaR @@ -443,6 +448,12 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { trace("decision", "unknown (not reachable)") return } + if st.Recovery.FactsMissing { + st.Recovery.Decision = DecisionUnknown + st.Recovery.DecisionReason = "no_boundaries" + trace("decision", "unknown (missing probe facts)") + return + } fact := RecoveryFactsObserved{ ReplicaID: st.Identity.ReplicaID, diff --git a/seaweed-block/core/engine/recovery_probe_order_test.go b/seaweed-block/core/engine/recovery_probe_order_test.go index 011329815b..15908d0687 100644 --- a/seaweed-block/core/engine/recovery_probe_order_test.go +++ b/seaweed-block/core/engine/recovery_probe_order_test.go @@ -14,6 +14,21 @@ func TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity(t *testing.T) { if st.Recovery.R != 100 { t.Fatalf("old probe lowered completed R: %d", st.Recovery.R) } + // An unknown probe must not turn the retained R into invented primary + // boundaries or publish healthy. A later valid observation recovers it. + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + if r.Projection.RecoveryDecision != DecisionUnknown { + t.Fatalf("retained R fabricated known boundaries: %+v", r.Projection) + } + r = Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + if r.Projection.RecoveryDecision != DecisionUnknown { + t.Fatal("reachability fabricated missing recovery facts") + } + assertNoCommand(t, r, "PublishHealthy") + r = Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + if r.Projection.RecoveryDecision != DecisionNone || st.Recovery.FactsMissing { + t.Fatalf("valid ack did not restore known facts: %+v", r.Projection) + } // A higher primary head remains real new work, starting after durable R. r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 150}) start := findStartCatchUp(t, r.Commands) diff --git a/seaweed-block/core/engine/state.go b/seaweed-block/core/engine/state.go index bd90e8847a..c92f15734c 100644 --- a/seaweed-block/core/engine/state.go +++ b/seaweed-block/core/engine/state.go @@ -82,6 +82,9 @@ const ( // RecoveryTruth: what recovery is needed. Authority: primary. type RecoveryTruth struct { + // FactsMissing preserves an all-zero probe's unknown confidence even + // while R retains already-confirmed durable progress. + FactsMissing bool R uint64 // replica durable/achieved boundary S uint64 // primary recoverable start boundary (WAL tail) H uint64 // primary target boundary (head) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 57d5a0fcb7..da54e306fe 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -127,7 +127,7 @@ stateDiagram-v2 | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | | Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | -**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. +**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R; missing probe boundaries remain unknown until a valid observation arrives. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 5e92eb1847..8190995f3e 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -319,4 +319,4 @@ end-to-end wall-clock latency guarantee. Keep long model runs off tp04. HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. ## Replica apply ordering -`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression` and `NoDuplicateRecovery`; the three `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. +`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression`, `NoDuplicateRecovery` and `NoFalseKnown`; the four `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. diff --git a/seaweed-block/docs/spec/ReplicaApplyOrder.tla b/seaweed-block/docs/spec/ReplicaApplyOrder.tla index f277cbd544..3ff2348cff 100644 --- a/seaweed-block/docs/spec/ReplicaApplyOrder.tla +++ b/seaweed-block/docs/spec/ReplicaApplyOrder.tla @@ -4,13 +4,14 @@ EXTENDS Integers, TLC \* Two admitted sessions, one LBA, three versions. Bytes are represented by \* their LSN. Storage faults, restart persistence and authority are external \* obligations; this model checks successful apply ordering and probe dedupe. -CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts -VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR -vars == <> +CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts, PreserveUnknownConfidence +VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR, factsKnown, knownDecision +vars == <> Max(a,b) == IF a > b THEN a ELSE b Init == /\ applied = 0 /\ local = [s \in 1..2 |-> 0] /\ bytes = 0 /\ seen = 0 /\ stage = 0 /\ active = FALSE /\ starts = 0 /\ replicaR = 0 + /\ factsKnown = TRUE /\ knownDecision = TRUE \* One shared mutex covers stale check, physical apply and version publication. Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] @@ -18,27 +19,36 @@ Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] /\ applied' = Max(applied,n) /\ local' = [local EXCEPT ![s] = Max(@,n)] /\ seen' = Max(seen,n) - /\ UNCHANGED <> + /\ UNCHANGED <> \* A probe's two semantic events must observe the same reserved session. FirstEvent == /\ stage = 0 /\ stage' = 1 /\ starts' = 1 /\ active' = PrepareEachEvent - /\ UNCHANGED <> + /\ UNCHANGED <> SecondEvent == /\ stage = 1 /\ stage' = 2 /\ starts' = IF active THEN starts ELSE starts + 1 /\ active' = TRUE - /\ UNCHANGED <> + /\ UNCHANGED <> Complete == /\ stage = 2 /\ stage' = 3 /\ replicaR' = 3 /\ active' = FALSE - /\ UNCHANGED <> + /\ UNCHANGED <> DelayedProbe == /\ stage = 3 /\ stage' = 4 /\ replicaR' = IF MonotoneFacts THEN replicaR ELSE 1 /\ starts' = IF replicaR' < 3 THEN starts + 1 ELSE starts /\ active' = (replicaR' < 3) - /\ UNCHANGED <> + /\ UNCHANGED <> +\* Retaining durable R does not give an all-zero probe known confidence. +MissingProbe == /\ stage = 3 /\ stage' = 5 + /\ factsKnown' = FALSE + /\ knownDecision' = ~PreserveUnknownConfidence + /\ UNCHANGED <> +FreshAck == /\ stage = 5 /\ stage' = 3 + /\ factsKnown' = TRUE /\ knownDecision' = TRUE + /\ UNCHANGED <> Next == (\E s \in 1..2, n \in 1..3 : Apply(s,n)) - \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe + \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe \/ MissingProbe \/ FreshAck Spec == Init /\ [][Next]_vars NoRegression == bytes = seen NoDuplicateRecovery == starts <= 1 +NoFalseKnown == ~factsKnown => ~knownDecision ============================================================================= diff --git a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg index a8d99dad2a..c2893f1af0 100644 --- a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg +++ b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = TRUE PrepareEachEvent = FALSE MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg index b01f07b424..662b75c378 100644 --- a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg +++ b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = TRUE PrepareEachEvent = TRUE MonotoneFacts = FALSE + PreserveUnknownConfidence = TRUE INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg index efc9f01d4c..e457c7f536 100644 --- a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg +++ b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = FALSE PrepareEachEvent = TRUE MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE INVARIANT NoRegression diff --git a/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg b/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg new file mode 100644 index 0000000000..762579b7e0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE + PreserveUnknownConfidence = FALSE +INVARIANT NoFalseKnown diff --git a/seaweed-block/docs/spec/cfg/R292_safe.cfg b/seaweed-block/docs/spec/cfg/R292_safe.cfg index d631657e24..47c0f9fd2f 100644 --- a/seaweed-block/docs/spec/cfg/R292_safe.cfg +++ b/seaweed-block/docs/spec/cfg/R292_safe.cfg @@ -2,4 +2,5 @@ SPECIFICATION Spec CONSTANTS SharedVersions = TRUE PrepareEachEvent = TRUE MonotoneFacts = TRUE -INVARIANTS NoRegression NoDuplicateRecovery + PreserveUnknownConfidence = TRUE +INVARIANTS NoRegression NoDuplicateRecovery NoFalseKnown From 4987a49d31114448acdcb10b426020fd8366024b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:22:08 -0800 Subject: [PATCH 16/35] fix: emit one recovery action per post-close durable acknowledgement --- seaweed-block/core/adapter/recovery_dedup_test.go | 15 +++++++++++++++ seaweed-block/core/engine/apply.go | 2 ++ seaweed-block/docs/design/invariants.md | 2 +- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index f195941461..6005fad58d 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -48,6 +48,21 @@ func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { } } +func TestAdapter_OneRecoveryFromPostCloseStalledAck(t *testing.T) { + a, exec, _ := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + for i := 0; i < 8; i++ { + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: uint64(200 + i)}) + if got := countStarts(exec, "StartCatchUp"); got > 1 { + if got != 2 { + t.Fatalf("one stalled ack emitted duplicate recovery: starts=%d", got) + } + return + } + } + t.Fatal("stalled ack never requested legitimate new recovery") +} + func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { for _, n := range []int{8, 5} { t.Run(strconv.Itoa(n), func(t *testing.T) { diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 6d1af8d7ec..b15c1c520f 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -354,6 +354,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra TargetLSN: fact.PrimaryH, }) trace("command", "StartCatchUp (durable ack stalled)") + return // this observation already selected and emitted its recovery } if lag == LagDecisionStartRebuild && canEmitRecoveryFromDurableAck(st) { st.Recovery.R = st.Recovery.DurableAckR @@ -369,6 +370,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra TargetLSN: fact.PrimaryH, }) trace("command", "StartRebuild (durable ack below retention)") + return // do not emit a second recovery through post-close decide } if st.Recovery.PostCloseDurableAckKnown { decide(st, r, trace) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index da54e306fe..afe5586a3a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -134,7 +134,7 @@ stateDiagram-v2 | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| | `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each probe observation reserves at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | | `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion` | `ReplicaApplyOrder` NoRegression | ACTIVE | | `INV-REPL-CATCHUP-REBUILD-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | From 54c1c61156adfd09472345e0bc0b2b173c7ac38b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:23:24 -0800 Subject: [PATCH 17/35] test: cover both post-close recovery decisions and settle the latest session --- .../core/adapter/recovery_dedup_test.go | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index 6005fad58d..1fc3424f23 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -21,7 +21,15 @@ func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResu ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} a.OnProbeResult(probe) t.Cleanup(func() { - a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: max(exec.latestSessionID("StartCatchUp"), exec.latestSessionID("StartRebuild")), Success: true, AchievedLSN: 100}) + exec.mu.Lock() + var sid, target uint64 + for _, start := range exec.starts { + if start.sessionID > sid { + sid, target = start.sessionID, start.targetLSN + } + } + exec.mu.Unlock() + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: sid, Success: true, AchievedLSN: target}) }) return a, exec, probe } @@ -49,18 +57,26 @@ func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { } func TestAdapter_OneRecoveryFromPostCloseStalledAck(t *testing.T) { - a, exec, _ := dedupAdapter(t) - a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) - for i := 0; i < 8; i++ { - a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: uint64(200 + i)}) - if got := countStarts(exec, "StartCatchUp"); got > 1 { - if got != 2 { - t.Fatalf("one stalled ack emitted duplicate recovery: starts=%d", got) + for _, kind := range []string{"StartCatchUp", "StartRebuild"} { + t.Run(kind, func(t *testing.T) { + a, exec, _ := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + initial, tail := 1, uint64(10) + if kind == "StartRebuild" { + initial, tail = 0, 110 } - return - } + for i := 0; i < 8; i++ { + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: tail, PrimaryHeadLSN: uint64(200 + i)}) + if got := countStarts(exec, kind); got > initial { + if got != initial+1 { + t.Fatalf("one stalled ack emitted duplicate recovery: kind=%s starts=%d want=%d", kind, got, initial+1) + } + return + } + } + t.Fatal("stalled ack never requested legitimate new recovery") + }) } - t.Fatal("stalled ack never requested legitimate new recovery") } func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { From bc1b0fbaebee271adb99ac24e852d28c326ee68a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:42:38 -0800 Subject: [PATCH 18/35] test: expose replica version history growth and recovery holes --- .../core/replication/apply_gate_floor_test.go | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 seaweed-block/core/replication/apply_gate_floor_test.go diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go new file mode 100644 index 0000000000..0ed7074e65 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -0,0 +1,56 @@ +package replication + +import ( + "bytes" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A synced scalar maximum does not establish recovery coverage for other LBAs. +func TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if r, err := store.Sync(); err != nil || r != 120 { + t.Fatalf("sync: R=%d err=%v", r, err) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(2, 100), 6, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("synced maximum swallowed an uncovered recovery LBA: err=%v got=%x", err, got[:8]) + } +} + +// Each batch completes durability and closes coverage; retained version history +// should scale with the outstanding suffix, rather than all LBAs ever written. +func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { + const batch = 32 + store := storage.NewBlockStore(1025, 1) + gate := NewReplicaApplyGate(store) + for round := uint64(0); round < 32; round++ { + session := round + 1 + for j := uint64(0); j < batch; j++ { + lba := uint32(round*batch + j) + if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, uint64(lba)+1); err != nil { + t.Fatal(err) + } + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + // A subsequent apply provides a lazy-pruning opportunity. + if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, 2048+round); err != nil { + t.Fatal(err) + } + tracked, _, _, _ := gate.SessionState(session) + if tracked > batch+1 { + t.Fatalf("durable version history grew with historical LBAs: round=%d tracked=%d bound=%d", round, tracked, batch+1) + } + gate.CloseSession(session) + } +} From 0a95b53940c70309a36f261cf5dfab886ca6ddb9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:43:03 -0800 Subject: [PATCH 19/35] test: keep long-run source versions monotone --- seaweed-block/core/replication/apply_gate_floor_test.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go index 0ed7074e65..1ff083d333 100644 --- a/seaweed-block/core/replication/apply_gate_floor_test.go +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -32,11 +32,13 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { const batch = 32 store := storage.NewBlockStore(1025, 1) gate := NewReplicaApplyGate(store) + var lsn uint64 for round := uint64(0); round < 32; round++ { session := round + 1 for j := uint64(0); j < batch; j++ { lba := uint32(round*batch + j) - if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, uint64(lba)+1); err != nil { + lsn++ + if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, lsn); err != nil { t.Fatal(err) } } @@ -44,7 +46,8 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { t.Fatal(err) } // A subsequent apply provides a lazy-pruning opportunity. - if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, 2048+round); err != nil { + lsn++ + if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, lsn); err != nil { t.Fatal(err) } tracked, _, _, _ := gate.SessionState(session) From 28d3054de5ff7afa8b546a54746e4e1e7e5c6d88 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:44:54 -0800 Subject: [PATCH 20/35] test: preserve lane semantics after durable version pruning --- .../core/replication/apply_gate_floor_test.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go index 1ff083d333..a4f7d07a1f 100644 --- a/seaweed-block/core/replication/apply_gate_floor_test.go +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -57,3 +57,39 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { gate.CloseSession(session) } } + +func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { + gate, store := newGate(t) + want := makeData(0xBB) + for lba := uint32(0); lba < 32; lba++ { + if err := gate.ApplyLive(liveLineage(1), lba, want, uint64(lba)+1); err != nil { + t.Fatal(err) + } + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if err := gate.ApplyRecovery(recoveryLineage(2, 32), 5, makeData(0xAA), 1); err != nil { + t.Fatal(err) + } + if !gate.SessionRecoveryCoverage(2, 5) { + t.Fatal("pruned stale recovery did not cover its own session") + } + if err := gate.ApplyLive(liveLineage(3), 6, makeData(0xCC), 2); err == nil { + t.Fatal("pruned stale live write was accepted") + } + if gate.SessionRecoveryCoverage(3, 6) { + t.Fatal("stale live write advanced recovery coverage") + } + for _, lba := range []uint32{5, 6} { + got, err := store.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("pruned stale record changed LBA %d: err=%v", lba, err) + } + } + tracked, _, _, _ := gate.SessionState(2) + if tracked != 0 { + t.Fatalf("durable versions were not pruned: tracked=%d want=0", tracked) + } +} From 85bf19a8bb6d951a44ebd7038bf118b8ba557acb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:53:34 -0800 Subject: [PATCH 21/35] fix: prune replica versions only behind certified recovery prefixes --- seaweed-block/core/adapter/adapter.go | 5 + seaweed-block/core/adapter/executor.go | 6 + seaweed-block/core/engine/apply.go | 14 +- seaweed-block/core/engine/commands.go | 2 + .../core/engine/recovery_prefix_test.go | 25 ++++ seaweed-block/core/replication/apply_gate.go | 44 +++++- .../core/replication/apply_gate_floor_test.go | 52 +++++++- .../apply_gate_prefix_wire_test.go | 126 ++++++++++++++++++ seaweed-block/core/transport/executor.go | 29 ++++ seaweed-block/core/transport/protocol.go | 4 + seaweed-block/core/transport/replica.go | 31 ++++- 11 files changed, 330 insertions(+), 8 deletions(-) create mode 100644 seaweed-block/core/engine/recovery_prefix_test.go create mode 100644 seaweed-block/core/replication/apply_gate_prefix_wire_test.go diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index 9798315423..8994bc89ab 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -575,6 +575,11 @@ func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) { a.executor.InvalidateSession(c.ReplicaID, c.SessionID, c.Reason) case engine.PublishHealthy: + if c.CertifiedPrefix != 0 { + if publisher, ok := a.executor.(RecoveryPrefixPublisher); ok { + publisher.PublishRecoveryPrefix(c.ReplicaID, c.RecoverySessionID, c.Epoch, c.EndpointVersion, c.CertifiedPrefix) + } + } a.executor.PublishHealthy(c.ReplicaID) case engine.PublishDegraded: diff --git a/seaweed-block/core/adapter/executor.go b/seaweed-block/core/adapter/executor.go index 8807399726..ba6e284fea 100644 --- a/seaweed-block/core/adapter/executor.go +++ b/seaweed-block/core/adapter/executor.go @@ -163,3 +163,9 @@ type DurableAckResult struct { type DurableAckCallbackSetter interface { SetOnDurableAck(fn OnDurableAck) } + +// RecoveryPrefixPublisher forwards the engine's explicit completed-prefix +// certificate. Plain healthy/probe or storage Sync facts carry no certificate. +type RecoveryPrefixPublisher interface { + PublishRecoveryPrefix(replicaID string, sessionID, epoch, endpointVersion, prefix uint64) +} diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index b15c1c520f..643f4dbbfe 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -524,7 +524,19 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { } else if recoveredReplicaWaitingForPostCloseAck(st) { trace("publish_healthy_held", "waiting for post-close durable ack") } else { - r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID}) + healthy := PublishHealthy{ReplicaID: st.Identity.ReplicaID} + target := st.Session.FrontierHint + if target == 0 { + target = st.Session.TargetLSN + } + if st.Recovery.RecoveryWindowClosed && st.Recovery.PostCloseDurableAckKnown && + st.Session.Phase == PhaseCompleted && target > 0 && st.Session.AchievedLSN >= target { + healthy.RecoverySessionID = st.Session.SessionID + healthy.Epoch = st.Identity.Epoch + healthy.EndpointVersion = st.Identity.EndpointVersion + healthy.CertifiedPrefix = target + } + r.Commands = append(r.Commands, healthy) } } diff --git a/seaweed-block/core/engine/commands.go b/seaweed-block/core/engine/commands.go index 3d137a7a38..d8bcefcccc 100644 --- a/seaweed-block/core/engine/commands.go +++ b/seaweed-block/core/engine/commands.go @@ -106,6 +106,8 @@ func (FenceAtEpoch) commandKind() string { return "FenceAtEpoch" } // PublishHealthy: declare this replica healthy for external consumption. type PublishHealthy struct { ReplicaID string + // Zero unless this publication follows a successful recovery close at T. + RecoverySessionID, Epoch, EndpointVersion, CertifiedPrefix uint64 } func (PublishHealthy) commandKind() string { return "PublishHealthy" } diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go new file mode 100644 index 0000000000..464b8ea878 --- /dev/null +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -0,0 +1,25 @@ +package engine + +import "testing" + +func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { + st := helperPrime(t, 1, 1, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 8, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 8}) + result := Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 8, AchievedLSN: 100}) + for _, command := range result.Commands { + if _, ok := command.(PublishHealthy); ok { + t.Fatal("recovery close certified before post-close ack") + } + } + result = Apply(st, DurableAckObserved{ReplicaID: "r1", SessionID: 8, EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) + for _, command := range result.Commands { + if healthy, ok := command.(PublishHealthy); ok { + if healthy.CertifiedPrefix != 100 || healthy.RecoverySessionID != 8 || healthy.Epoch != 1 || healthy.EndpointVersion != 1 { + t.Fatalf("healthy publication lost exact completed target: %+v", healthy) + } + return + } + } + t.Fatal("post-close ack did not publish certified recovery prefix") +} diff --git a/seaweed-block/core/replication/apply_gate.go b/seaweed-block/core/replication/apply_gate.go index 0adb09402c..aa0fa64cd1 100644 --- a/seaweed-block/core/replication/apply_gate.go +++ b/seaweed-block/core/replication/apply_gate.go @@ -68,6 +68,7 @@ type ReplicaApplyGate struct { mu sync.Mutex sessions map[uint64]*applyGateSession // keyed by lineage.SessionID appliedLSN map[uint32]uint64 // replica-wide, shared by every lane and session + floorLSN uint64 // certified contiguous prefix; never inferred from synced maximum R } // applyGateSession is the per-recovery-session state. Per round-44 @@ -165,7 +166,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat g.mu.Lock() defer g.mu.Unlock() - if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { + if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing { // Stale: skip data write but ADVANCE recoveryCovered. sess.recoveryCovered[lba] = true return nil @@ -190,7 +191,7 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] g.mu.Lock() defer g.mu.Unlock() - if existing, ok := g.appliedLSN[lba]; ok && lsn <= existing { + if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing { // Stale: fail-loud. Caller logs + drops conn. return fmt.Errorf("apply gate: live-lane stale entry lba=%d lsn=%d <= applied=%d (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD)", lba, lsn, existing) @@ -224,7 +225,9 @@ func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession return sess } for lba, lsn := range seed { - g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) + if lsn > g.floorLSN { + g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) + } } return sess } @@ -288,3 +291,38 @@ func (g *ReplicaApplyGate) SessionAppliedLSN(sessionID uint64, lba uint32) (uint lsn, present := g.appliedLSN[lba] return lsn, present } + +// CertifyRecoveryPrefix accepts an explicit source-coverage certificate emitted +// only after a successful recovery close is published healthy. Sync/Boundaries +// alone cannot certify coverage: a high live LSN can be durable across a hole. +// The transport owns lineage admission. A missing/refused certificate retains +// history conservatively; ordinary live traffic does not advance this floor. +func (g *ReplicaApplyGate) CertifyRecoveryPrefix(lineage transport.RecoveryLineage) error { + prefix := lineage.EffectiveFrontierHint() + g.mu.Lock() + defer g.mu.Unlock() + r, _, _ := g.store.Boundaries() + if prefix == 0 || prefix > r { + return fmt.Errorf("apply gate: certified prefix %d exceeds durable boundary %d or is zero", prefix, r) + } + if prefix <= g.floorLSN { + return nil + } + // Rebuild rather than only deleting: release the old map's bucket capacity. + retained := make(map[uint32]uint64) + for lba, lsn := range g.appliedLSN { + if lsn > prefix { + retained[lba] = lsn + } + } + g.appliedLSN = retained + g.floorLSN = prefix + return nil +} + +// CertifiedPrefix reports the source-certified coverage frontier, not R. +func (g *ReplicaApplyGate) CertifiedPrefix() uint64 { + g.mu.Lock() + defer g.mu.Unlock() + return g.floorLSN +} diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go index a4f7d07a1f..68f1323176 100644 --- a/seaweed-block/core/replication/apply_gate_floor_test.go +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -26,9 +26,9 @@ func TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole(t *testing.T) { } } -// Each batch completes durability and closes coverage; retained version history -// should scale with the outstanding suffix, rather than all LBAs ever written. -func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { +// Each batch has a successful recovery close and an explicit prefix certificate. +// Durability alone is insufficient; ordinary healthy traffic remains unbounded. +func TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory(t *testing.T) { const batch = 32 store := storage.NewBlockStore(1025, 1) gate := NewReplicaApplyGate(store) @@ -45,6 +45,9 @@ func TestApplyGate_DurableFloorBoundsVersionHistory(t *testing.T) { if _, err := store.Sync(); err != nil { t.Fatal(err) } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(session, lsn)); err != nil { + t.Fatal(err) + } // A subsequent apply provides a lazy-pruning opportunity. lsn++ if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, lsn); err != nil { @@ -69,6 +72,9 @@ func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { if _, err := store.Sync(); err != nil { t.Fatal(err) } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 32)); err != nil { + t.Fatal(err) + } gate.CloseSession(1) if err := gate.ApplyRecovery(recoveryLineage(2, 32), 5, makeData(0xAA), 1); err != nil { t.Fatal(err) @@ -93,3 +99,43 @@ func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { t.Fatalf("durable versions were not pruned: tracked=%d want=0", tracked) } } + +func TestApplyGate_CertifiedPrefixFreezesAcrossSessions(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if err := gate.ApplyLive(liveLineage(2), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if got := gate.CertifiedPrefix(); got != 1 { + t.Fatalf("new session or Sync extended certified floor: P=%d", got) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(3, 100), 6, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("frozen prefix swallowed missing recovery: err=%v", err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 121)); err == nil { + t.Fatal("certificate above durable boundary accepted") + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 1)); err != nil { + t.Fatal(err) + } + if gate.CertifiedPrefix() != 1 { + t.Fatal("failed/repeated certificate changed prefix") + } +} diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go new file mode 100644 index 0000000000..3ffe7a8591 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -0,0 +1,126 @@ +package replication + +import ( + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type observedPrefixGate struct { + *ReplicaApplyGate + certified chan error +} + +func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error { + err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l) + g.certified <- err + return err +} + +// Real primary engine/adapter/executor -> role-gated replica -> shared gate. +func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { + primary := storage.NewBlockStore(64, blockSize) + for lba := uint32(0); lba < 32; lba++ { + if _, err := primary.Write(lba, makeData(byte(lba+1))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + store := storage.NewBlockStore(64, blockSize) + gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan error, 8)} + if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + executor := transport.NewBlockExecutor(primary, listener.Addr()) + t.Cleanup(func() { executor.Stop(); listener.StopHard() }) + a := adapter.NewVolumeReplicaAdapter(executor) + a.OnAssignment(adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: listener.Addr()}) + select { + case err := <-gate.certified: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("healthy recovery did not publish wire prefix certificate") + } + if got := gate.CertifiedPrefix(); got != 32 { + t.Fatalf("wire certified prefix=%d want32", got) + } + tracked, _, _, found := gate.SessionState(2) + if !found || tracked != 0 { + t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) + } +} + +func TestApplyGate_WirePrefixCannotIntroduceOrReviveSession(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + send := func(l transport.RecoveryLineage, certificate bool) { + t.Helper() + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + if certificate { + if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(l)); err != nil { + t.Fatal(err) + } + } + if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)); err != nil { + if certificate { + return + } + t.Fatal(err) + } + kind, _, err := transport.ReadMsg(c) + if !certificate && (err != nil || kind != transport.MsgBarrierResp) { + t.Fatalf("setup barrier: kind=%d err=%v", kind, err) + } + } + send(recoveryLineage(1, 1), true) // unseen: rejected, must not introduce lineage + if gate.CertifiedPrefix() != 0 { + t.Fatal("unseen session certified prefix") + } + send(recoveryLineage(2, 1), false) + send(recoveryLineage(1, 1), true) // superseded: cannot certify even with valid R + if gate.CertifiedPrefix() != 0 { + t.Fatal("stale session certified prefix") + } +} diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index e8eb0f44b7..26bd2f0419 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -1315,3 +1315,32 @@ func (e *BlockExecutor) recordSessionRunning(replicaID string, sessionID uint64) SessionID: sessionID, } } + +// PublishRecoveryPrefix forwards a completed-recovery certificate supplied by +// the engine's healthy publication. Failure conservatively retains the map. +// It does not certify subsequent live traffic or infer coverage from R. +func (e *BlockExecutor) PublishRecoveryPrefix(replicaID string, sessionID, epoch, endpointVersion, prefix uint64) { + if err := e.beginAsyncOperation(); err != nil { + return + } + go func() { + defer e.asyncWG.Done() + lineage := RecoveryLineage{SessionID: sessionID, Epoch: epoch, EndpointVersion: endpointVersion, FrontierHint: prefix} + conn, err := net.DialTimeout("tcp", e.replicaAddr, 2*time.Second) + if err != nil { + log.Printf("executor: prefix certificate %s: %v", replicaID, err) + return + } + defer conn.Close() + if err := e.trackTransientConn(conn); err != nil { + return + } + defer e.untrackTransientConn(conn) + if err := conn.SetDeadline(time.Now().Add(recoveryConnTimeout)); err != nil { + return + } + if err := WriteMsg(conn, MsgCertifiedPrefix, EncodeLineage(lineage)); err != nil { + log.Printf("executor: prefix certificate %s: %v", replicaID, err) + } + }() +} diff --git a/seaweed-block/core/transport/protocol.go b/seaweed-block/core/transport/protocol.go index c15344cfce..188974eed9 100644 --- a/seaweed-block/core/transport/protocol.go +++ b/seaweed-block/core/transport/protocol.go @@ -46,6 +46,10 @@ const ( // recovery-lane before any MsgShipEntry frames arrive. It replaces // payload-derived lane guessing from RecoveryLineage.TargetLSN. MsgRecoveryLaneStart byte = 0x08 + // MsgCertifiedPrefix carries a full lineage whose frontier is an explicit + // completed-recovery coverage certificate, never a scalar Sync maximum. + // No acknowledgement/old-peer fallback is needed: refusal retains history. + MsgCertifiedPrefix byte = 0x09 ) // RecoveryLineage binds a mutating recovery stream to one accepted recovery diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 13fec7a963..084b9aaefe 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -38,6 +38,12 @@ const ( // Returning a non-nil error → caller (handler) logs + closes conn. // Per INV-REPL-LIVE-LANE-STALE-FAILS-LOUD: live-lane stale entries // surface here as errors. +// RecoveryPrefixHook accepts explicit completed-prefix certificates. It does +// not derive source coverage from Sync. Admission is checked at the effect. +type RecoveryPrefixHook interface { + CertifyRecoveryPrefix(lineage RecoveryLineage) error +} + type ApplyHook interface { // ApplyRecovery routes the entry through the recovery-lane apply // path. Stale entries (LSN <= per-LBA applied) skip data + advance @@ -512,6 +518,12 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { replyType, reply = MsgBarrierResp, resp return true + case MsgCertifiedPrefix: + lineage, err := DecodeLineage(payload) + if err != nil || r.certifyRecoveryPrefix(lineage) != nil { + return true + } + case MsgBarrierReq: lineage, err := DecodeLineage(payload) if err != nil { @@ -660,7 +672,7 @@ const defaultFenceDrainTimeout = 10 * time.Second // isMutationMsg names the frames that pass acceptMutationLineage. func isMutationMsg(msgType byte) bool { switch msgType { - case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq: + case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq, MsgCertifiedPrefix: return true } return false @@ -782,3 +794,20 @@ func compareLineage(a, b RecoveryLineage) int { return 0 } } + +// A certificate cannot introduce an unseen session or survive a later one. +// Lock order: listener.mu -> gate.mu -> store boundary read. There is no wire +// or physical I/O here; fencing/session admission cannot cross the effect. +func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.primary || (r.requireRole && !r.assigned) || lineage.Epoch < r.epochFloor || + lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) { + return fmt.Errorf("replica: uncertified/stale recovery lineage") + } + hook, ok := r.applyHook.(RecoveryPrefixHook) + if !ok { + return fmt.Errorf("replica: no recovery prefix hook") + } + return hook.CertifyRecoveryPrefix(lineage) +} From ed08492b87d798eb875f05f66f38020dacdd67e2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:56:19 -0800 Subject: [PATCH 22/35] test: specify certified prefix pruning and recovery coverage guards --- .../core/engine/recovery_prefix_test.go | 2 +- seaweed-block/docs/design/block-design.md | 1 + seaweed-block/docs/design/invariants.md | 9 +++++- seaweed-block/docs/spec/README.md | 7 +++++ .../docs/spec/ReplicaPrefixFloor.tla | 31 +++++++++++++++++++ .../spec/cfg/R293_prefix_red_forgot_floor.cfg | 4 +++ .../spec/cfg/R293_prefix_red_synced_max.cfg | 4 +++ .../docs/spec/cfg/R293_prefix_safe.cfg | 4 +++ seaweed-block/docs/spec/run.sh | 1 + 9 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/docs/spec/ReplicaPrefixFloor.tla create mode 100644 seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go index 464b8ea878..d58b5367cc 100644 --- a/seaweed-block/core/engine/recovery_prefix_test.go +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -12,7 +12,7 @@ func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { t.Fatal("recovery close certified before post-close ack") } } - result = Apply(st, DurableAckObserved{ReplicaID: "r1", SessionID: 8, EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) + result = Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) for _, command := range result.Commands { if healthy, ok := command.(PublishHealthy); ok { if healthy.CertifiedPrefix != 100 || healthy.RecoverySessionID != 8 || healthy.Epoch != 1 || healthy.EndpointVersion != 1 { diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 41a572dd55..9061f000c4 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -299,6 +299,7 @@ stateDiagram-v2 Degraded --> CatchingUp: gap within the primary's WAL CatchingUp --> CatchingUp: identical recovery facts retain the prepared session Healthy --> Healthy: delayed probe retains completed durable R + Healthy --> Healthy: completed recovery certifies P, prune version suffix CatchingUp --> Healthy: caught up to the target CatchingUp --> Degraded: catch-up fails Degraded --> Healthy: recovers diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index afe5586a3a..e30a534706 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -114,6 +114,13 @@ stateDiagram-v2 Excluded --> Supporting: later fact lists self as a peer ``` +The apply gate retains versions only above its certified contiguous prefix P. +Completed recovery plus post-close healthy publication sends an explicit full-lineage +certificate; current listener admission and the durable boundary guard it. Sync R, +ordinary live traffic and session changes do not advance P. This implementation +prunes at successful recovery certification only; healthy-run growth remains an +RF2 qualification limitation until ordered-live certification is wired. + **Host role and listener admission.** | From | To | Event and guard | Enforced in | Protects | @@ -135,7 +142,7 @@ stateDiagram-v2 |---|---|---|---|---| | `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | | `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | -| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion` | `ReplicaApplyOrder` NoRegression | ACTIVE | +| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | | `INV-REPL-CATCHUP-REBUILD-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 8190995f3e..a3586b8834 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -320,3 +320,10 @@ HostBudget also models guarded configuration initialization: staged bytes are in ## Replica apply ordering `ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression`, `NoDuplicateRecovery` and `NoFalseKnown`; the four `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. + +`ReplicaPrefixFloor.tla` checks two LBAs/three source versions with explicit +covered-prefix certification, suffix pruning and stale checks against the floor. +`R293_prefix_safe` checks `NoRegression`, `CertifiedCoverage`, and `OnlySuffix`; +its two negative controls infer a prefix from the synced maximum or omit the +floor after pruning. It does not establish the wire certificate's provenance, +restart persistence, live-prefix extension, or a fixed memory cap without closes. diff --git a/seaweed-block/docs/spec/ReplicaPrefixFloor.tla b/seaweed-block/docs/spec/ReplicaPrefixFloor.tla new file mode 100644 index 0000000000..70e419d693 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaPrefixFloor.tla @@ -0,0 +1,31 @@ +----------------------- MODULE ReplicaPrefixFloor ----------------------- +EXTENDS Integers, TLC +CONSTANTS UseFloor, CertifiedOnly +VARIABLES data, seen, versions, durable, prefix +vars == <> +Addr(n) == IF n = 2 THEN 2 ELSE 1 +Max(a,b) == IF a > b THEN a ELSE b +Covered(p) == \A n \in 1..p : data[Addr(n)] >= n +Init == /\ data = [i \in 1..2 |-> 0] /\ seen = data /\ versions = data + /\ durable = 0 /\ prefix = 0 +Apply(n) == LET i == Addr(n) + threshold == Max(versions[i], IF UseFloor THEN prefix ELSE 0) + IN /\ data' = IF n > threshold THEN [data EXCEPT ![i] = n] ELSE data + /\ seen' = [seen EXCEPT ![i] = Max(@,n)] + /\ versions' = IF n > threshold THEN [versions EXCEPT ![i] = n] ELSE versions + /\ UNCHANGED <> +Sync == /\ durable' = Max(durable, Max(data[1],data[2])) + /\ UNCHANGED <> +Certify(p) == /\ p > prefix /\ p <= durable + /\ (~CertifiedOnly \/ Covered(p)) + /\ prefix' = p + /\ versions' = [i \in 1..2 |-> IF versions[i] <= p THEN 0 ELSE versions[i]] + /\ UNCHANGED <> +\* Session changes, ordinary live writes, disconnects and Sync do not certify. +RestartSession == UNCHANGED vars +Next == (\E n \in 1..3 : Apply(n)) \/ Sync \/ (\E p \in 1..3 : Certify(p)) \/ RestartSession +Spec == Init /\ [][Next]_vars +NoRegression == data = seen +CertifiedCoverage == Covered(prefix) +OnlySuffix == \A i \in 1..2 : versions[i] = 0 \/ versions[i] > prefix +============================================================================= \ No newline at end of file diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg new file mode 100644 index 0000000000..651a875730 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = FALSE + CertifiedOnly = TRUE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg new file mode 100644 index 0000000000..2e7b34a866 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = TRUE + CertifiedOnly = FALSE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg new file mode 100644 index 0000000000..8fc29bed97 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = TRUE + CertifiedOnly = TRUE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 4bfc7d0b46..06ed9184b8 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,7 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R293_prefix_*) spec=ReplicaPrefixFloor ;; R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; S9_*) spec=RetentionGCTiming ;; From 7b2522b4850c070f9acfaea538413398f4b75801 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:57:24 -0800 Subject: [PATCH 23/35] test: refuse prefix certification from plain healthy probes --- .../core/engine/recovery_prefix_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go index d58b5367cc..d8eeec7077 100644 --- a/seaweed-block/core/engine/recovery_prefix_test.go +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -23,3 +23,20 @@ func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { } t.Fatal("post-close ack did not publish certified recovery prefix") } + +func TestHealthyProbeDoesNotCertifyRecoveryPrefix(t *testing.T) { + st := helperPrime(t, 100, 1, 100) + result := Apply(st, FenceCompleted{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + found := false + for _, command := range result.Commands { + if healthy, ok := command.(PublishHealthy); ok { + found = true + if healthy.CertifiedPrefix != 0 || healthy.RecoverySessionID != 0 { + t.Fatalf("plain healthy probe invented a prefix certificate: %+v", healthy) + } + } + } + if !found { + t.Fatal("control did not reach healthy publication") + } +} From 78781527ae91243bb4273d39770da3208b32415c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 04:58:38 -0800 Subject: [PATCH 24/35] test: bind wire pruning assertion to its actual recovery session --- .../apply_gate_prefix_wire_test.go | 21 ++++++++++++------- .../spec/cfg/R293_prefix_red_forgot_floor.cfg | 2 +- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go index 3ffe7a8591..9c194b13fa 100644 --- a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -10,14 +10,19 @@ import ( "github.com/seaweedfs/seaweed-block/core/transport" ) +type prefixResult struct { + lineage transport.RecoveryLineage + err error +} + type observedPrefixGate struct { *ReplicaApplyGate - certified chan error + certified chan prefixResult } func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error { err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l) - g.certified <- err + g.certified <- prefixResult{l, err} return err } @@ -33,7 +38,7 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { t.Fatal(err) } store := storage.NewBlockStore(64, blockSize) - gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan error, 8)} + gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan prefixResult, 8)} if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { t.Fatal(err) } @@ -53,18 +58,20 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { t.Cleanup(func() { executor.Stop(); listener.StopHard() }) a := adapter.NewVolumeReplicaAdapter(executor) a.OnAssignment(adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: listener.Addr()}) + var certified transport.RecoveryLineage select { - case err := <-gate.certified: - if err != nil { - t.Fatal(err) + case result := <-gate.certified: + if result.err != nil { + t.Fatal(result.err) } + certified = result.lineage case <-time.After(5 * time.Second): t.Fatal("healthy recovery did not publish wire prefix certificate") } if got := gate.CertifiedPrefix(); got != 32 { t.Fatalf("wire certified prefix=%d want32", got) } - tracked, _, _, found := gate.SessionState(2) + tracked, _, _, found := gate.SessionState(certified.SessionID) if !found || tracked != 0 { t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) } diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg index 651a875730..c877180acc 100644 --- a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg @@ -1,4 +1,4 @@ SPECIFICATION Spec CONSTANTS UseFloor = FALSE CertifiedOnly = TRUE -INVARIANTS NoRegression CertifiedCoverage OnlySuffix +INVARIANTS NoRegression From 8bd459c24af06b7ef90dfb6beb34097da5a53928 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:02:39 -0800 Subject: [PATCH 25/35] fix: require a covered starting image before extending replica prefix --- .../apply_gate_prefix_wire_test.go | 93 +++++++++++++++++-- seaweed-block/core/transport/replica.go | 32 ++++++- 2 files changed, 116 insertions(+), 9 deletions(-) diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go index 9c194b13fa..83065c3ce1 100644 --- a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -1,6 +1,7 @@ package replication import ( + "bytes" "net" "testing" "time" @@ -28,6 +29,10 @@ func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) // Real primary engine/adapter/executor -> role-gated replica -> shared gate. func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { + t.Run("catchup_from_certified_base", func(t *testing.T) { runHealthyRecoveryPrefix(t, true) }) + t.Run("full_base", func(t *testing.T) { runHealthyRecoveryPrefix(t, false) }) +} +func runHealthyRecoveryPrefix(t *testing.T, seeded bool) { primary := storage.NewBlockStore(64, blockSize) for lba := uint32(0); lba < 32; lba++ { if _, err := primary.Write(lba, makeData(byte(lba+1))); err != nil { @@ -39,11 +44,17 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { } store := storage.NewBlockStore(64, blockSize) gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan prefixResult, 8)} - if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { - t.Fatal(err) - } - if _, err := store.Sync(); err != nil { - t.Fatal(err) + if seeded { + if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + // This initial BASE is known complete; Sync alone must not establish it. + if err := gate.ReplicaApplyGate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil { + t.Fatal(err) + } } listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) if err != nil { @@ -72,7 +83,7 @@ func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { t.Fatalf("wire certified prefix=%d want32", got) } tracked, _, _, found := gate.SessionState(certified.SessionID) - if !found || tracked != 0 { + if (seeded && !found) || tracked != 0 { t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) } } @@ -131,3 +142,73 @@ func TestApplyGate_WirePrefixCannotIntroduceOrReviveSession(t *testing.T) { t.Fatal("stale session certified prefix") } } + +// A clean recovery close cannot certify a pre-existing hole in its starting R. +func TestApplyGate_WirePrefixRequiresCoveredStartingImage(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + lineage := recoveryLineage(2, 120) + dial := func() net.Conn { + t.Helper() + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + return c + } + barrier := func(c net.Conn) error { + if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(lineage)); err != nil { + return err + } + _, _, err := transport.ReadMsg(c) + return err + } + c := dial() + if err := transport.WriteMsg(c, transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + if err := barrier(c); err != nil { + t.Fatal(err) + } + if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + _ = barrier(c) // certificate refusal closes this connection + if got := gate.CertifiedPrefix(); got != 0 { + t.Fatalf("uncertified starting R advanced P=%d", got) + } + c = dial() + if err := transport.WriteMsg(c, transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + want := makeData(0xAA) + if err := transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 6, LSN: 95, Data: want})); err != nil { + t.Fatal(err) + } + if err := barrier(c); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("uncertified starting image swallowed recovery hole: err=%v", err) + } +} diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 084b9aaefe..a0ce27c2f4 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -42,6 +42,7 @@ const ( // not derive source coverage from Sync. Admission is checked at the effect. type RecoveryPrefixHook interface { CertifyRecoveryPrefix(lineage RecoveryLineage) error + CertifiedPrefix() uint64 } type ApplyHook interface { @@ -64,8 +65,9 @@ type ReplicaListener struct { wg sync.WaitGroup applyHook ApplyHook // optional gate plug-in; nil = direct apply - mu sync.Mutex - activeLineage RecoveryLineage + mu sync.Mutex + activeLineage RecoveryLineage + prefixEligible RecoveryLineage // one active source-covered recovery certificate // epochFloor is the highest epoch this host has taken a role at // (G2): mutating traffic below it is refused. primary is set while // this host is the primary: then every inbound replication mutation @@ -382,6 +384,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return true } lane = mutationLaneRecovery + r.markPrefixEligibility(lineage, false) case MsgShipEntry: entry, err := DecodeShipEntry(payload) @@ -509,6 +512,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: sync after rebuild done: %v", err) return true } + // A completed full BASE supplies the covered starting image. + r.markPrefixEligibility(lineage, true) // Echo the request's full lineage in the rebuild-done ack // so primary-side validators can consume it. resp := EncodeBarrierResp(BarrierResponse{ @@ -802,7 +807,7 @@ func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { r.mu.Lock() defer r.mu.Unlock() if r.primary || (r.requireRole && !r.assigned) || lineage.Epoch < r.epochFloor || - lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) { + lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) || !r.prefixEligible.Equivalent(lineage) { return fmt.Errorf("replica: uncertified/stale recovery lineage") } hook, ok := r.applyHook.(RecoveryPrefixHook) @@ -811,3 +816,24 @@ func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { } return hook.CertifyRecoveryPrefix(lineage) } + +// A successful scan can extend only an already-covered starting prefix. The +// engine starts catch-up at probed R+1; R is monotone, so observing local R<=P +// at the lane marker is a conservative bound on that starting R. A completed +// full BASE instead supplies its own prefix. A refusal only retains history. +func (r *ReplicaListener) markPrefixEligibility(lineage RecoveryLineage, fullBase bool) { + r.mu.Lock() + defer r.mu.Unlock() + if !r.activeLineage.Equivalent(lineage) || r.primary || (r.requireRole && !r.assigned) { + return + } + r.prefixEligible = RecoveryLineage{} + hook, ok := r.applyHook.(RecoveryPrefixHook) + if !ok { + return + } + synced, _, _ := r.store.Boundaries() + if fullBase || synced <= hook.CertifiedPrefix() { + r.prefixEligible = lineage + } +} From 7261411c467892aabb79395584c0f4c04090e926 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:04:01 -0800 Subject: [PATCH 26/35] docs: state prefix provenance and remaining healthy-run bound --- seaweed-block/docs/design/invariants.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e30a534706..fabac920e5 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -116,10 +116,10 @@ stateDiagram-v2 The apply gate retains versions only above its certified contiguous prefix P. Completed recovery plus post-close healthy publication sends an explicit full-lineage -certificate; current listener admission and the durable boundary guard it. Sync R, +certificate; current listener admission and the durable boundary guard it. A catch-up certificate also requires a covered starting image (local R at its lane marker no greater than P); a completed full BASE supplies its own image. A missing certificate retains history. Sync R, ordinary live traffic and session changes do not advance P. This implementation prunes at successful recovery certification only; healthy-run growth remains an -RF2 qualification limitation until ordered-live certification is wired. +RF2 qualification limitation until ordered-live certification is wired (#297). Session coverage teardown is separate. **Host role and listener admission.** From 61274080b08b68178691cbb8d156cdde1c12ad4e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:12:09 -0800 Subject: [PATCH 27/35] test: reproduce false readiness and retained settled replica coverage --- .../engine/recovery_review_regression_test.go | 29 ++++++++++ .../replication/apply_gate_retirement_test.go | 54 +++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 seaweed-block/core/engine/recovery_review_regression_test.go create mode 100644 seaweed-block/core/replication/apply_gate_retirement_test.go diff --git a/seaweed-block/core/engine/recovery_review_regression_test.go b/seaweed-block/core/engine/recovery_review_regression_test.go new file mode 100644 index 0000000000..627be92efa --- /dev/null +++ b/seaweed-block/core/engine/recovery_review_regression_test.go @@ -0,0 +1,29 @@ +package engine + +import "testing" + +func TestPromotionReadyRefusesDelayedProbeDuringNewRecovery(t *testing.T) { + st := helperPrime(t, 50, 10, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 100, S: 10, H: 150}) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 2, Kind: SessionCatchUp, FrontierHint: 150}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + if fact := BuildPromotionReadyFact(st); fact.Ready { + t.Fatalf("active recovery became promotion ready after delayed probe: %+v", fact) + } +} + +func TestMissingProbeAckRestoresNewerDurableProgress(t *testing.T) { + st := helperPrime(t, 50, 10, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + result := Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 150, PrimaryTailLSN: 110, PrimaryHeadLSN: 150}) + if st.Recovery.R != 150 || st.Recovery.Decision != DecisionNone { + t.Fatalf("missing-probe ACK retained stale progress: R=%d decision=%s", st.Recovery.R, st.Recovery.Decision) + } + assertNoCommand(t, result, "StartRebuild") + assertNoCommand(t, result, "StartCatchUp") +} diff --git a/seaweed-block/core/replication/apply_gate_retirement_test.go b/seaweed-block/core/replication/apply_gate_retirement_test.go new file mode 100644 index 0000000000..64e506e94b --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_retirement_test.go @@ -0,0 +1,54 @@ +package replication + +import ( + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestApplyGate_WireSessionTurnoverRetiresSettledCoverage(t *testing.T) { + gate, store := newGate(t) + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + for session := uint64(1); session <= 128; session++ { + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + c.Close() + t.Fatal(err) + } + l := liveLineage(session) + err = transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: l, LBA: 5, LSN: session, Data: makeData(byte(session))})) + if err == nil { + err = transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)) + } + if err == nil { + _, _, err = transport.ReadMsg(c) + } + c.Close() + if err != nil { + t.Fatal(err) + } + if session > 1 { + if _, _, _, found := gate.SessionState(session - 1); found { + t.Fatalf("settled session coverage survived turnover: session=%d", session-1) + } + } + } + // Retirement must leave the shared suffix version intact. + if err := gate.ApplyLive(liveLineage(129), 5, makeData(0), 127); err == nil { + t.Fatal("coverage retirement erased shared version") + } +} From 704eedac6730fac5499055087b73ca2ea96d92f5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:16:35 -0800 Subject: [PATCH 28/35] fix: guard promotion readiness and retire settled replica sessions --- .../core/adapter/recovery_dedup_test.go | 21 +++- seaweed-block/core/engine/apply.go | 1 + seaweed-block/core/engine/promotion_ready.go | 3 + .../apply_gate_wire_overlap_test.go | 24 ++++- seaweed-block/core/transport/replica.go | 98 ++++++++++++++++--- seaweed-block/docs/design/invariants.md | 10 +- 6 files changed, 137 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go index 1fc3424f23..721c937c33 100644 --- a/seaweed-block/core/adapter/recovery_dedup_test.go +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -4,6 +4,7 @@ import ( "strconv" "sync" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/engine" ) @@ -94,8 +95,24 @@ func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { wg.Add(1) go func() { defer wg.Done(); <-start; a.OnProbeResult(probe) }() } - close(start) - wg.Wait() + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(start) }) } + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("concurrent probe workers did not settle during cleanup") + } + }) + release() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("concurrent probe workers did not settle") + } if got := countStarts(exec, "StartCatchUp"); got != 1 { t.Fatalf("identical delayed probes restarted healthy recovery: starts=%d path=%v", got, a.CommandLog()) } diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 643f4dbbfe..f0ef93008f 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -313,6 +313,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra } fact := e.ProgressFact() if st.Recovery.FactsMissing { + st.Recovery.R = max(st.Recovery.R, fact.ReplicaR) st.Recovery.S, st.Recovery.H = fact.PrimaryS, fact.PrimaryH st.Recovery.FactsMissing = false } diff --git a/seaweed-block/core/engine/promotion_ready.go b/seaweed-block/core/engine/promotion_ready.go index 9f8f8f79e6..ef1426ee72 100644 --- a/seaweed-block/core/engine/promotion_ready.go +++ b/seaweed-block/core/engine/promotion_ready.go @@ -2,6 +2,7 @@ package engine const ( PromotionReadyReasonReady = "promotion_ready" + PromotionReadyReasonRecoveryActive = "recovery_active" PromotionReadyReasonNotMember = "not_member" PromotionReadyReasonNotReachable = "not_reachable" PromotionReadyReasonNotCaughtUp = "not_caught_up" @@ -35,6 +36,8 @@ func BuildPromotionReadyFact(st *ReplicaState) PromotionReadyFact { fact.Reason = PromotionReadyReasonNotMember case st.Reachability.Status != ProbeReachable: fact.Reason = PromotionReadyReasonNotReachable + case hasActiveSession(st): + fact.Reason = PromotionReadyReasonRecoveryActive case st.Recovery.Decision != DecisionNone: fact.Reason = PromotionReadyReasonNotCaughtUp case st.Identity.Epoch > st.Reachability.FencedEpoch: diff --git a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go index e6a0040e50..f3f41a5e1c 100644 --- a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go +++ b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go @@ -15,6 +15,14 @@ type heldAdmittedRecovery struct { *ReplicaApplyGate entered, release chan struct{} done chan error + closed chan uint64 +} + +func (h *heldAdmittedRecovery) CloseSession(id uint64) { + h.ReplicaApplyGate.CloseSession(id) + if h.closed != nil { + h.closed <- id + } } func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba uint32, data []byte, lsn uint64) error { @@ -32,7 +40,7 @@ func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba ui // advances that check, then reach the apply gate after the newer write. func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { store := storage.NewBlockStore(64, blockSize) - h := &heldAdmittedRecovery{ReplicaApplyGate: NewReplicaApplyGate(store), entered: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1)} + h := &heldAdmittedRecovery{ReplicaApplyGate: NewReplicaApplyGate(store), entered: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1), closed: make(chan uint64, 8)} listener, err := transport.NewReplicaListenerWithApplyHook("127.0.0.1:0", store, h) if err != nil { t.Fatal(err) @@ -79,6 +87,9 @@ func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { want := bytes.Repeat([]byte{0xBB}, blockSize) send(c2, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: newer, LBA: 5, Data: want, LSN: 120})) barrier(c2, newer) + if _, _, _, found := h.SessionState(old.SessionID); !found { + t.Fatal("admitted old frame lost coverage before settlement") + } release() select { case err := <-h.done: @@ -88,6 +99,17 @@ func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { case <-time.After(3 * time.Second): t.Fatal("admitted old frame did not settle") } + select { + case id := <-h.closed: + if id != old.SessionID { + t.Fatalf("retired session=%d want old%d", id, old.SessionID) + } + case <-time.After(3 * time.Second): + t.Fatal("settled admitted old session was not retired") + } + if _, _, _, found := h.SessionState(old.SessionID); found { + t.Fatal("settled old coverage survived retirement") + } got, err := store.Read(5) if err != nil || !bytes.Equal(got, want) { t.Fatalf("admitted old wire session regressed bytes: err=%v", err) diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index a0ce27c2f4..9ac13c5017 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -40,6 +40,8 @@ const ( // surface here as errors. // RecoveryPrefixHook accepts explicit completed-prefix certificates. It does // not derive source coverage from Sync. Admission is checked at the effect. +type SessionRetirer interface{ CloseSession(sessionID uint64) } + type RecoveryPrefixHook interface { CertifyRecoveryPrefix(lineage RecoveryLineage) error CertifiedPrefix() uint64 @@ -65,9 +67,11 @@ type ReplicaListener struct { wg sync.WaitGroup applyHook ApplyHook // optional gate plug-in; nil = direct apply - mu sync.Mutex - activeLineage RecoveryLineage - prefixEligible RecoveryLineage // one active source-covered recovery certificate + mu sync.Mutex + activeLineage RecoveryLineage + prefixEligible RecoveryLineage // one active source-covered recovery certificate + sessionFrames map[uint64]int + retiringSessions map[uint64]bool // epochFloor is the highest epoch this host has taken a role at // (G2): mutating traffic below it is refused. primary is set while // this host is the primary: then every inbound replication mutation @@ -163,21 +167,31 @@ func (r *ReplicaListener) raiseFloor(epoch uint64) error { func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool { r.mu.Lock() prev := r.activeLineage - r.mu.Unlock() - if !r.acceptMutationLineage(l) { + if !r.acceptMutationLineageLocked(l) { + r.mu.Unlock() return false } + if r.sessionFrames == nil { + r.sessionFrames = make(map[uint64]int) + } + r.sessionFrames[l.SessionID]++ // register before another lineage can retire it + r.mu.Unlock() if err := r.raiseFloor(l.Epoch); err != nil { - // Nothing changes on a refused frame: undo the lineage advance, - // unless another frame has moved it on since. r.mu.Lock() if r.activeLineage == l { r.activeLineage = prev } + r.markSessionRetiringLocked(l.SessionID) r.mu.Unlock() + r.endSessionFrame(l.SessionID) log.Printf("replica: refuse mutation at epoch %d: %v", l.Epoch, err) return false } + r.mu.Lock() + if prev.SessionID != l.SessionID { + r.markSessionRetiringLocked(prev.SessionID) + } + r.mu.Unlock() return true } @@ -245,6 +259,7 @@ func (r *ReplicaListener) Stop() { close(r.stopCh) r.listener.Close() r.wg.Wait() + r.closeSettledSessions() } // StopHard is like Stop but also forcibly closes all active handler @@ -280,6 +295,7 @@ func (r *ReplicaListener) StopHard() { _ = c.Close() } r.wg.Wait() + r.closeSettledSessions() } func (r *ReplicaListener) acceptLoop() { @@ -370,6 +386,14 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { // the fence waits for storage effects only, never for the network. var replyType byte var reply []byte + var admittedSession uint64 + admit := func(l RecoveryLineage) bool { + if !r.admitMutation(l) { + return false + } + admittedSession = l.SessionID + return true + } stop := func() bool { switch msgType { case MsgRecoveryLaneStart: @@ -378,7 +402,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode recovery lane start: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -392,7 +416,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode ship entry: %v", err) return true } - if !r.admitMutation(entry.Lineage) { + if !admit(entry.Lineage) { log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d", entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion) return true @@ -466,7 +490,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode rebuild block: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -489,7 +513,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode rebuild done: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -535,7 +559,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode barrier req: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -557,6 +581,9 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } return false }() + if admittedSession != 0 { + r.endSessionFrame(admittedSession) + } if mutating { r.endMutationFrame() } @@ -749,6 +776,10 @@ func (r *ReplicaListener) AdmitAsReplica(epoch uint64) error { func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { r.mu.Lock() defer r.mu.Unlock() + return r.acceptMutationLineageLocked(incoming) +} + +func (r *ReplicaListener) acceptMutationLineageLocked(incoming RecoveryLineage) bool { if incoming.SessionID == 0 || incoming.Epoch == 0 || incoming.EndpointVersion == 0 { return false @@ -837,3 +868,46 @@ func (r *ReplicaListener) markPrefixEligibility(lineage RecoveryLineage, fullBas r.prefixEligible = lineage } } + +// Retirement tracks logical-session frames, not socket lifetimes. A newer +// session may run while an admitted older frame is parked before the hook. +// Lock order remains listener.mu -> gate.mu; versions and P are not released. +func (r *ReplicaListener) markSessionRetiringLocked(id uint64) { + if id == 0 { + return + } + if r.retiringSessions == nil { + r.retiringSessions = make(map[uint64]bool) + } + r.retiringSessions[id] = true + r.retireSessionIfSettledLocked(id) +} +func (r *ReplicaListener) retireSessionIfSettledLocked(id uint64) { + if !r.retiringSessions[id] || id == r.activeLineage.SessionID || r.sessionFrames[id] != 0 { + return + } + if hook, ok := r.applyHook.(SessionRetirer); ok { + hook.CloseSession(id) + } + delete(r.retiringSessions, id) +} +func (r *ReplicaListener) endSessionFrame(id uint64) { + r.mu.Lock() + defer r.mu.Unlock() + r.sessionFrames[id]-- + if r.sessionFrames[id] == 0 { + delete(r.sessionFrames, id) + } + r.retireSessionIfSettledLocked(id) +} +func (r *ReplicaListener) closeSettledSessions() { + r.mu.Lock() + defer r.mu.Unlock() + if hook, ok := r.applyHook.(SessionRetirer); ok { + hook.CloseSession(r.activeLineage.SessionID) + for id := range r.retiringSessions { + hook.CloseSession(id) + } + } + r.retiringSessions = nil +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index fabac920e5..6907808089 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -119,7 +119,7 @@ Completed recovery plus post-close healthy publication sends an explicit full-li certificate; current listener admission and the durable boundary guard it. A catch-up certificate also requires a covered starting image (local R at its lane marker no greater than P); a completed full BASE supplies its own image. A missing certificate retains history. Sync R, ordinary live traffic and session changes do not advance P. This implementation prunes at successful recovery certification only; healthy-run growth remains an -RF2 qualification limitation until ordered-live certification is wired (#297). Session coverage teardown is separate. +RF2 qualification limitation until ordered-live certification is wired (#297). Settled superseded logical sessions release coverage after their admitted frames finish; shared versions and P survive. Seed enumeration and healthy-run growth remain RF2 qualification limits. **Host role and listener admission.** @@ -141,9 +141,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| | `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | -| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | | `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | @@ -335,7 +333,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. +83 rows: 72 ACTIVE, 11 STUB; 15 kept from the internal ledger, 68 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. @@ -425,6 +423,8 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| +| `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | +| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | | `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | | `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | | `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | From db07ef2c160a872ccd99f6bdbf778b00b55db1df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 05:23:15 -0800 Subject: [PATCH 29/35] docs: align replica lifecycle and promotion guard models --- seaweed-block/core/transport/replica.go | 2 ++ seaweed-block/docs/design/block-design.md | 1 + seaweed-block/docs/design/invariants.md | 9 +++--- seaweed-block/docs/spec/README.md | 7 ++++ .../docs/spec/ReplicaReviewGuards.tla | 32 +++++++++++++++++++ .../docs/spec/cfg/R293_review_red_ack.cfg | 6 ++++ .../spec/cfg/R293_review_red_early_close.cfg | 6 ++++ .../spec/cfg/R293_review_red_readiness.cfg | 6 ++++ .../spec/cfg/R293_review_red_retention.cfg | 6 ++++ .../docs/spec/cfg/R293_review_safe.cfg | 6 ++++ seaweed-block/docs/spec/run.sh | 1 + 11 files changed, 78 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/docs/spec/ReplicaReviewGuards.tla create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg create mode 100644 seaweed-block/docs/spec/cfg/R293_review_safe.cfg diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 9ac13c5017..b413222c7e 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -42,6 +42,8 @@ const ( // not derive source coverage from Sync. Admission is checked at the effect. type SessionRetirer interface{ CloseSession(sessionID uint64) } +// RecoveryPrefixHook accepts explicit completed-prefix certificates. It does +// not derive source coverage from Sync. Admission is checked at the effect. type RecoveryPrefixHook interface { CertifyRecoveryPrefix(lineage RecoveryLineage) error CertifiedPrefix() uint64 diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index 9061f000c4..f3f35d38e8 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -298,6 +298,7 @@ stateDiagram-v2 Healthy --> Degraded: barrier or ship failure Degraded --> CatchingUp: gap within the primary's WAL CatchingUp --> CatchingUp: identical recovery facts retain the prepared session + CatchingUp --> CatchingUp: active session refuses promotion readiness Healthy --> Healthy: delayed probe retains completed durable R Healthy --> Healthy: completed recovery certifies P, prune version suffix CatchingUp --> Healthy: caught up to the target diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6907808089..d2227ca9d4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -132,7 +132,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S | Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | | any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | -| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | +| Supporting | promotion candidate | no active recovery session; member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | **Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R; missing probe boundaries remain unknown until a valid observation arrives. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. @@ -333,7 +333,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -83 rows: 72 ACTIVE, 11 STUB; 15 kept from the internal ledger, 68 new. +117 rows: 98 ACTIVE, 19 STUB; 15 kept from the internal ledger, 102 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. @@ -423,7 +423,8 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| -| `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery | ACTIVE | +| `INV-REPL-SESSION-COVERAGE-RETIRE-001` | Superseded logical-session coverage is released only after every already-admitted frame for that session settles; newer sessions do not delay that release. Shared version history and P survive. | M3 replica admission / session retirement | `transport/replica.go` `admitMutation`, `endSessionFrame`; `ReplicaApplyGate.CloseSession` | `TestApplyGate_WireSessionTurnoverRetiresSettledCoverage`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` | `ReplicaReviewGuards` NoEarlyRetirement/NoSettledHistory | ACTIVE | +| `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestMissingProbeAckRestoresNewerDurableProgress`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery; `ReplicaReviewGuards` AckRestoresProgress | ACTIVE | | `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | | `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | | `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | @@ -431,7 +432,7 @@ Notes: | `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | | `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | | `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. An active recovery session always refuses readiness, even if delayed bounds select DecisionNone. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`), `TestPromotionReadyRefusesDelayedProbeDuringNewRecovery` | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive`; `ReplicaReviewGuards` ReadyRequiresIdle | ACTIVE | | `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | | `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | | `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index a3586b8834..7b0862480e 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -327,3 +327,10 @@ covered-prefix certification, suffix pruning and stale checks against the floor. its two negative controls infer a prefix from the synced maximum or omit the floor after pruning. It does not establish the wire certificate's provenance, restart persistence, live-prefix extension, or a fixed memory cap without closes. + +`ReplicaReviewGuards.tla` checks two logical sessions with one admitted frame +per session, settled-coverage retirement, active-recovery readiness refusal and +one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; +four negative controls separately remove retirement, the frame join, the +readiness guard or ACK progress restoration. This abstracts successful admitted +frames and does not prove physical-I/O, authority rollback or timing behavior. diff --git a/seaweed-block/docs/spec/ReplicaReviewGuards.tla b/seaweed-block/docs/spec/ReplicaReviewGuards.tla new file mode 100644 index 0000000000..82e179c078 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaReviewGuards.tla @@ -0,0 +1,32 @@ +---------------------- MODULE ReplicaReviewGuards ---------------------- +EXTENDS Integers, TLC +CONSTANTS RetireSettled, WaitForFrames, GuardActive, RestoreAck +VARIABLES current, refs, coverage, active, ready, missing, observedR +vars == <> +Init == /\ current = 1 /\ refs = [s \in 1..2 |-> 0] /\ coverage = {1} + /\ active = FALSE /\ ready = FALSE /\ missing = TRUE /\ observedR = 100 +Admit(s) == /\ s >= current /\ refs[s] = 0 + /\ current' = s /\ refs' = [refs EXCEPT ![s] = 1] + /\ coverage' = (coverage \cup {s}) \ ( + IF RetireSettled /\ s # current /\ (refs[current] = 0 \/ ~WaitForFrames) + THEN {current} ELSE {}) + /\ UNCHANGED <> +Release(s) == /\ refs[s] = 1 /\ refs' = [refs EXCEPT ![s] = 0] + /\ coverage' = IF RetireSettled /\ s # current THEN coverage \ {s} ELSE coverage + /\ UNCHANGED <> +Prepare == /\ ~active /\ active' = TRUE /\ ready' = FALSE + /\ UNCHANGED <> +DelayedProbe == /\ active /\ ready' = ~GuardActive + /\ UNCHANGED <> +Finish == /\ active /\ active' = FALSE /\ ready' = TRUE + /\ UNCHANGED <> +Ack == /\ missing /\ missing' = FALSE + /\ observedR' = IF RestoreAck THEN 150 ELSE 100 + /\ UNCHANGED <> +Next == (\E s \in 1..2 : Admit(s) \/ Release(s)) \/ Prepare \/ DelayedProbe \/ Finish \/ Ack +Spec == Init /\ [][Next]_vars +NoEarlyRetirement == \A s \in 1..2 : refs[s] = 1 => s \in coverage +NoSettledHistory == \A s \in coverage : s = current \/ refs[s] = 1 +ReadyRequiresIdle == ready => ~active +AckRestoresProgress == ~missing => observedR = 150 +============================================================================= \ No newline at end of file diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg new file mode 100644 index 0000000000..8ff050bb89 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = FALSE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg new file mode 100644 index 0000000000..c9ebaae853 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = FALSE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg new file mode 100644 index 0000000000..2ea4b4a0da --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = FALSE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg new file mode 100644 index 0000000000..d67850d71a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = FALSE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_safe.cfg b/seaweed-block/docs/spec/cfg/R293_review_safe.cfg new file mode 100644 index 0000000000..ba56fd7d5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 06ed9184b8..06c7e844f3 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,7 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R293_review_*) spec=ReplicaReviewGuards ;; R293_prefix_*) spec=ReplicaPrefixFloor ;; R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; From 0b5a980bc8c674743e8a8134cb551f7fe55df98a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:21:58 -0800 Subject: [PATCH 30/35] test(storage): require sparse creation and refuse fallocate policy --- .../core/storage/data_sync_linux_test.go | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 0c76a670a2..379c2a6248 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -190,32 +190,32 @@ func TestDataSyncSyscallProbe(t *testing.T) { } } -func TestFallocateCreatesAllocatedUnwrittenVolume(t *testing.T) { - t.Setenv("SWBLOCK_SYNC", "fdatasync") +func TestFallocateAllocationIsRefused(t *testing.T) { t.Setenv("SWBLOCK_PREZERO", "0") t.Setenv("SWBLOCK_ALLOCATION", "fallocate") + s, err := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + if err == nil { + s.Close() + t.Fatal("fallocate allocation must be refused") + } +} + +func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "") + t.Setenv("SWBLOCK_PREZERO", "") + t.Setenv("SWBLOCK_ALLOCATION", "") path := filepath.Join(t.TempDir(), "volume") - s, e := CreateWALStore(path, 32, 4096) - if e != nil { - t.Fatal(e) + s, err := CreateWALStore(path, 8192, 4096) + if err != nil { + t.Fatal(err) } defer s.Close() - f, e := os.Open(path) - if e != nil { - t.Fatal(e) - } - defer f.Close() - if e = verifyAllocatedFile(f, false); e != nil { - t.Fatalf("fallocate left holes: %v", e) - } - if e = verifyInitializedFile(f); e == nil { - t.Fatal("fallocate unexpectedly reports every extent written") - } - if _, e = s.Recover(); e != nil { - t.Fatal(e) + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) } - b, e := s.Read(31) - if e != nil || !bytes.Equal(b, make([]byte, 4096)) { - t.Fatalf("unwritten extent bytes: %v", e) + stat := info.Sys().(*syscall.Stat_t) + if allocated := stat.Blocks * 512; allocated >= info.Size()/4 { + t.Fatalf("default volume lost sparse allocation: allocated=%d size=%d", allocated, info.Size()) } } From a1ce2a4d9e8d75898dc770fe8893f2518f9455f3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:22:34 -0800 Subject: [PATCH 31/35] fix(storage): default Linux data sync to fdatasync and retain sparse creation --- seaweed-block/core/storage/data_sync.go | 24 +++++++------------ seaweed-block/core/storage/data_sync_linux.go | 2 ++ seaweed-block/core/storage/data_sync_other.go | 2 ++ 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 89105d9272..ee6efd7a46 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -7,17 +7,21 @@ import ( "os" ) -// Experimental data-only sync applies to WAL/extent data. Descriptor slots, +// Data-only sync applies to WAL/extent data on Linux by default. Descriptor slots, // chunk maps, creation and directory operations retain full fsync. func newDataFileSync(f *os.File) (func() error, error) { - switch mode := os.Getenv("SWBLOCK_SYNC"); mode { - case "", "fsync": + mode := os.Getenv("SWBLOCK_SYNC") + if mode == "" { + mode = defaultDataFileSyncMode + } + switch mode { + case "fsync": return f.Sync, nil case "fdatasync": if err := dataSyncSupported(); err != nil { return nil, err } - log.Printf("storage: experimental WAL/extent sync=fdatasync file=%s", f.Name()) + log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) return func() error { return fdatasyncFile(f) }, nil default: return nil, fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) @@ -42,17 +46,7 @@ func prezeroNewStore(f *os.File, size int64) error { case "", "sparse": return nil case "fallocate": - if err := fallocateFile(f, size); err != nil { - return err - } - if err := f.Sync(); err != nil { - return err - } - if err := verifyAllocatedFile(f, false); err != nil { - return err - } - log.Printf("storage: FIEMAP verified allocated file=%s bytes=%d (unwritten extents allowed)", f.Name(), size) - return nil + return fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") case "prezero": if err := dataSyncSupported(); err != nil { return err diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go index cbc07c8832..23273f33f4 100644 --- a/seaweed-block/core/storage/data_sync_linux.go +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -12,6 +12,8 @@ import ( // FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. // Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone // does not satisfy the initialized-file experiment's precondition. +const defaultDataFileSyncMode = "fdatasync" + func verifyInitializedFile(f *os.File) error { return verifyAllocatedFile(f, true) } func verifyAllocatedFile(f *os.File, written bool) error { diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go index 8469247cfe..7018474354 100644 --- a/seaweed-block/core/storage/data_sync_other.go +++ b/seaweed-block/core/storage/data_sync_other.go @@ -7,6 +7,8 @@ import ( "os" ) +const defaultDataFileSyncMode = "fsync" + func dataSyncSupported() error { return errors.New("storage: fdatasync/prezero experiment requires Linux") } From ccd94bd232b882b9144e98231c01190749a1719e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:23:32 -0800 Subject: [PATCH 32/35] docs(storage): align data sync and sparse creation contract --- seaweed-block/core/storage/data_sync_linux_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 379c2a6248..4540d255a1 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -159,7 +159,7 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { } } -// Run under strace with the experiment environment unset/set to verify the +// Run under strace with the sync environment unset/set to verify the // syscall boundary independently of the selected function's Go identity. func TestDataSyncSyscallProbe(t *testing.T) { opts := WALStoreOptions{} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3801ba765a..2c6706d810 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | Default WAL/extent sync remains fsync. Linux `SWBLOCK_SYNC=fdatasync` selects data-only sync for WAL/extent data; descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|fallocate|prezero` selects allocation at create; fallocate retains unwritten extents. `SWBLOCK_PREZERO=1` aliases prezero, which writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | ## Part C. Change rules From 802b159c9fabf1f43a3250a3bd93020f3db73a7c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:24:59 -0800 Subject: [PATCH 33/35] test(storage): distinguish sparse volume space from initialized WAL --- seaweed-block/core/storage/data_sync_linux_test.go | 2 +- seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 4540d255a1..c040f2287f 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -205,7 +205,7 @@ func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { t.Setenv("SWBLOCK_PREZERO", "") t.Setenv("SWBLOCK_ALLOCATION", "") path := filepath.Join(t.TempDir(), "volume") - s, err := CreateWALStore(path, 8192, 4096) + s, err := CreateWALStore(path, 262144, 4096) if err != nil { t.Fatal(err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2c6706d810..c94cedf021 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -531,7 +531,7 @@ Notes: | ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | |---|---|---|---|---|---|---| -| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateCreatesAllocatedUnwrittenVolume`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | +| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | ## Part C. Change rules From 33904ff61d75dca413f04504a86fb058c08b5c61 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:36:11 -0800 Subject: [PATCH 34/35] test(storage): expose create-policy side effects and sync control lifetime gaps --- .../core/storage/data_sync_linux_test.go | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index c040f2287f..2c87bcfa9d 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -11,6 +11,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "syscall" "testing" "time" @@ -64,6 +65,12 @@ func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { + if os.Getenv("SWBLOCK_TEST_SYNC_CHILD_FAILURE") == "1" { + _ = os.Stdout.Close() + time.Sleep(30 * time.Millisecond) + fmt.Fprintln(os.Stderr, "SYNC_CHILD_FAILURE_SETTLED") + os.Exit(7) + } opts := WALStoreOptions{} if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { opts.WMode = WModeStrict @@ -72,6 +79,9 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if e != nil { panic(e) } + if os.Getenv("SWBLOCK_PREZERO") == "0" && verifyInitializedFile(s.fd) == nil { + panic("sparse crash arm was silently prezeroed") + } s.DisableAutoFlushForRecoveryTest() if _, e = s.Recover(); e != nil { panic(e) @@ -219,3 +229,68 @@ func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { t.Fatalf("default volume lost sparse allocation: allocated=%d size=%d", allocated, info.Size()) } } + +func TestInvalidCreatePolicyLeavesNoFileAndAllowsRetry(t *testing.T) { + for _, tc := range []struct{ name, sync, allocation, prezero string }{ + {"sync-before-prezero", "bad", "prezero", "1"}, + {"allocation", "fdatasync", "bad", "0"}, + {"fallocate", "fdatasync", "fallocate", "0"}, + {"prezero", "fdatasync", "", "bad"}, + {"conflict", "fdatasync", "sparse", "1"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", tc.sync) + t.Setenv("SWBLOCK_ALLOCATION", tc.allocation) + t.Setenv("SWBLOCK_PREZERO", tc.prezero) + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStore(path, 32, 4096) + if err == nil { + s.Close() + t.Fatal("invalid policy accepted") + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("invalid policy touched volume before refusal: %v", err) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_ALLOCATION", "sparse") + t.Setenv("SWBLOCK_PREZERO", "0") + s, err = CreateWALStore(path, 32, 4096) + if err != nil { + t.Fatalf("corrected retry failed: %v", err) + } + s.Close() + }) + } +} + +func TestSyncCrashFailureDiagnosticsWaitForStderr(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=1", "SWBLOCK_ALLOCATION=", "SWBLOCK_PREZERO=0") + out, err := cmd.CombinedOutput() + if err == nil || ctx.Err() != nil { + t.Fatalf("wrong failed-child outcome: %v %v", err, ctx.Err()) + } + if !strings.Contains(string(out), "SYNC_CHILD_FAILURE_SETTLED") || strings.Contains(string(out), "WARNING: DATA RACE") { + t.Fatalf("failure diagnostics read before child settlement: %s", out) + } +} + +func TestSyncControlsIgnoreAmbientAllocation(t *testing.T) { + for _, tc := range []struct{ name, test, allocation string }{ + {"prezero", "TestPrezeroCreatesInitializedVolume", "sparse"}, + {"crash-matrix", "TestFdatasyncAcknowledgedWritesSurviveSIGKILL", "prezero"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + 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") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("ambient allocation contaminated control: %v: %s", err, out) + } + }) + } +} From 5a50d30dddbd5a1e8ed74408be949048c3b46ac3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 06:38:01 -0800 Subject: [PATCH 35/35] fix(storage): validate creation policy before file ownership and settle sync helpers --- seaweed-block/core/storage/data_sync.go | 62 +++++++++++++------ .../core/storage/data_sync_linux_test.go | 21 ++++--- seaweed-block/core/storage/walstore.go | 9 ++- seaweed-block/core/storage/walstore_v3.go | 3 + 4 files changed, 68 insertions(+), 27 deletions(-) diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index ee6efd7a46..c09081897c 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -9,50 +9,74 @@ import ( // Data-only sync applies to WAL/extent data on Linux by default. Descriptor slots, // chunk maps, creation and directory operations retain full fsync. -func newDataFileSync(f *os.File) (func() error, error) { +func configuredDataSyncMode() (string, error) { mode := os.Getenv("SWBLOCK_SYNC") if mode == "" { mode = defaultDataFileSyncMode } switch mode { case "fsync": - return f.Sync, nil + return mode, nil case "fdatasync": - if err := dataSyncSupported(); err != nil { - return nil, err - } - log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) - return func() error { return fdatasyncFile(f) }, nil + return mode, dataSyncSupported() default: - return nil, fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) + return "", fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) } } -// Only newly-created files reach this hook: existing volume bytes are never -// rewritten. Writing zeros (not fallocate) converts unwritten extents too. -func prezeroNewStore(f *os.File, size int64) error { +func newDataFileSync(f *os.File) (func() error, error) { + mode, err := configuredDataSyncMode() + if err != nil { + return nil, err + } + if mode == "fsync" { + return f.Sync, nil + } + log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) + return func() error { return fdatasyncFile(f) }, nil +} + +// Configuration errors must not create or initialize a volume file. +func validateNewStorePolicy() error { + if _, err := configuredDataSyncMode(); err != nil { + return err + } + _, err := configuredAllocationMode() + return err +} + +func configuredAllocationMode() (string, error) { mode := os.Getenv("SWBLOCK_ALLOCATION") prezero := os.Getenv("SWBLOCK_PREZERO") if prezero != "" && prezero != "0" && prezero != "1" { - return fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) + return "", fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) } if prezero == "1" { if mode != "" && mode != "prezero" { - return fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) + return "", fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) } mode = "prezero" } switch mode { case "", "sparse": - return nil + return "sparse", nil case "fallocate": - return fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") + return "", fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") case "prezero": - if err := dataSyncSupported(); err != nil { - return err - } + return mode, dataSyncSupported() default: - return fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) + return "", fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) + } +} + +// Only newly-created files reach this hook; existing bytes are never rewritten. +func prezeroNewStore(f *os.File, size int64) error { + mode, err := configuredAllocationMode() + if err != nil { + return err + } + if mode == "sparse" { + return nil } zero := make([]byte, 1<<20) for off := int64(0); off < size; { diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go index 2c87bcfa9d..e91897834f 100644 --- a/seaweed-block/core/storage/data_sync_linux_test.go +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -12,12 +12,14 @@ import ( "os/exec" "path/filepath" "strings" + "sync" "syscall" "testing" "time" ) func TestPrezeroCreatesInitializedVolume(t *testing.T) { + t.Setenv("SWBLOCK_ALLOCATION", "") t.Setenv("SWBLOCK_SYNC", "fdatasync") t.Setenv("SWBLOCK_PREZERO", "1") path := filepath.Join(t.TempDir(), "volume") @@ -112,7 +114,7 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") - cmd.Env = append(os.Environ(), "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) + cmd.Env = append(os.Environ(), "SWBLOCK_ALLOCATION=", "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) out, e := cmd.StdoutPipe() if e != nil { t.Fatal(e) @@ -122,7 +124,10 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { if e = cmd.Start(); e != nil { t.Fatal(e) } - defer func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }() + var waitOnce sync.Once + var waitErr error + wait := func() { waitOnce.Do(func() { waitErr = cmd.Wait() }) } + defer func() { _ = cmd.Process.Kill(); wait() }() scan := bufio.NewScanner(out) ready := false for scan.Scan() { @@ -132,20 +137,22 @@ func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { } } if !ready { - t.Fatalf("no sync ACK: %v %s", scan.Err(), stderr.String()) + wait() + t.Fatalf("no sync ACK: scan=%v wait=%v %s", scan.Err(), waitErr, stderr.String()) } if e = cmd.Process.Kill(); e != nil { t.Fatal(e) } - e = cmd.Wait() - exit, ok := e.(*exec.ExitError) + wait() + exit, ok := waitErr.(*exec.ExitError) if !ok { - t.Fatalf("not killed: %v", e) + t.Fatalf("not killed: %v", waitErr) } status, ok := exit.Sys().(syscall.WaitStatus) if !ok || status.Signal() != syscall.SIGKILL { - t.Fatalf("wrong exit: %v", e) + t.Fatalf("wrong exit: %v", waitErr) } + t.Setenv("SWBLOCK_ALLOCATION", "") t.Setenv("SWBLOCK_SYNC", "fdatasync") t.Setenv("SWBLOCK_PREZERO", prezero) s, e := OpenWALStore(path) diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index bba62eb0a8..29104f42fb 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -209,6 +209,9 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt // Frozen constructor for legacy-format regression fixtures; public Create // never reaches it after activation. Removed from production in row 14a. func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opts WALStoreOptions) (*WALStore, error) { + if err := validateNewStorePolicy(); err != nil { + return nil, err + } if blockSize == 0 { blockSize = DefaultBlockSize } @@ -254,7 +257,11 @@ func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize in _ = f.Close() return nil, fmt.Errorf("storage: fsync after create: %w", err) } - return openInitializedWithMetadata(path, f, &sb, metadata) + s, err := openInitializedWithMetadata(path, f, &sb, metadata) + if err != nil { + _ = f.Close() + } + return s, err } // OpenWALStore opens an existing store file WITHOUT recovering it. diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 716edeb1e9..9c61731325 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -231,6 +231,9 @@ func createWALStoreV3MapAtCursorForTest(path string, numBlocks, blockSize uint32 } func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSize uint64, mode WMode, cursor, chunkBlocks uint64, opts WALStoreOptions) (*WALStore, error) { + if err := validateNewStorePolicy(); err != nil { + return nil, err + } d := descriptorV3{ ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, VolumeSize: uint64(numBlocks) * uint64(blockSize), ExtentSize: 64 * 1024, BlockSize: blockSize,