diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 7ba42433e5..36204eeab4 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -772,6 +772,9 @@ func run(f flags) int { _ = h.Close() return 1 } + // G2: fence the listener with the role the host already holds + // (the assignment stream started above) before it serves. + h.SetSelfFence(listener) listener.Serve() replListen = listener diff --git a/seaweed-block/core/host/volume/g2_self_fence_test.go b/seaweed-block/core/host/volume/g2_self_fence_test.go new file mode 100644 index 0000000000..5c3b88dc0b --- /dev/null +++ b/seaweed-block/core/host/volume/g2_self_fence_test.go @@ -0,0 +1,134 @@ +package volume + +// G2 (internal/docs/protocol/fencing-gaps-todo.md): a host that becomes +// primary must fence its own replica listener. Before the fix, Fence sent +// barriers to peers only, so a deposed primary that could still reach the new +// primary's listener kept getting its writes applied there (and could count +// that ACK toward its quorum). + +import ( + "bytes" + "errors" + "net" + "os" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +const g2BlockSize = 4096 + +// g2Ship opens a connection to addr and sends one MsgShipEntry, as the +// (deposed) primary P1 would. +func g2Ship(t *testing.T, addr string, lineage transport.RecoveryLineage, lsn uint64, fill byte) net.Conn { + t.Helper() + conn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatalf("dial replica listener: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + entry := transport.ShipEntry{Lineage: lineage, LBA: 0, LSN: lsn, Data: bytes.Repeat([]byte{fill}, g2BlockSize)} + if err := transport.WriteMsg(conn, transport.MsgShipEntry, transport.EncodeShipEntry(entry)); err != nil { + t.Fatalf("ship: %v", err) + } + return conn +} + +// g2Closed reports whether the listener closed conn within d (a refused +// mutation closes the connection; an applied ship sends nothing back). +func g2Closed(conn net.Conn, d time.Duration) bool { + _ = conn.SetReadDeadline(time.Now().Add(d)) + _, err := conn.Read(make([]byte, 1)) + return err != nil && !errors.Is(err, os.ErrDeadlineExceeded) +} + +func g2Block(t *testing.T, store storage.LogicalStorage) []byte { + t.Helper() + b, err := store.Read(0) + if err != nil { + t.Fatalf("read LBA 0: %v", err) + } + return b +} + +// TestG2_PromotedHostRefusesShipFromDeposedPrimary — the G2 red test, as the +// doc describes it: ship at epoch 1 to listener B; master promotes B at epoch +// 2 through the host role path (Host.applyFact with a self fact, not a +// test-only setter); the old primary ships at epoch 1 again. The second ship +// must be refused: the connection closed and LBA 0 unchanged. +func TestG2_PromotedHostRefusesShipFromDeposedPrimary(t *testing.T) { + store := storage.NewBlockStore(16, g2BlockSize) + ln, err := transport.NewReplicaListener("127.0.0.1:0", store) + if err != nil { + t.Fatalf("listener: %v", err) + } + h, a, _ := newStubbedHost(t, "vol1", "rB", &orderingRecorder{}) + h.SetSelfFence(ln) // as cmd/blockvolume wires it, before Serve + ln.Serve() + t.Cleanup(ln.Stop) + + // P1 is primary at epoch 1 and ships to B. + p1 := transport.RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, FrontierHint: 1} + g2Ship(t, ln.Addr(), p1, 1, 'X') + deadline := time.Now().Add(2 * time.Second) + for !bytes.Equal(g2Block(t, store), bytes.Repeat([]byte{'X'}, g2BlockSize)) { + if time.Now().After(deadline) { + t.Fatal("fixture: the epoch-1 ship was never applied before promotion") + } + time.Sleep(5 * time.Millisecond) + } + + // Master promotes B to primary at epoch 2: the production role path. + h.applyFact(&control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "rB", // self + Epoch: 2, + EndpointVersion: 1, + DataAddr: ln.Addr(), + CtrlAddr: "127.0.0.1:1", + PeerSetGeneration: 2, + }) + if got := a.callCount.Load(); got != 1 || a.lastInfo.Epoch != 2 { + t.Fatalf("fixture: host did not adopt primary at epoch 2 (OnAssignment calls=%d epoch=%d)", got, a.lastInfo.Epoch) + } + + // P1, cut off from master but still reaching B, ships at epoch 1 again. + conn := g2Ship(t, ln.Addr(), p1, 2, 'Y') + closed := g2Closed(conn, 2*time.Second) + if got := g2Block(t, store); bytes.Equal(got, bytes.Repeat([]byte{'Y'}, g2BlockSize)) { + t.Fatal("G2: the new primary (epoch 2) applied the deposed primary's epoch-1 ship") + } + if !closed { + t.Fatal("G2: the new primary's listener kept the deposed primary's connection open (mutation not refused)") + } +} + +// stubFencer fails FenceAsPrimary, as a listener whose in-flight mutations did +// not drain within the bound would. +type stubFencer struct{ err error } + +func (s stubFencer) FenceAsPrimary(uint64) error { return s.err } +func (s stubFencer) AdmitAsReplica(uint64) {} + +// If the host cannot fence its own listener, it must not adopt the primary +// role: OnAssignment is skipped (frontend stays gated), as for an +// UpdateReplicaSet failure, and master's stream replay redelivers the fact. +func TestG2_HostDoesNotAdoptPrimaryWhenItsListenerCannotBeFenced(t *testing.T) { + h, a, _ := newStubbedHost(t, "vol1", "rB", &orderingRecorder{}) + h.SetSelfFence(stubFencer{err: errors.New("2 replication mutation(s) still in flight")}) + h.applyFact(&control.AssignmentFact{ + VolumeId: "vol1", + ReplicaId: "rB", + Epoch: 2, + EndpointVersion: 1, + DataAddr: "127.0.0.1:1", + CtrlAddr: "127.0.0.1:2", + PeerSetGeneration: 2, + }) + if got := a.callCount.Load(); got != 0 { + t.Fatalf("fail-closed violated: OnAssignment calls=%d want 0", got) + } +} diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 2dba4cb95c..2eac840935 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -111,6 +111,17 @@ type Host struct { replicationMu sync.RWMutex replication replicaSetUpdater + // selfFence is this host's own replica listener (G2). When the host + // takes the primary role at epoch e it fences the listener at e before + // the adapter is told (so before the frontend serves IO); when it is + // admitted as a supporting replica it re-admits replication at that + // epoch. selfRole/selfEpoch remember the last decision so a listener + // wired after the first fact (the binary path) is fenced on install. + selfFenceMu sync.Mutex + selfFence selfFencer + selfRole selfRole + selfEpoch uint64 + conn *grpc.ClientConn obsCli control.ObservationServiceClient asnCli control.AssignmentServiceClient @@ -322,6 +333,65 @@ func (h *Host) replayLocalReadinessFactIfReady() { h.applyFact(fact) } +// selfFencer is the narrow interface Host needs from its own replica +// listener (G2). *transport.ReplicaListener satisfies it. +type selfFencer interface { + // FenceAsPrimary: this host is primary at epoch; refuse all inbound + // replication mutations, and any below epoch. It returns once no + // mutation admitted before the fence is still applying, or an error + // if that did not happen in time (the host must not take the role). + FenceAsPrimary(epoch uint64) error + // AdmitAsReplica: this host supports another primary at epoch; + // accept replication again, but none below epoch. + AdmitAsReplica(epoch uint64) +} + +type selfRole int + +const ( + selfRoleNone selfRole = iota + selfRolePrimary + selfRoleReplica +) + +// SetSelfFence installs this host's own replica listener (G2). The binary +// starts the assignment stream before the listener exists, so a role +// already adopted is applied to the listener here, before it serves (a +// listener that is not yet serving has nothing in flight to wait for). +func (h *Host) SetSelfFence(f selfFencer) { + h.selfFenceMu.Lock() + defer h.selfFenceMu.Unlock() + h.selfFence = f + if f != nil { + if err := applySelfRole(f, h.selfRole, h.selfEpoch); err != nil { + h.log.Printf("blockvolume: volume %s replica listener fence on install: %v", h.cfg.VolumeID, err) + } + } +} + +// fenceSelf records the role this host just took and applies it to its +// listener, if installed. An error means the listener could not be fenced +// in time; the caller must not adopt the primary role. +func (h *Host) fenceSelf(role selfRole, epoch uint64) error { + h.selfFenceMu.Lock() + defer h.selfFenceMu.Unlock() + h.selfRole, h.selfEpoch = role, epoch + if h.selfFence != nil { + return applySelfRole(h.selfFence, role, epoch) + } + return nil +} + +func applySelfRole(f selfFencer, role selfRole, epoch uint64) error { + switch role { + case selfRolePrimary: + return f.FenceAsPrimary(epoch) + case selfRoleReplica: + f.AdmitAsReplica(epoch) + } + return nil +} + // getReplication returns the current replication slot under a // read-lock. Used by applyFact at every AssignmentFact. func (h *Host) getReplication() replicaSetUpdater { @@ -606,6 +676,7 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.cfg.VolumeID, reason, info.ReplicaID, info.Epoch, info.EndpointVersion) return } + _ = h.fenceSelf(selfRoleReplica, info.Epoch) // admitting cannot fail h.adpt.OnAssignment(info) h.log.Printf("blockvolume: volume %s admitted as SUPPORTING replica %s at epoch=%d EV=%d behind primary %s; frontend remains gated", h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion, fact.ReplicaId) @@ -655,6 +726,16 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // Step (2c): identity install only after replication is live. // SOLE permitted decode path. See subscribe.go. info := decodeAssignmentFact(fact) + // G2: fence our own replica listener at this epoch before the adapter + // can turn Healthy and the frontend serves IO, so a deposed primary that + // still reaches us cannot get its writes applied (or counted) here. + if err := h.fenceSelf(selfRolePrimary, info.Epoch); err != nil { + // Fail closed, as for an UpdateReplicaSet failure: the frontend + // stays gated and master's stream replay redelivers the fact. + h.log.Printf("blockvolume: volume %s could not fence its own replica listener at epoch %d: %v — NOT applying to adapter (fail-closed)", + h.cfg.VolumeID, info.Epoch, err) + return + } h.adpt.OnAssignment(info) h.log.Printf("blockvolume: volume %s adopted as PRIMARY at %s@%d (EV=%d)", h.cfg.VolumeID, info.ReplicaID, info.Epoch, info.EndpointVersion) diff --git a/seaweed-block/core/transport/g2_self_fence_test.go b/seaweed-block/core/transport/g2_self_fence_test.go new file mode 100644 index 0000000000..70baaf727d --- /dev/null +++ b/seaweed-block/core/transport/g2_self_fence_test.go @@ -0,0 +1,319 @@ +package transport + +import ( + "errors" + "net" + "os" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// G2 listener contract (fencing-gaps-todo.md): while the host is primary +// every replication mutation is refused, probes are still answered, and the +// epoch floor it set never goes down when it later supports another primary. + +func g2Dial(t *testing.T, addr string) net.Conn { + t.Helper() + conn, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return conn +} + +// g2Refused sends one mutating frame and reports whether the listener closed +// the connection (refusal) rather than leaving it open (accepted). +func g2Refused(t *testing.T, addr string, msgType byte, payload []byte) bool { + t.Helper() + conn := g2Dial(t, addr) + if err := WriteMsg(conn, msgType, payload); err != nil { + t.Fatal(err) + } + _ = conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond)) + _, err := conn.Read(make([]byte, 1)) + return err != nil && !errors.Is(err, os.ErrDeadlineExceeded) +} + +func g2ShipPayload(l RecoveryLineage, lsn uint64) []byte { + return EncodeShipEntry(ShipEntry{Lineage: l, LBA: 0, LSN: lsn, Data: make([]byte, 4096)}) +} + +func TestG2_PrimaryListenerRefusesMutationsButAnswersProbes(t *testing.T) { + _, _, listener := setupPrimaryReplica(t) + listener.FenceAsPrimary(2) + + newer := RecoveryLineage{SessionID: 9, Epoch: 3, EndpointVersion: 1, TargetLSN: 1} + if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(newer, 1)) { + t.Fatal("a primary applied an inbound ship (even at a higher epoch)") + } + if !g2Refused(t, listener.Addr(), MsgRecoveryLaneStart, EncodeLineage(newer)) { + t.Fatal("a primary accepted a recovery lane start") + } + if !g2Refused(t, listener.Addr(), MsgRebuildBlock, EncodeRebuildBlock(newer, 0, make([]byte, 4096))) { + t.Fatal("a primary accepted a rebuild block") + } + + conn := g2Dial(t, listener.Addr()) + _ = conn.SetDeadline(time.Now().Add(2 * time.Second)) + probe := RecoveryLineage{SessionID: 4, Epoch: 2, EndpointVersion: 1, TargetLSN: 1} + if err := WriteMsg(conn, MsgProbeReq, EncodeProbeReq(ProbeRequest{Lineage: probe})); err != nil { + t.Fatal(err) + } + if msgType, _, err := ReadMsg(conn); err != nil || msgType != MsgProbeResp { + t.Fatalf("a primary must still answer probes: type=0x%02x err=%v", msgType, err) + } +} + +func TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother(t *testing.T) { + _, _, listener := setupPrimaryReplica(t) + listener.FenceAsPrimary(2) + listener.AdmitAsReplica(3) // superseded, now supporting the epoch-3 primary + + if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(RecoveryLineage{SessionID: 1, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, 1)) { + t.Fatal("a ship below the floor (epoch 2 < 3) was accepted") + } + if g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(RecoveryLineage{SessionID: 2, Epoch: 3, EndpointVersion: 1, TargetLSN: 1}, 1)) { + t.Fatal("the epoch-3 primary's ship was refused by its supporting replica") + } + + listener.AdmitAsReplica(1) // a stale, lower admission never lowers the floor + if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(RecoveryLineage{SessionID: 3, Epoch: 2, EndpointVersion: 1, TargetLSN: 1}, 2)) { + t.Fatal("the floor went down after a lower admission") + } +} + +// pausingStore holds ApplyEntry inside the store until released, to put a +// ship frame "past the gate but not yet applied" at the moment of promotion +// (claude03's review control for #82). +type pausingStore struct { + storage.LogicalStorage + entered chan struct{} + release chan struct{} + applied chan time.Time +} + +func (s *pausingStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { + s.entered <- struct{}{} + <-s.release + err := s.LogicalStorage.ApplyEntry(lba, data, lsn) + s.applied <- time.Now() + return err +} + +func g2PausedShip(t *testing.T) (*ReplicaListener, *pausingStore) { + t.Helper() + store := &pausingStore{ + LogicalStorage: storage.NewBlockStore(64, 4096), + entered: make(chan struct{}, 1), + release: make(chan struct{}), + applied: make(chan time.Time, 1), + } + listener, err := NewReplicaListener("127.0.0.1:0", store) // production no-hook path + if err != nil { + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.Stop) + conn := g2Dial(t, listener.Addr()) + old := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} + if err := WriteMsg(conn, MsgShipEntry, g2ShipPayload(old, 1)); err != nil { + t.Fatal(err) + } + select { + case <-store.entered: + case <-time.After(5 * time.Second): + t.Fatal("fixture: the epoch-1 ship never reached the store") + } + return listener, store +} + +// An epoch-1 ship admitted just before promotion is inside ApplyEntry when +// FenceAsPrimary(2) is called. The fence must not return until that apply has +// finished: nothing from the deposed primary is applied after the host serves +// as primary (claude03 P2-1 on #82; before the fix it was applied ~18 µs after +// the fence returned). +func TestG2_FenceWaitsForAShipAlreadyPastTheGate(t *testing.T) { + listener, store := g2PausedShip(t) + type result struct { + at time.Time + err error + } + fenced := make(chan result, 1) + go func() { + err := listener.FenceAsPrimary(2) + fenced <- result{time.Now(), err} + }() + select { + case r := <-fenced: + close(store.release) + t.Fatalf("FenceAsPrimary returned (err=%v) while an admitted epoch-1 ship was still applying", r.err) + case <-time.After(300 * time.Millisecond): + } + close(store.release) + appliedAt := <-store.applied + select { + case r := <-fenced: + if r.err != nil { + t.Fatalf("fence: %v", r.err) + } + if r.at.Before(appliedAt) { + t.Fatalf("FenceAsPrimary returned %v before the in-flight apply finished", appliedAt.Sub(r.at)) + } + case <-time.After(5 * time.Second): + t.Fatal("FenceAsPrimary never returned after the in-flight apply finished") + } +} + +// If an admitted mutation does not finish within the bound, FenceAsPrimary +// reports it (the host then refuses the primary role) instead of returning as +// if fenced; the listener stays fenced for new frames. +func TestG2_FenceReportsAMutationStuckPastTheBound(t *testing.T) { + listener, store := g2PausedShip(t) + defer close(store.release) + listener.mu.Lock() + listener.fenceDrainTimeout = 200 * time.Millisecond + listener.mu.Unlock() + if err := listener.FenceAsPrimary(2); err == nil { + t.Fatal("FenceAsPrimary returned nil with a mutation still applying past the bound") + } + newer := RecoveryLineage{SessionID: 9, Epoch: 3, EndpointVersion: 1, TargetLSN: 1} + if !g2Refused(t, listener.Addr(), MsgShipEntry, g2ShipPayload(newer, 2)) { + t.Fatal("after a timed-out fence the listener accepted a new ship") + } +} + +// pausingExtentStore holds a rebuild base write (WriteExtentDirect) inside the +// store until released. +type pausingExtentStore struct { + storage.LogicalStorage + entered chan struct{} + release chan struct{} + written chan time.Time +} + +func (s *pausingExtentStore) WriteExtentDirect(lba uint32, data []byte) error { + s.entered <- struct{}{} + <-s.release + err := s.LogicalStorage.WriteExtentDirect(lba, data) + s.written <- time.Now() + return err +} + +// The rebuild path has the same boundary as ship: a rebuild block admitted +// before promotion is inside its base write when FenceAsPrimary(2) is called. +// The fence must not return until that write has finished. +func TestG2_FenceWaitsForARebuildBlockAlreadyPastTheGate(t *testing.T) { + store := &pausingExtentStore{ + LogicalStorage: storage.NewBlockStore(64, 4096), + entered: make(chan struct{}, 1), + release: make(chan struct{}), + written: make(chan time.Time, 1), + } + listener, err := NewReplicaListener("127.0.0.1:0", store) + if err != nil { + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.Stop) + conn := g2Dial(t, listener.Addr()) + old := RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1} + if err := WriteMsg(conn, MsgRebuildBlock, EncodeRebuildBlock(old, 0, make([]byte, 4096))); err != nil { + t.Fatal(err) + } + select { + case <-store.entered: + case <-time.After(5 * time.Second): + t.Fatal("fixture: the rebuild block never reached the store") + } + fenced := make(chan time.Time, 1) + go func() { + if err := listener.FenceAsPrimary(2); err != nil { + t.Errorf("fence: %v", err) + } + fenced <- time.Now() + }() + select { + case <-fenced: + close(store.release) + t.Fatal("FenceAsPrimary returned while an admitted rebuild block was still being written") + case <-time.After(300 * time.Millisecond): + } + close(store.release) + writtenAt := <-store.written + select { + case at := <-fenced: + if at.Before(writtenAt) { + t.Fatalf("FenceAsPrimary returned %v before the in-flight rebuild write finished", writtenAt.Sub(at)) + } + case <-time.After(5 * time.Second): + t.Fatal("FenceAsPrimary never returned after the rebuild write finished") + } +} + +// pausingHook holds a live-lane apply inside the apply gate until released +// (the ship path used when an ApplyHook is installed). +type pausingHook struct { + store storage.LogicalStorage + entered chan struct{} + release chan struct{} + applied chan time.Time +} + +func (h *pausingHook) ApplyRecovery(l RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + return h.store.ApplyEntry(lba, data, lsn) +} + +func (h *pausingHook) ApplyLive(l RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + h.entered <- struct{}{} + <-h.release + err := h.store.ApplyEntry(lba, data, lsn) + h.applied <- time.Now() + return err +} + +// The ship path through an installed ApplyHook: the fence waits for a live +// apply already past the gate, as on the direct path. +func TestG2_FenceWaitsForAHookedShipAlreadyPastTheGate(t *testing.T) { + hook := &pausingHook{store: storage.NewBlockStore(64, 4096), entered: make(chan struct{}, 1), release: make(chan struct{}), applied: make(chan time.Time, 1)} + listener, err := NewReplicaListenerWithApplyHook("127.0.0.1:0", hook.store, hook) + if err != nil { + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.Stop) + conn := g2Dial(t, listener.Addr()) + if err := WriteMsg(conn, MsgShipEntry, g2ShipPayload(RecoveryLineage{SessionID: 1, Epoch: 1, EndpointVersion: 1, TargetLSN: 1}, 1)); err != nil { + t.Fatal(err) + } + select { + case <-hook.entered: + case <-time.After(5 * time.Second): + t.Fatal("fixture: the ship never reached the apply hook") + } + fenced := make(chan time.Time, 1) + go func() { + if err := listener.FenceAsPrimary(2); err != nil { + t.Errorf("fence: %v", err) + } + fenced <- time.Now() + }() + select { + case <-fenced: + close(hook.release) + t.Fatal("FenceAsPrimary returned while a hooked epoch-1 apply was still running") + case <-time.After(300 * time.Millisecond): + } + close(hook.release) + appliedAt := <-hook.applied + select { + case at := <-fenced: + if at.Before(appliedAt) { + t.Fatalf("FenceAsPrimary returned %v before the hooked apply finished", appliedAt.Sub(at)) + } + case <-time.After(5 * time.Second): + t.Fatal("FenceAsPrimary never returned after the hooked apply finished") + } +} diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index ab8442a594..7af8c8d702 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -1,9 +1,11 @@ package transport import ( + "fmt" "log" "net" "sync" + "time" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -57,7 +59,20 @@ type ReplicaListener struct { mu sync.Mutex activeLineage RecoveryLineage - conns map[net.Conn]struct{} // active handler connections; protected by mu + // 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 + // is refused (it may only come from a deposed primary). Probes are + // unaffected. + epochFloor uint64 + primary bool + // inFlight counts mutating frames between their gate check and the + // end of their effect; drained is signalled when it reaches zero. + inFlight int + drained *sync.Cond + // fenceDrainTimeout bounds how long FenceAsPrimary waits for them. + fenceDrainTimeout time.Duration + conns map[net.Conn]struct{} // active handler connections; protected by mu } // NewReplicaListener creates a listener on the given address. @@ -218,168 +233,191 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { return // connection closed } - switch msgType { - case MsgRecoveryLaneStart: - lineage, err := DecodeLineage(payload) - if err != nil { - log.Printf("replica: decode recovery lane start: %v", err) - return - } - if !r.acceptMutationLineage(lineage) { - log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) - return - } - lane = mutationLaneRecovery - - case MsgShipEntry: - entry, err := DecodeShipEntry(payload) - if err != nil { - log.Printf("replica: decode ship entry: %v", err) - return - } - if !r.acceptMutationLineage(entry.Lineage) { - log.Printf("replica: reject stale ship session=%d epoch=%d endpointVersion=%d", - entry.Lineage.SessionID, entry.Lineage.Epoch, entry.Lineage.EndpointVersion) - return - } - // If the apply-gate is installed, route through it. - // Caller (this handler) decides lane; gate is lane-pure. - // Live-lane stale entries return error here → log + - // close conn (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD). - if r.applyHook != nil { - var err error - if lane == mutationLaneRecovery { - err = r.applyHook.ApplyRecovery(entry.Lineage, entry.LBA, entry.Data, entry.LSN) - } else { - err = r.applyHook.ApplyLive(entry.Lineage, entry.LBA, entry.Data, entry.LSN) - } + // G2: a mutating frame is counted from before its gate check until its + // effect is done, so FenceAsPrimary can wait out every frame that may + // already have passed the gate (claude03 review of #82). + mutating := isMutationMsg(msgType) + if mutating { + r.beginMutationFrame() + } + // A mutating frame's ack is written after the frame is uncounted: + // the fence waits for storage effects only, never for the network. + var replyType byte + var reply []byte + stop := func() bool { + switch msgType { + case MsgRecoveryLaneStart: + lineage, err := DecodeLineage(payload) if err != nil { - log.Printf("replica: apply gate: %v", err) - return + log.Printf("replica: decode recovery lane start: %v", err) + return true } - continue - } - // No hook: direct apply. - if err := r.store.ApplyEntry(entry.LBA, entry.Data, entry.LSN); err != nil { - log.Printf("replica: apply entry: %v", err) - } + if !r.acceptMutationLineage(lineage) { + log.Printf("replica: reject stale recovery lane start session=%d epoch=%d endpointVersion=%d", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + return true + } + lane = mutationLaneRecovery - case MsgProbeReq: - // ProbeReq carries full RecoveryLineage. Decode + validate - // + echo via the symmetric-pair rule. Failure to decode - // (short / zeroed lineage) closes the conn without - // echoing — the primary times out + treats as - // unreachable, which is the correct fail-closed surface. - // - // Probe is non-mutating: validation gates zeros and clearly - // stale lineages but MUST NOT advance `activeLineage`. - // Advancing activeLineage from a probe would cause a - // later catch-up / rebuild session at a lower sessionID - // (but same epoch / endpointVersion) to be incorrectly - // rejected as stale — probes monotonically advance - // sessionID via the adapter's global counter, so they - // would routinely race ahead of in-flight session IDs. - // Use `validateProbeLineage` instead. - req, err := DecodeProbeReq(payload) - if err != nil { - log.Printf("replica: decode probe req: %v", err) - return - } - if !r.validateProbeLineage(req.Lineage) { - log.Printf("replica: reject stale probe session=%d epoch=%d endpointVersion=%d", - req.Lineage.SessionID, req.Lineage.Epoch, req.Lineage.EndpointVersion) - return - } - R, S, H := r.store.Boundaries() - resp := EncodeProbeResp(ProbeResponse{ - Lineage: req.Lineage, // echo per symmetric-pair rule - SyncedLSN: R, - WalTail: S, - WalHead: H, - }) - if err := WriteMsg(conn, MsgProbeResp, resp); err != nil { - return - } + case MsgShipEntry: + entry, err := DecodeShipEntry(payload) + if err != nil { + log.Printf("replica: decode ship entry: %v", err) + return true + } + if !r.acceptMutationLineage(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 + } + // If the apply-gate is installed, route through it. + // Caller (this handler) decides lane; gate is lane-pure. + // Live-lane stale entries return error here → log + + // close conn (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD). + if r.applyHook != nil { + var err error + if lane == mutationLaneRecovery { + err = r.applyHook.ApplyRecovery(entry.Lineage, entry.LBA, entry.Data, entry.LSN) + } else { + err = r.applyHook.ApplyLive(entry.Lineage, entry.LBA, entry.Data, entry.LSN) + } + if err != nil { + log.Printf("replica: apply gate: %v", err) + return true + } + return false + } + // No hook: direct apply. + if err := r.store.ApplyEntry(entry.LBA, entry.Data, entry.LSN); err != nil { + log.Printf("replica: apply entry: %v", err) + } - case MsgRebuildBlock: - lineage, lba, data, err := DecodeRebuildBlock(payload) - if err != nil { - log.Printf("replica: decode rebuild block: %v", err) - return - } - if !r.acceptMutationLineage(lineage) { - log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) - return - } - // 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) - return - } - if err := r.store.WriteExtentDirect(lba, data); err != nil { - log.Printf("replica: apply rebuild base block: %v", err) - return - } + case MsgProbeReq: + // ProbeReq carries full RecoveryLineage. Decode + validate + // + echo via the symmetric-pair rule. Failure to decode + // (short / zeroed lineage) closes the conn without + // echoing — the primary times out + treats as + // unreachable, which is the correct fail-closed surface. + // + // Probe is non-mutating: validation gates zeros and clearly + // stale lineages but MUST NOT advance `activeLineage`. + // Advancing activeLineage from a probe would cause a + // later catch-up / rebuild session at a lower sessionID + // (but same epoch / endpointVersion) to be incorrectly + // rejected as stale — probes monotonically advance + // sessionID via the adapter's global counter, so they + // would routinely race ahead of in-flight session IDs. + // Use `validateProbeLineage` instead. + req, err := DecodeProbeReq(payload) + if err != nil { + log.Printf("replica: decode probe req: %v", err) + return true + } + if !r.validateProbeLineage(req.Lineage) { + log.Printf("replica: reject stale probe session=%d epoch=%d endpointVersion=%d", + req.Lineage.SessionID, req.Lineage.Epoch, req.Lineage.EndpointVersion) + return true + } + R, S, H := r.store.Boundaries() + resp := EncodeProbeResp(ProbeResponse{ + Lineage: req.Lineage, // echo per symmetric-pair rule + SyncedLSN: R, + WalTail: S, + WalHead: H, + }) + if err := WriteMsg(conn, MsgProbeResp, resp); err != nil { + return true + } - case MsgRebuildDone: - lineage, err := DecodeLineage(payload) - if err != nil { - log.Printf("replica: decode rebuild done: %v", err) - return - } - if !r.acceptMutationLineage(lineage) { - log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) - return - } - if err := prepareBaseInstall(); err != nil { - log.Printf("replica: prepare empty rebuild base: %v", err) - return - } - // 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{ - Lineage: lineage, - AchievedLSN: frontier, - }) - if err := WriteMsg(conn, MsgBarrierResp, resp); err != nil { - return - } - return + case MsgRebuildBlock: + lineage, lba, data, err := DecodeRebuildBlock(payload) + if err != nil { + log.Printf("replica: decode rebuild block: %v", err) + return true + } + if !r.acceptMutationLineage(lineage) { + log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + return true + } + // 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) + return true + } + if err := r.store.WriteExtentDirect(lba, data); err != nil { + log.Printf("replica: apply rebuild base block: %v", err) + return true + } - case MsgBarrierReq: - lineage, err := DecodeLineage(payload) - if err != nil { - log.Printf("replica: decode barrier req: %v", err) - return - } - if !r.acceptMutationLineage(lineage) { - log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d", - lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) - return - } - frontier, _ := r.store.Sync() - // Echo the request's full lineage in the barrier ack. - // The primary's DurabilityCoordinator validates this - // tuple against the session it is awaiting before - // counting the ack toward quorum. - resp := EncodeBarrierResp(BarrierResponse{ - Lineage: lineage, - AchievedLSN: frontier, - }) - WriteMsg(conn, MsgBarrierResp, resp) + case MsgRebuildDone: + lineage, err := DecodeLineage(payload) + if err != nil { + log.Printf("replica: decode rebuild done: %v", err) + return true + } + if !r.acceptMutationLineage(lineage) { + log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + return true + } + if err := prepareBaseInstall(); err != nil { + log.Printf("replica: prepare empty rebuild base: %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{ + Lineage: lineage, + AchievedLSN: frontier, + }) + replyType, reply = MsgBarrierResp, resp + return true - default: - log.Printf("replica: unknown message type 0x%02x", msgType) + case MsgBarrierReq: + lineage, err := DecodeLineage(payload) + if err != nil { + log.Printf("replica: decode barrier req: %v", err) + return true + } + if !r.acceptMutationLineage(lineage) { + log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d", + lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) + return true + } + frontier, _ := r.store.Sync() + // Echo the request's full lineage in the barrier ack. + // The primary's DurabilityCoordinator validates this + // tuple against the session it is awaiting before + // counting the ack toward quorum. + resp := EncodeBarrierResp(BarrierResponse{ + Lineage: lineage, + AchievedLSN: frontier, + }) + replyType, reply = MsgBarrierResp, resp + + default: + log.Printf("replica: unknown message type 0x%02x", msgType) + return true + } + return false + }() + if mutating { + r.endMutationFrame() + } + if reply != nil { + if err := WriteMsg(conn, replyType, reply); err != nil { + return + } + } + if stop { return } } @@ -425,6 +463,98 @@ func (r *ReplicaListener) validateProbeLineage(incoming RecoveryLineage) bool { return true } +// FenceAsPrimary is called when this host takes the primary role at epoch +// (G2), before its frontend serves IO: from now on the listener refuses +// every replication mutation (ship, recovery lane start, rebuild), and none +// below epoch is accepted again. Probes are still answered. +// +// It returns only once every mutating frame that may already have passed +// the gate has finished its effect, so nothing from a deposed primary is +// applied after the host serves as primary. If that does not happen within +// fenceDrainTimeout it returns an error, and the host must not take the +// role (it fails closed; master redelivers the assignment). +func (r *ReplicaListener) FenceAsPrimary(epoch uint64) error { + r.mu.Lock() + defer r.mu.Unlock() + r.primary = true + if epoch > r.epochFloor { + r.epochFloor = epoch + } + if r.inFlight == 0 { + return nil + } + timeout := r.fenceDrainTimeout + if timeout <= 0 { + timeout = defaultFenceDrainTimeout + } + drained := r.drainedLocked() + expired := false + timer := time.AfterFunc(timeout, func() { + r.mu.Lock() + expired = true + r.mu.Unlock() + drained.Broadcast() + }) + defer timer.Stop() + for r.inFlight > 0 && !expired { + drained.Wait() + } + if r.inFlight > 0 { + return fmt.Errorf("replica listener: %d replication mutation(s) still in flight %v after fencing as primary at epoch %d", r.inFlight, timeout, epoch) + } + return nil +} + +// defaultFenceDrainTimeout bounds FenceAsPrimary's wait for in-flight +// mutations (one apply or rebuild extent write, or one barrier fsync). +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: + return true + } + return false +} + +func (r *ReplicaListener) beginMutationFrame() { + r.mu.Lock() + r.inFlight++ + r.mu.Unlock() +} + +func (r *ReplicaListener) endMutationFrame() { + r.mu.Lock() + r.inFlight-- + if r.inFlight == 0 { + r.drainedLocked().Broadcast() + } + r.mu.Unlock() +} + +// drainedLocked returns the in-flight condition variable, creating it on +// first use (some callers build the listener without a constructor). +// Caller holds r.mu. +func (r *ReplicaListener) drainedLocked() *sync.Cond { + if r.drained == nil { + r.drained = sync.NewCond(&r.mu) + } + return r.drained +} + +// AdmitAsReplica is called when this host is admitted as a supporting +// replica at epoch (G2): replication is accepted again, but none below +// epoch (the floor never goes down). +func (r *ReplicaListener) AdmitAsReplica(epoch uint64) { + r.mu.Lock() + defer r.mu.Unlock() + r.primary = false + if epoch > r.epochFloor { + r.epochFloor = epoch + } +} + func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { r.mu.Lock() defer r.mu.Unlock() @@ -432,6 +562,11 @@ func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { if incoming.SessionID == 0 || incoming.Epoch == 0 || incoming.EndpointVersion == 0 { return false } + // G2: a primary applies no inbound replication, and no host applies + // any below the epoch it has taken a role at. + if r.primary || incoming.Epoch < r.epochFloor { + return false + } active := r.activeLineage if active.SessionID == 0 { diff --git a/seaweed-block/internal/docs/protocol/fencing-gaps-todo.md b/seaweed-block/internal/docs/protocol/fencing-gaps-todo.md index 784c2db5b9..b73fafb416 100644 --- a/seaweed-block/internal/docs/protocol/fencing-gaps-todo.md +++ b/seaweed-block/internal/docs/protocol/fencing-gaps-todo.md @@ -16,7 +16,7 @@ row in [`invariant-ledger.md`](./invariant-ledger.md). | ID | Gap | Status | Priority | Proposed fix (short) | |---|---|---|---|---| | G1 | Replica lineage floor lives only in memory | Confirmed by code | P1 | Persist an epoch floor; reject mutations until floor is known | -| G2 | New primary does not fence its own replica listener | Confirmed by code | P1 | On becoming primary, raise own floor and refuse inbound ship | +| G2 | New primary does not fence its own replica listener | Fixed (red test + fix; ledger `INV-FENCE-SELF-ON-PROMOTE-001`) | P1 | On becoming primary, raise own floor and refuse inbound ship | | G3 | Production promotion runs without a required ACK frontier | Confirmed by code | P1 | Probe all survivors (R+W>N), then record the ACK frontier in master | | G4 | No primary-side lease; a cut-off primary keeps serving reads | Decided 2026-11-07: option A | P2 | Keep as an explicit non-claim for alpha/beta (see G4) | | G5 | Caught-up check compares LSN without epoch | Plausible, needs test | P2 | (epoch, LSN) comparison plus truncation at the epoch start | diff --git a/seaweed-block/internal/docs/protocol/invariant-ledger.md b/seaweed-block/internal/docs/protocol/invariant-ledger.md index 54dc5f2dc3..a87c3a17c6 100644 --- a/seaweed-block/internal/docs/protocol/invariant-ledger.md +++ b/seaweed-block/internal/docs/protocol/invariant-ledger.md @@ -33,6 +33,7 @@ deleting it. | `INV-CONTROL-CONTEXT-001` | Cross-layer explanations must be derived from facts/events, not reconstructed from TestOps-only grep order. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001` but retained for continuity. | observation | Product event stream D5; Phase 22 bundle artifact replay tests in `core/ops/managed_volume_artifact_test.go` and `core/ops/observation_bundle_test.go` | ACTIVE | | `INV-K8S-ADAPTOR-FACTS-001` | K8s adaptor must express PVC/PV/Pod/Node/CSI facts as typed facts with source, time, generation, and confidence before deriving recovery status. | K8s adaptor / future operator | PVC pending, mount-failure, image-pull, loopback, and node-loss reattach tests in `core/ops/managed_volume_model_test.go` and `core/ops/managed_volume_artifact_test.go` | ACTIVE | | `INV-HOSTPATH-FACTS-001` | Host path adaptor must distinguish iSCSI session reachability, multipath path state, ALUA state, and workload data check before claiming transparent failover. | host path adaptor | Stage 2 transparent host-path projection and non-claim tests in `core/ops/managed_volume_model_test.go` plus artifact replay in `core/ops/managed_volume_artifact_test.go` | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and no traffic below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | transport replica listener + volume host | `core/host/volume/g2_self_fence_test.go` (`TestG2_PromotedHostRefusesShipFromDeposedPrimary`: real `Host.applyFact` primary path + real listener); `core/transport/g2_self_fence_test.go` | ACTIVE | ## Add Row Checklist