diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 7e922154f5..204709474a 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -1,6 +1,7 @@ package transport import ( + "crypto/rand" "fmt" "log" "net" @@ -308,17 +309,33 @@ func (r *ReplicaListener) acceptLoop() { func (r *ReplicaListener) handleConn(conn net.Conn) { defer conn.Close() lane := mutationLaneLive - basePrepared := false - prepareBaseInstall := func() error { - if basePrepared { + // The legacy single-lane rebuild is the second BASE-install caller + // (DESIGN r17.4 section 8.7): the first admitted rebuild message of a + // connection begins one install at its frontier hint under a fresh + // random ID; a reconnect is a new connection and so a superseding + // install. Stores without the seam keep their pre-seam behaviour behind + // the legacy handle (lazy BaseStager staging, WriteExtentDirect, + // AdvanceFrontier at completion). + var install storage.InstallHandle + var installBase uint64 + beginInstall := func(hint uint64) error { + if install != nil { + if hint != installBase { + return fmt.Errorf("rebuild frontier hint %d differs from the install's BaseLSN %d", hint, installBase) + } return nil } - if stager, ok := r.store.(storage.BaseStager); ok { - if err := stager.BeginBaseStage(); err != nil { + var id [16]byte + for id == ([16]byte{}) { + if _, err := rand.Read(id[:]); err != nil { return err } } - basePrepared = true + h, err := storage.BeginInstall(r.store, hint, id) + if err != nil { + return err + } + install, installBase = h, hint return nil } @@ -442,11 +459,11 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { // Rebuild blocks are BASE-lane bytes. They must not enter the // WAL apply path and must not advance R/S/H per block; the // frontier is reconciled once, at MsgRebuildDone. - if err := prepareBaseInstall(); err != nil { - log.Printf("replica: prepare rebuild base: %v", err) + if err := beginInstall(lineage.EffectiveFrontierHint()); err != nil { + log.Printf("replica: begin rebuild base: %v", err) return true } - if err := r.store.WriteExtentDirect(lba, data); err != nil { + if err := install.WriteBase(lba, data); err != nil { log.Printf("replica: apply rebuild base block: %v", err) return true } @@ -462,15 +479,24 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true } - if err := prepareBaseInstall(); err != nil { - log.Printf("replica: prepare empty rebuild base: %v", err) + // Done (DESIGN 8.7): an empty rebuild begins here; the hint must + // equal the install's BaseLSN; then complete, then the logical + // Sync, which is ordinary once installed. A failed completion or + // Sync closes the connection with no MsgBarrierResp, so the + // primary never sees an AchievedLSN from a failed call. + if err := beginInstall(lineage.EffectiveFrontierHint()); err != nil { + log.Printf("replica: begin rebuild base at done: %v", err) + return true + } + if err := install.MarkBaseComplete(); err != nil { + log.Printf("replica: complete rebuild base: %v", err) + return true + } + frontier, err := r.store.Sync() + if err != nil { + log.Printf("replica: sync after rebuild done: %v", err) return true } - // The done message carries the engine's frozen base frontier hint. - // Advance the replica's frontier metadata without touching - // any block data — AdvanceFrontier only updates nextLSN/walHead. - r.store.AdvanceFrontier(lineage.EffectiveFrontierHint()) - frontier, _ := r.store.Sync() // Echo the request's full lineage in the rebuild-done ack // so primary-side validators can consume it. resp := EncodeBarrierResp(BarrierResponse{ diff --git a/seaweed-block/core/transport/replica_install_format_v3_test.go b/seaweed-block/core/transport/replica_install_format_v3_test.go new file mode 100644 index 0000000000..5050dd6238 --- /dev/null +++ b/seaweed-block/core/transport/replica_install_format_v3_test.go @@ -0,0 +1,291 @@ +//go:build swblock_format_v3_test + +package transport + +import ( + "bytes" + "errors" + "net" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Plan row 10b controls (DESIGN r17.4 section 8.7, caller 2; owner +// claude03): the legacy single-lane rebuild on a dark v3 replica. The +// first admitted rebuild message begins one install at its frontier hint; +// blocks go through the handle; done completes, then Syncs, and a failure +// closes the connection with no MsgBarrierResp. + +const v3RepBlock = 4096 + +func v3Rep(t *testing.T) *storage.WALStore { + t.Helper() + s, err := storage.CreateWALStoreV3Test(filepath.Join(t.TempDir(), "replica.v3"), 64, v3RepBlock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + return s +} + +func v3Listen(t *testing.T, store storage.LogicalStorage) *ReplicaListener { + t.Helper() + l, err := NewReplicaListener("127.0.0.1:0", store) + if err != nil { + t.Fatal(err) + } + l.Serve() + t.Cleanup(func() { l.Stop() }) + return l +} + +func v3Dial(t *testing.T, l *ReplicaListener) net.Conn { + t.Helper() + c, err := net.Dial("tcp", l.Addr()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + return c +} + +func v3RepBlk(b byte) []byte { return bytes.Repeat([]byte{b}, v3RepBlock) } + +// done sends MsgRebuildDone and returns the BarrierResp, or ok=false when +// the replica closed the connection without one. +func v3Done(t *testing.T, c net.Conn, l RecoveryLineage) (BarrierResponse, bool) { + t.Helper() + if err := WriteMsg(c, MsgRebuildDone, EncodeLineage(l)); err != nil { + t.Fatal(err) + } + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + mt, payload, err := ReadMsg(c) + if err != nil { + var ne net.Error + if errors.As(err, &ne) && ne.Timeout() { + t.Fatal("no reply and no close after MsgRebuildDone") + } + return BarrierResponse{}, false + } + if mt != MsgBarrierResp { + t.Fatalf("reply %d, want MsgBarrierResp", mt) + } + r, err := DecodeBarrierResp(payload) + if err != nil { + t.Fatal(err) + } + return r, true +} + +func v3Read(t *testing.T, s *storage.WALStore, lba uint32) []byte { + t.Helper() + b, err := s.Read(lba) + if err != nil { + t.Fatal(err) + } + return b +} + +// The positive and the empty rebuild through the replica handler: installed, +// AchievedLSN = the hint, the blocks readable. Mutants: no begin (the +// unanchored jump: the store-level direct write is refused on v3) and no +// MarkBaseComplete (the achieved-0 shape: the gated Sync fails the done +// path and nothing is replied) both fail here. +func TestReplicaV3LegacyRebuildInstallsThroughTheHandle(t *testing.T) { + for _, empty := range []bool{false, true} { + name := "blocks" + if empty { + name = "empty" + } + t.Run(name, func(t *testing.T) { + s := v3Rep(t) + l := v3Listen(t, s) + c := v3Dial(t, l) + lin := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if !empty { + for lba := uint32(0); lba < 3; lba++ { + if err := WriteMsg(c, MsgRebuildBlock, EncodeRebuildBlock(lin, lba, v3RepBlk(0x10+byte(lba)))); err != nil { + t.Fatal(err) + } + } + } + resp, ok := v3Done(t, c, lin) + if !ok || resp.AchievedLSN != 5 { + t.Fatalf("done: replied %v, AchievedLSN %d, want 5", ok, resp.AchievedLSN) + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalled { + t.Fatalf("state %d, want installed", st) + } + if !empty { + for lba := uint32(0); lba < 3; lba++ { + if got := v3Read(t, s, lba); !bytes.Equal(got, v3RepBlk(0x10+byte(lba))) { + t.Fatalf("LBA %d = %x...", lba, got[0]) + } + } + } + }) + } +} + +// The actual caller: BlockExecutor.StartRebuild -> doRebuild -> the +// replica handler, onto a dark v3 replica. The session closes successfully +// and the replica holds the primary's blocks, installed. +func TestReplicaV3RebuildThroughTheBlockExecutor(t *testing.T) { + primary := storage.NewBlockStore(64, v3RepBlock) + for lba := uint32(0); lba < 4; lba++ { + if _, err := primary.Write(lba, v3RepBlk(0x20+byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + _, _, pH := primary.Boundaries() + s := v3Rep(t) + l := v3Listen(t, s) + exec := NewBlockExecutor(primary, l.Addr()) + closeCh := make(chan adapter.SessionCloseResult, 1) + exec.SetOnSessionClose(func(r adapter.SessionCloseResult) { closeCh <- r }) + if err := exec.StartRebuild("r1", 7, 1, 1, pH); err != nil { + t.Fatal(err) + } + select { + case r := <-closeCh: + if !r.Success { + t.Fatalf("rebuild closed unsuccessfully: %+v", r) + } + case <-time.After(20 * time.Second): + t.Fatal("rebuild did not close") + } + if st, _ := storage.BaseStateV3Test(s); st != storage.BaseInstalled { + t.Fatalf("state %d, want installed", st) + } + for lba := uint32(0); lba < 4; lba++ { + if got := v3Read(t, s, lba); !bytes.Equal(got, v3RepBlk(0x20+byte(lba))) { + t.Fatalf("LBA %d = %x...", lba, got[0]) + } + } +} + +// failingDoneStore injects a done-path failure: the completion or the +// logical Sync after it. +type failingDoneStore struct { + *storage.WALStore + failComplete, failSync atomic.Bool +} + +type failingHandle struct { + storage.InstallHandle + s *failingDoneStore +} + +func (h failingHandle) MarkBaseComplete() error { + if h.s.failComplete.Load() { + return errors.New("injected MarkBaseComplete failure") + } + return h.InstallHandle.MarkBaseComplete() +} + +func (s *failingDoneStore) BeginBaseInstall(baseLSN uint64, id [16]byte) (storage.InstallHandle, error) { + h, err := s.WALStore.BeginBaseInstall(baseLSN, id) + if err != nil { + return nil, err + } + return failingHandle{InstallHandle: h, s: s}, nil +} + +func (s *failingDoneStore) Sync() (uint64, error) { + if s.failSync.Load() { + return 0, errors.New("injected Sync failure") + } + return s.WALStore.Sync() +} + +// Injected done-path failures (DESIGN 8.7): a failed MarkBaseComplete or a +// failed Sync closes the connection with no MsgBarrierResp. Mutants: a +// handler that discards either error replies and fails here. +func TestReplicaV3RebuildDoneFailureRepliesNothing(t *testing.T) { + for _, which := range []string{"complete", "sync"} { + t.Run(which, func(t *testing.T) { + s := &failingDoneStore{WALStore: v3Rep(t)} + if which == "complete" { + s.failComplete.Store(true) + } else { + s.failSync.Store(true) + } + l := v3Listen(t, s) + c := v3Dial(t, l) + lin := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if err := WriteMsg(c, MsgRebuildBlock, EncodeRebuildBlock(lin, 0, v3RepBlk(0x11))); err != nil { + t.Fatal(err) + } + if resp, ok := v3Done(t, c, lin); ok { + t.Fatalf("a failed %s replied MsgBarrierResp AchievedLSN %d", which, resp.AchievedLSN) + } + }) + } +} + +// A reconnect is a new connection and so a superseding install: refused +// unless its hint covers W (the replica acknowledged LSN 4 before the +// rebuild), allowed when it does. +func TestReplicaV3RebuildReconnectSupersedesOnlyUnderCoverage(t *testing.T) { + s := v3Rep(t) + for lba := uint32(10); lba < 14; lba++ { + if _, err := s.Write(lba, v3RepBlk(byte(lba))); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + l := v3Listen(t, s) + a := v3Dial(t, l) + linA := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 5} + if err := WriteMsg(a, MsgRebuildBlock, EncodeRebuildBlock(linA, 0, v3RepBlk(0xAA))); err != nil { + t.Fatal(err) + } + waitInstalling(t, s) + _, idA := storage.BaseStateV3Test(s) + b := v3Dial(t, l) + linB := RecoveryLineage{SessionID: 2, Epoch: 2, EndpointVersion: 2, TargetLSN: 3} // below W 4 + if err := WriteMsg(b, MsgRebuildBlock, EncodeRebuildBlock(linB, 0, v3RepBlk(0xBB))); err != nil { + t.Fatal(err) + } + if _, ok := v3Done(t, b, linB); ok { + t.Fatal("an uncovered reconnect completed") + } + if st, id := storage.BaseStateV3Test(s); st != storage.BaseInstalling || id != idA { + t.Fatalf("after the uncovered reconnect: state %d, id changed %v", st, id != idA) + } + c := v3Dial(t, l) + linC := RecoveryLineage{SessionID: 3, Epoch: 3, EndpointVersion: 3, TargetLSN: 6} + if err := WriteMsg(c, MsgRebuildBlock, EncodeRebuildBlock(linC, 0, v3RepBlk(0xCC))); err != nil { + t.Fatal(err) + } + if resp, ok := v3Done(t, c, linC); !ok || resp.AchievedLSN != 6 { + t.Fatalf("covered reconnect: replied %v AchievedLSN %d, want 6", ok, resp.AchievedLSN) + } + if got := v3Read(t, s, 0); !bytes.Equal(got, v3RepBlk(0xCC)) { + t.Fatalf("LBA 0 = %x..., want the covering install's bytes", got[0]) + } +} + +func waitInstalling(t *testing.T, s *storage.WALStore) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + if st, _ := storage.BaseStateV3Test(s); st == storage.BaseInstalling { + return + } + if time.Now().After(deadline) { + t.Fatal("the rebuild never began its install") + } + time.Sleep(5 * time.Millisecond) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 07b6410c52..fee73fdcb3 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -307,7 +307,7 @@ Notes: - `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. - `INV-FE-FLUSH-SYNC-001`: The failed-`Sync` case is asserted for ublk; for NVMe/TCP only the dispatch to `Sync` is asserted here. - `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). The legacy single-lane caller is row 10. Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; the installing reopen, the fence before a resume or superseding begin, and the same-ID resume rule are row 11. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; the installing reopen, the fence before a resume or superseding begin, and the same-ID resume rule are row 11. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). - `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. - `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. - `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`).