diff --git a/seaweed-block/core/storage/descriptor_v3.go b/seaweed-block/core/storage/descriptor_v3.go new file mode 100644 index 0000000000..6547de5789 --- /dev/null +++ b/seaweed-block/core/storage/descriptor_v3.go @@ -0,0 +1,276 @@ +package storage + +import ( + "errors" + "fmt" + "sync" +) + +// The single v3 descriptor publisher (format bump v3, DESIGN r15 sections +// 4, 5 and 5.1; plan row 3). +// +// Every v3 descriptor change goes through descriptorPublisherV3.publish: +// Sync W, checkpoint, metadata-only rollover, seed, BASE transitions and +// reset. It is dark until the v3 store is wired in (plan rows 4 and 5) and +// activated (row 12b); the v2 checkpoint path in walstore.go is unchanged. +// +// Lock graph (DESIGN 4), the only order: +// +// metadata callbacks (run by the caller first, holding none of these) +// -> WALStore.mu (snapshot only, released before slot I/O) +// -> descMu +// -> fileSyncMu (leaf, inside syncFile) +// +// Nothing below descMu is ever held while acquiring WALStore.mu, and no +// callback runs under descMu or fileSyncMu. + +var ( + // errDescriptorIdentityChange: a publication tried to change the + // store identity or geometry, which no v3 publication may do. + errDescriptorIdentityChange = errors.New("storage: v3 descriptor identity or geometry change refused") + // errDescriptorTransition: a publication asked for a BASE, map, nonce + // or bounds change that DESIGN 5/8.5 does not allow. + errDescriptorTransition = errors.New("storage: v3 descriptor transition refused") +) + +// descriptorIOV3 is the store I/O the publisher needs. writeSlot does one +// pwrite of a whole slot; syncFile runs the store's leaf (pwrite + fsync +// under fileSyncMu, latching the sticky fault on fsync failure); sticky +// reports a latched fault. +type descriptorIOV3 struct { + writeSlot func(off int64, b []byte) error + fsync func() error + syncFile func(write, sync func() error) error + sticky func() error +} + +// descriptorPublisherV3 holds the authoritative in-memory descriptor and +// the contents of the fallback slot, which pins reuse (DESIGN 5). +type descriptorPublisherV3 struct { + descMu sync.Mutex + + cur descriptorV3 // selected slot: authoritative + curSlot slotIDV3 + other descriptorV3 // fallback slot, when valid + otherValid bool + + io descriptorIOV3 + accept slotImplAcceptor + + // trace, when set by a test, records lock acquisitions and releases + // in order (the section 11 item 9 lock recorder). + trace func(event string) +} + +func newDescriptorPublisherV3(cur descriptorV3, curSlot slotIDV3, other *descriptorV3, io descriptorIOV3) *descriptorPublisherV3 { + p := &descriptorPublisherV3{cur: cur, curSlot: curSlot, io: io} + if other != nil { + p.other, p.otherValid = *other, true + } + return p +} + +func (p *descriptorPublisherV3) note(event string) { + if p.trace != nil { + p.trace(event) + } +} + +// current returns the authoritative descriptor. +func (p *descriptorPublisherV3) current() descriptorV3 { + p.descMu.Lock() + defer p.descMu.Unlock() + return p.cur +} + +// reuseFloor is the lowest logical WAL position still referenced by a valid +// slot (DESIGN 5): min of both tails when both carry the same nonce. With +// mixed nonces (a reset between its two publications, DESIGN 8.6) tails are +// not comparable and ok is false: nothing may be reused. +func (p *descriptorPublisherV3) reuseFloor() (floor uint64, ok bool) { + p.descMu.Lock() + defer p.descMu.Unlock() + return p.reuseFloorLocked() +} + +func (p *descriptorPublisherV3) reuseFloorLocked() (uint64, bool) { + if !p.otherValid { + return p.cur.RetainedTail, true + } + if p.other.Nonce != p.cur.Nonce { + return 0, false + } + return min(p.cur.RetainedTail, p.other.RetainedTail), true +} + +// publish is publishDescriptor (DESIGN 5). Callers run their metadata +// callbacks before calling it. If storeMu is non-nil it is taken first, +// snap runs under it, then descMu is taken and storeMu released before any +// slot I/O. mutate edits a copy of the CURRENT authoritative descriptor, +// never a caller's snapshot; the publisher then applies the monotonic merge +// and the transition rules, validates the whole result and writes it into +// the fallback slot with slotGen+1. +func (p *descriptorPublisherV3) publish(storeMu sync.Locker, snap func(), mutate func(next *descriptorV3) error) (descriptorV3, error) { + if storeMu != nil { + storeMu.Lock() + p.note("lock WALStore.mu") + if snap != nil { + snap() + } + p.descMu.Lock() + p.note("lock descMu") + storeMu.Unlock() + p.note("unlock WALStore.mu") + } else { + p.descMu.Lock() + p.note("lock descMu") + } + defer func() { + p.note("unlock descMu") + p.descMu.Unlock() + }() + return p.publishLocked(mutate) +} + +func (p *descriptorPublisherV3) publishLocked(mutate func(next *descriptorV3) error) (descriptorV3, error) { + if err := p.io.sticky(); err != nil { + return descriptorV3{}, err + } + next := p.cur + if mutate != nil { + if err := mutate(&next); err != nil { + return descriptorV3{}, err + } + } + if err := mergeDescriptorV3(&p.cur, &next); err != nil { + return descriptorV3{}, err + } + gen, err := nextSlotGenV3(p.cur.SlotGen) + if err != nil { + return descriptorV3{}, err + } + next.SlotGen = gen + next.MigrationPhase = MigrationNormal + if err := next.validate(p.accept); err != nil { + return descriptorV3{}, err + } + target := slotB + off := int64(slotBOffsetV3) + if p.curSlot == slotB { + target, off = slotA, slotAOffsetV3 + } + buf := next.encode() + err = p.io.syncFile(func() error { + p.note("hold fileSyncMu") + return p.io.writeSlot(off, buf) + }, p.io.fsync) + if err != nil { + return descriptorV3{}, err + } + // Success boundary: a fault latched by another path while this + // publication was in flight still refuses it (#172). + if err := p.io.sticky(); err != nil { + return descriptorV3{}, err + } + p.other, p.otherValid = p.cur, true + p.cur, p.curSlot = next, target + return next, nil +} + +// mergeDescriptorV3 applies the monotonic merge and transition rules of +// DESIGN 5 and 8.5 to next, a mutated copy of cur. +func mergeDescriptorV3(cur, next *descriptorV3) error { + if next.ImplKind != cur.ImplKind || next.ImplVersion != cur.ImplVersion || next.UUID != cur.UUID || + next.CreatedAt != cur.CreatedAt || !sameGeometryV3(*cur, *next) { + return errDescriptorIdentityChange + } + // W and CheckpointLSN are max-merged: a stale request never lowers them. + next.W = max(cur.W, next.W) + next.CheckpointLSN = max(cur.CheckpointLSN, next.CheckpointLSN) + // The nonce changes only through the reset transaction (DESIGN 8.6, + // plan row 8); within one nonce the retained bounds never move back. + if next.Nonce != cur.Nonce { + return fmt.Errorf("%w: nonce change outside a reset", errDescriptorTransition) + } + if next.RetainedTail < cur.RetainedTail { + return fmt.Errorf("%w: retainedTail %d below %d", errDescriptorTransition, next.RetainedTail, cur.RetainedTail) + } + // The map root changes only to a strictly higher generation; the full + // coverage predicates against the root are added by plan row 7. + if next.MapGeneration != cur.MapGeneration || next.MapRootLocator != cur.MapRootLocator || + next.MapRootHash != cur.MapRootHash || next.MapCoveredCheckpoint != cur.MapCoveredCheckpoint || + next.MapLineage != cur.MapLineage || next.MapFormatID != cur.MapFormatID { + if next.MapGeneration <= cur.MapGeneration { + return fmt.Errorf("%w: map root change without a higher generation (%d -> %d)", + errDescriptorTransition, cur.MapGeneration, next.MapGeneration) + } + if next.MapLineage != cur.MapLineage { + return fmt.Errorf("%w: map lineage change outside an install or reset", errDescriptorTransition) + } + } + if next.WMode != cur.WMode && next.WMode != WModeLagged && next.WMode != WModeStrict { + return fmt.Errorf("%w: WMode %d", errDescriptorTransition, next.WMode) + } + return baseTransitionAllowedV3(cur, next) +} + +// baseTransitionAllowedV3 is the DESIGN 8.5 edge table. The conditions an +// edge needs (coverage, destructive mutation, drain) are enforced by the +// install callers (plan rows 9 to 11); this refuses every other edge. +func baseTransitionAllowedV3(cur, next *descriptorV3) error { + same := next.BaseState == cur.BaseState && next.BaseLSN == cur.BaseLSN && + next.BaseCursor == cur.BaseCursor && next.BaseInstallID == cur.BaseInstallID + if same { + return nil + } + ok := false + switch cur.BaseState { + case BaseNone: + ok = next.BaseState == BaseInstalling + case BaseInstalling: + switch next.BaseState { + case BaseInstalling: + ok = next.BaseInstallID != cur.BaseInstallID // superseding begin + case BaseInstalled: + ok = next.BaseInstallID == cur.BaseInstallID && next.BaseLSN == cur.BaseLSN + case BaseNone: + ok = true // abort; its preconditions are the caller's (8.5) + } + case BaseInstalled: + switch next.BaseState { + case BaseInstalled: + // Retirement may clear BaseCursor below the tail; the ID and + // BaseLSN stay. + ok = next.BaseInstallID == cur.BaseInstallID && next.BaseLSN == cur.BaseLSN + case BaseInstalling: + ok = next.BaseInstallID != cur.BaseInstallID // a new install begins + case BaseNone: + ok = next.BaseLSN == 0 && next.CheckpointLSN >= cur.BaseLSN + } + } + if !ok { + return fmt.Errorf("%w: BASE %d -> %d", errDescriptorTransition, cur.BaseState, next.BaseState) + } + return nil +} + +// rolloverIfPinned is the metadata-only rollover (DESIGN 5.1): when the +// fallback slot still pins reuse below the selected tail, republish the +// current descriptor unchanged into the fallback slot so both carry the new +// tail. It needs no record, Sync, guest write or checkpoint change. It +// reports whether it published. +func (p *descriptorPublisherV3) rolloverIfPinned() (bool, error) { + p.note("lock descMu") + p.descMu.Lock() + defer func() { + p.note("unlock descMu") + p.descMu.Unlock() + }() + if !p.otherValid || p.other.Nonce != p.cur.Nonce || p.other.RetainedTail >= p.cur.RetainedTail { + return false, nil + } + if _, err := p.publishLocked(nil); err != nil { + return false, err + } + return true, nil +} diff --git a/seaweed-block/core/storage/descriptor_v3_test.go b/seaweed-block/core/storage/descriptor_v3_test.go new file mode 100644 index 0000000000..70d82dfb03 --- /dev/null +++ b/seaweed-block/core/storage/descriptor_v3_test.go @@ -0,0 +1,384 @@ +package storage + +import ( + "errors" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" +) + +// Row 3 (DESIGN r15 sections 4, 5, 5.1) controls for the v3 descriptor +// publisher, against a real file through a syncFile leaf that behaves like +// WALStore.syncFile (fileSyncMu, sticky latch on fsync failure). + +type descHarnessV3 struct { + t *testing.T + f *os.File + fileSyncMu sync.Mutex + fault atomic.Pointer[error] + fsyncErr atomic.Pointer[error] + afterFsync func() // test hook inside the leaf, after a successful fsync + storeMu sync.Mutex + pub *descriptorPublisherV3 +} + +func newDescHarnessV3(t *testing.T) *descHarnessV3 { + t.Helper() + f, err := os.Create(filepath.Join(t.TempDir(), "store.v3")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = f.Close() }) + ref := readSlotVector(t, "slot-ref") + if _, err := f.WriteAt(ref, slotAOffsetV3); err != nil { + t.Fatal(err) + } + if _, err := f.WriteAt(make([]byte, slotSizeV3), slotBOffsetV3); err != nil { + t.Fatal(err) + } + d, err := decodeSlotV3(ref, nil) + if err != nil { + t.Fatal(err) + } + h := &descHarnessV3{t: t, f: f} + h.pub = newDescriptorPublisherV3(d, slotA, nil, descriptorIOV3{ + writeSlot: func(off int64, b []byte) error { _, err := f.WriteAt(b, off); return err }, + fsync: func() error { + if e := h.fsyncErr.Load(); e != nil { + return *e + } + return f.Sync() + }, + syncFile: func(write, sync func() error) error { + h.fileSyncMu.Lock() + defer h.fileSyncMu.Unlock() + if e := h.fault.Load(); e != nil { + return *e + } + if err := write(); err != nil { + return err + } + if err := sync(); err != nil { + h.fault.CompareAndSwap(nil, &err) + return err + } + if h.afterFsync != nil { + h.afterFsync() + } + return nil + }, + sticky: func() error { + if e := h.fault.Load(); e != nil { + return *e + } + return nil + }, + }) + return h +} + +// onDisk selects from the file's two slots, as a reopen would. +func (h *descHarnessV3) onDisk() (descriptorV3, slotIDV3) { + h.t.Helper() + a := make([]byte, slotSizeV3) + b := make([]byte, slotSizeV3) + if _, err := h.f.ReadAt(a, slotAOffsetV3); err != nil { + h.t.Fatal(err) + } + if _, err := h.f.ReadAt(b, slotBOffsetV3); err != nil { + h.t.Fatal(err) + } + d, id, err := selectSlotV3(a, b, nil) + if err != nil { + h.t.Fatal(err) + } + return d, id +} + +func setW(w uint64) func(*descriptorV3) error { + return func(d *descriptorV3) error { d.W = w; return nil } +} + +func TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest(t *testing.T) { + h := newDescHarnessV3(t) + d, err := h.pub.publish(&h.storeMu, nil, setW(9)) + if err != nil { + t.Fatal(err) + } + if d.SlotGen != 2 || d.W != 9 { + t.Fatalf("published gen %d W %d, want gen 2 W 9", d.SlotGen, d.W) + } + if got, id := h.onDisk(); id != slotB || got.SlotGen != 2 || got.W != 9 { + t.Fatalf("reopen selects slot %d gen %d W %d, want B gen 2 W 9", id, got.SlotGen, got.W) + } + if _, err := h.pub.publish(&h.storeMu, nil, setW(11)); err != nil { + t.Fatal(err) + } + if got, id := h.onDisk(); id != slotA || got.SlotGen != 3 || got.W != 11 { + t.Fatalf("reopen selects slot %d gen %d W %d, want A gen 3 W 11", id, got.SlotGen, got.W) + } +} + +func TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, setW(20)); err != nil { + t.Fatal(err) + } + // A stale request (computed before W reached 20) never lowers W or the + // checkpoint. + d, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.W, n.CheckpointLSN = 12, 3 + return nil + }) + if err != nil { + t.Fatal(err) + } + if d.W != 20 || d.CheckpointLSN != 7 { + t.Fatalf("stale request regressed W %d / checkpoint %d, want 20 / 7", d.W, d.CheckpointLSN) + } + before := h.pub.current() + refused := []struct { + name string + mutate func(*descriptorV3) error + want error + }{ + {"identity", func(n *descriptorV3) error { n.UUID[0] ^= 1; return nil }, errDescriptorIdentityChange}, + {"geometry", func(n *descriptorV3) error { n.WALSize *= 2; return nil }, errDescriptorIdentityChange}, + {"nonce outside reset", func(n *descriptorV3) error { n.Nonce[0] ^= 1; return nil }, errDescriptorTransition}, + {"map root without a higher generation", func(n *descriptorV3) error { n.MapRootHash[0] ^= 1; return nil }, errDescriptorTransition}, + {"map lineage change", func(n *descriptorV3) error { + n.MapGeneration++ + n.MapLineage[0] ^= 1 + return nil + }, errDescriptorTransition}, + {"BASE none -> installed", func(n *descriptorV3) error { + n.BaseState, n.BaseLSN = BaseInstalled, 20 + n.BaseInstallID[0] = 1 + return nil + }, errDescriptorTransition}, + {"checkpoint above map coverage", func(n *descriptorV3) error { n.CheckpointLSN = 8; return nil }, errSuperblockInvalid}, + } + for _, c := range refused { + t.Run(c.name, func(t *testing.T) { + if _, err := h.pub.publish(&h.storeMu, nil, c.mutate); !errors.Is(err, c.want) { + t.Fatalf("err = %v, want %v", err, c.want) + } + if after := h.pub.current(); after != before { + t.Fatal("a refused publication changed the authoritative descriptor") + } + }) + } + // A higher map generation in the same lineage is accepted. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.MapGeneration++ + n.MapRootHash[0] ^= 1 + return nil + }); err != nil { + t.Fatalf("higher map generation refused: %v", err) + } + // Retained bounds never move back within one nonce. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail = 50 + return nil + }); !errors.Is(err, errDescriptorTransition) { + t.Fatalf("tail moved back: err = %v, want errDescriptorTransition", err) + } +} + +func TestDescriptorV3ConcurrentPublishersNeverRegress(t *testing.T) { + h := newDescHarnessV3(t) + const n = 40 + var wg sync.WaitGroup + for i := 1; i <= n; i++ { + wg.Add(1) + go func(w uint64) { + defer wg.Done() + if _, err := h.pub.publish(&h.storeMu, nil, setW(w)); err != nil { + t.Error(err) + } + }(uint64(7 + i)) + } + wg.Wait() + cur := h.pub.current() + if cur.W != 7+n || cur.SlotGen != 1+n { + t.Fatalf("after %d concurrent publications: W %d gen %d, want W %d gen %d", n, cur.W, cur.SlotGen, 7+n, 1+n) + } + if got, _ := h.onDisk(); got != cur { + t.Fatal("reopen selection differs from the authoritative descriptor") + } +} + +func TestDescriptorV3LockOrderRecorder(t *testing.T) { + h := newDescHarnessV3(t) + var events []string + var mu sync.Mutex + h.pub.trace = func(e string) { mu.Lock(); events = append(events, e); mu.Unlock() } + snapped := false + if _, err := h.pub.publish(&h.storeMu, func() { snapped = true }, setW(9)); err != nil { + t.Fatal(err) + } + if !snapped { + t.Fatal("snapshot did not run under WALStore.mu") + } + want := []string{"lock WALStore.mu", "lock descMu", "unlock WALStore.mu", "hold fileSyncMu", "unlock descMu"} + if len(events) != len(want) { + t.Fatalf("lock events %v, want %v", events, want) + } + for i := range want { + if events[i] != want[i] { + t.Fatalf("lock events %v, want %v (WALStore.mu must be released before slot I/O)", events, want) + } + } + // The store lock is not held during slot I/O: another goroutine can + // take it while the publication sits inside fileSyncMu. + h.pub.trace = nil + inLeaf := make(chan struct{}) + release := make(chan struct{}) + h.afterFsync = func() { close(inLeaf); <-release } + done := make(chan error, 1) + go func() { _, err := h.pub.publish(&h.storeMu, nil, setW(10)); done <- err }() + <-inLeaf + if !h.storeMu.TryLock() { + t.Fatal("WALStore.mu held across descriptor I/O") + } + h.storeMu.Unlock() + close(release) + if err := <-done; err != nil { + t.Fatal(err) + } +} + +func TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing(t *testing.T) { + h := newDescHarnessV3(t) + before := h.pub.current() + boom := errors.New("injected fsync failure") + h.fsyncErr.Store(&boom) + if _, err := h.pub.publish(&h.storeMu, nil, setW(9)); !errors.Is(err, boom) { + t.Fatalf("err = %v, want the fsync failure", err) + } + if h.pub.current() != before { + t.Fatal("a failed publication changed the authoritative descriptor") + } + h.fsyncErr.Store(nil) + if _, err := h.pub.publish(&h.storeMu, nil, setW(10)); !errors.Is(err, boom) { + t.Fatalf("publication after a latched fault: err = %v, want the latched fault", err) + } +} + +func TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary(t *testing.T) { + h := newDescHarnessV3(t) + before := h.pub.current() + other := errors.New("fault latched by another path") + h.afterFsync = func() { h.fault.CompareAndSwap(nil, &other) } + if _, err := h.pub.publish(&h.storeMu, nil, setW(9)); !errors.Is(err, other) { + t.Fatalf("err = %v, want the concurrently latched fault", err) + } + if h.pub.current() != before { + t.Fatal("a publication refused at the success boundary changed the descriptor") + } +} + +func TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange(t *testing.T) { + h := newDescHarnessV3(t) + // A checkpoint publishes tail = head = 100 (a full ring of 100 bytes + // retired): the fallback slot still pins tail 0. + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + if floor, ok := h.pub.reuseFloor(); !ok || floor != 0 { + t.Fatalf("floor after the checkpoint = %d (ok %v), want 0: the fallback pins it", floor, ok) + } + beforeW, beforeCkpt := h.pub.current().W, h.pub.current().CheckpointLSN + published, err := h.pub.rolloverIfPinned() + if err != nil || !published { + t.Fatalf("rollover: published %v err %v, want a metadata-only publication", published, err) + } + cur := h.pub.current() + if cur.W != beforeW || cur.CheckpointLSN != beforeCkpt || cur.RetainedTail != 100 { + t.Fatal("rollover changed W, the checkpoint or the tail") + } + if floor, ok := h.pub.reuseFloor(); !ok || floor != 100 { + t.Fatalf("floor after rollover = %d (ok %v), want 100", floor, ok) + } + if again, err := h.pub.rolloverIfPinned(); err != nil || again { + t.Fatalf("second rollover: published %v err %v, want nothing to do", again, err) + } +} + +func TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned(t *testing.T) { + h := newDescHarnessV3(t) + if _, err := h.pub.publish(&h.storeMu, nil, func(n *descriptorV3) error { + n.RetainedTail, n.RetainedHead = 100, 100 + return nil + }); err != nil { + t.Fatal(err) + } + boom := errors.New("injected fsync failure") + h.fsyncErr.Store(&boom) + if _, err := h.pub.rolloverIfPinned(); !errors.Is(err, boom) { + t.Fatalf("rollover err = %v, want the fsync failure", err) + } + if floor, _ := h.pub.reuseFloor(); floor != 0 { + t.Fatalf("floor = %d after a failed rollover, want 0 (still pinned)", floor) + } +} + +func TestDescriptorV3MixedNoncesNeverYieldAReuseFloor(t *testing.T) { + h := newDescHarnessV3(t) + old := h.pub.current() + old.Nonce[0] ^= 0xFF + h.pub.other, h.pub.otherValid = old, true + if _, ok := h.pub.reuseFloor(); ok { + t.Fatal("a reuse floor was computed across different nonces") + } + if published, err := h.pub.rolloverIfPinned(); err != nil || published { + t.Fatalf("rollover across nonces: published %v err %v, want nothing", published, err) + } +} + +func TestDescriptorV3BaseTransitionTable(t *testing.T) { + id1 := [16]byte{1} + id2 := [16]byte{2} + mk := func(state BaseState, lsn uint64, id [16]byte) descriptorV3 { + return descriptorV3{BaseState: state, BaseLSN: lsn, BaseInstallID: id, CheckpointLSN: 7} + } + cases := []struct { + name string + cur, nxt descriptorV3 + ok bool + }{ + {"none -> installing", mk(BaseNone, 0, [16]byte{}), mk(BaseInstalling, 50, id1), true}, + {"installing -> installed same ID", mk(BaseInstalling, 50, id1), mk(BaseInstalled, 50, id1), true}, + {"installing -> installed other ID", mk(BaseInstalling, 50, id1), mk(BaseInstalled, 50, id2), false}, + {"installing -> superseding installing", mk(BaseInstalling, 50, id1), mk(BaseInstalling, 60, id2), true}, + {"installing -> installing same ID new BaseLSN", mk(BaseInstalling, 50, id1), mk(BaseInstalling, 60, id1), false}, + {"installing -> none (abort)", mk(BaseInstalling, 50, id1), mk(BaseNone, 0, [16]byte{}), true}, + {"none -> installed", mk(BaseNone, 0, [16]byte{}), mk(BaseInstalled, 50, id1), false}, + {"installed -> none needs checkpoint past BaseLSN", mk(BaseInstalled, 50, id1), mk(BaseNone, 0, [16]byte{}), false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := baseTransitionAllowedV3(&c.cur, &c.nxt) + if (err == nil) != c.ok { + t.Fatalf("err = %v, want allowed = %v", err, c.ok) + } + }) + } + cur := mk(BaseInstalled, 50, id1) + nxt := mk(BaseNone, 0, [16]byte{}) + nxt.CheckpointLSN = 50 + if err := baseTransitionAllowedV3(&cur, &nxt); err != nil { + t.Fatalf("installed -> none with the checkpoint at BaseLSN refused: %v", err) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 677149cf46..3b489be397 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -258,7 +258,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th ## Part B. Invariant ledger -73 rows: 69 ACTIVE, 4 STUB; 15 kept from the internal ledger, 58 new. +74 rows: 69 ACTIVE, 5 STUB; 15 kept from the internal ledger, 59 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. @@ -280,6 +280,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-RECORD-001` | A dark impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 (v3 codec only; no production transition yet) | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5. A failed fsync or a fault latched mid-flight publishes nothing. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | — | STUB | | `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | | `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | @@ -288,6 +289,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-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`). ### B.2 Core: authority and epochs