From 243f73633fd2a3d1c167250ec6a3ed8eb9646cea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sun, 15 Nov 2026 21:29:56 -0800 Subject: [PATCH] fix: gate replication listeners on assigned replica slots --- seaweed-block/cmd/blockvolume/main.go | 84 +------ .../cmd/blockvolume/replication_ingress.go | 129 ++++++++++ .../replication_ingress_binary_test.go | 230 ++++++++++++++++++ seaweed-block/core/host/volume/host.go | 33 ++- seaweed-block/core/transport/replica.go | 11 + 5 files changed, 404 insertions(+), 83 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/replication_ingress.go create mode 100644 seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 467873372d..f2e5f791db 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -696,8 +696,8 @@ func run(f flags) int { // Bind the replication stack — ReplicationVolume for outbound peer // fan-out (primary role) + ReplicaListener for incoming WAL traffic - // (replica role). Both code paths are bound at startup; whichever - // role the master assignment selects is the active one. Construction + // (replica role). Incoming listeners are bound only when the master + // assignment includes replica slots; RF=1 never opens either lane. Construction // is post-dp.RecoverVolume because both borrow the same // LogicalStorage the durable Backend wraps; the LogicalStorage // isn't usable until recovery completes. @@ -711,7 +711,7 @@ func run(f flags) int { // control-plane split (no current binder). var ( replVolume *replication.ReplicationVolume - replListen *transport.ReplicaListener + replListen *replicationIngress ) if durableProv != nil { store := durableProv.LogicalStorage(f.volumeID) @@ -868,13 +868,13 @@ func run(f flags) int { fmt.Fprintln(os.Stderr, "blockvolume: write-observer wire: Backend(", f.volumeID, ") returned nil; replication fan-out disabled") } - // G1: the replica's epoch floor lives beside the volume's durable - // files so it survives a restart; non-durable (memback) runs keep it - // in memory only. Either way the listener refuses every mutation - // until the host's role call succeeds. - listener, err := transport.NewReplicaListenerWithFloor(f.dataAddr, store, f.volumeID, replicaFloorPath(f)) - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume: replica listener:", err) + // No replication socket exists until a master assignment includes + // replica slots. The role gate starts/fences both lanes before admission. + replListen = &replicationIngress{addr: f.dataAddr, store: store, + volumeID: f.volumeID, floorPath: replicaFloorPath(f), dualLane: f.recoveryMode == "dual-lane"} + if err := h.SetSelfFence(replListen); err != nil { + fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", err) + replListen.Stop() _ = replVolume.Close() _ = durableProv.Close() if status != nil { @@ -885,70 +885,6 @@ 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. G1: if - // that role cannot be made durable, do not serve at all. - if fErr := h.SetSelfFence(listener); fErr != nil { - fmt.Fprintln(os.Stderr, "blockvolume: replica listener role:", fErr) - listener.Stop() - _ = replVolume.Close() - _ = durableProv.Close() - if status != nil { - shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = status.Close(shutCtx) - shutCancel() - } - _ = h.Close() - return 1 - } - listener.Serve() - replListen = listener - - // When --recovery-mode=dual-lane, also bind a separate listener - // at port=data-addr-port+1 for inbound dual-lane recover-session - // connections. Each accepted conn is handed to a fresh - // recovery.Receiver via ReplicaBridge.AcceptDualLaneLoop. - // Listener lifecycle is goroutine-scoped here; daemon shutdown - // closes the underlying net.Listener via the deferred close - // added below. - if f.recoveryMode == "dual-lane" { - dualLaneAddr, err := deriveDualLaneAddr(f.dataAddr) - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume: dual-lane listen addr derive:", err) - replListen.Stop() - _ = replVolume.Close() - _ = durableProv.Close() - if status != nil { - shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = status.Close(shutCtx) - shutCancel() - } - _ = h.Close() - return 1 - } - dlLn, err := net.Listen("tcp", dualLaneAddr) - if err != nil { - fmt.Fprintln(os.Stderr, "blockvolume: dual-lane listen:", err) - replListen.Stop() - _ = replVolume.Close() - _ = durableProv.Close() - if status != nil { - shutCtx, shutCancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = status.Close(shutCtx) - shutCancel() - } - _ = h.Close() - return 1 - } - replicaBridge := recovery.NewReplicaBridgeWithGate(store, replListen) - dualLaneCtx, dualLaneCancel := context.WithCancel(context.Background()) - go replicaBridge.AcceptDualLaneLoop(dualLaneCtx, dlLn) - defer func() { - dualLaneCancel() - _ = dlLn.Close() - }() - fmt.Fprintf(os.Stderr, "blockvolume: dual-lane listener bound at %s\n", dualLaneAddr) - } } // Frontend volume capacity MUST derive from the daemon's diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go new file mode 100644 index 0000000000..4117fbad45 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -0,0 +1,129 @@ +package main + +import ( + "context" + "fmt" + "net" + "sync" + + "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +// replicationIngress owns both inbound lanes. Lock order: Host.selfFenceMu -> +// mu -> listener role gate. Stop never calls Host. No socket is created until +// an assignment permits a replica role, and each listener is fenced before Serve. +type replicationIngress struct { + mu sync.Mutex + addr, volumeID, floorPath string + store storage.LogicalStorage + dualLane bool + listener *transport.ReplicaListener + dual net.Listener + cancel context.CancelFunc + closed bool +} + +func (r *replicationIngress) FenceAsPrimary(epoch uint64) error { + return r.FenceAsPrimaryWithPeers(epoch, true) +} +func (r *replicationIngress) FenceAsPrimaryWithPeers(epoch uint64, hasPeers bool) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("replication ingress closed") + } + if !hasPeers { + if r.listener != nil { + if err := r.listener.FenceAsPrimary(epoch); err != nil { + return err + } + } + r.stopLocked(true) + return nil + } + return r.roleLocked(epoch, true) +} +func (r *replicationIngress) AdmitAsReplica(epoch uint64) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return fmt.Errorf("replication ingress closed") + } + return r.roleLocked(epoch, false) +} +func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { + listener := r.listener + fresh := listener == nil + if fresh { + var err error + listener, err = transport.NewReplicaListenerWithFloor(r.addr, r.store, r.volumeID, r.floorPath) + if err != nil { + return err + } + } + var err error + if primary { + err = listener.FenceAsPrimary(epoch) + } else { + err = listener.AdmitAsReplica(epoch) + } + if err != nil { + if fresh { + listener.Stop() + } + return err + } + if !fresh { + return nil + } + var dl net.Listener + if r.dualLane { + var addr string + addr, err = deriveDualLaneAddr(r.addr) + if err == nil { + dl, err = net.Listen("tcp", addr) + } + if err != nil { + listener.Stop() + return err + } + } + r.listener, r.dual = listener, dl + listener.Serve() + if dl != nil { + ctx, cancel := context.WithCancel(context.Background()) + r.cancel = cancel + bridge := recovery.NewReplicaBridgeWithGate(r.store, listener) + go bridge.AcceptDualLaneLoop(ctx, dl) + } + return nil +} +func (r *replicationIngress) stopLocked(withdrawn bool) { + if r.cancel != nil { + r.cancel() + r.cancel = nil + } + if r.dual != nil { + _ = r.dual.Close() + r.dual = nil + } + if r.listener != nil { + if withdrawn { + // FenceAsPrimary already drained admitted mutations. The role has + // been revoked, so disconnect idle peers instead of waiting for + // them to close a connection to an endpoint they no longer own. + r.listener.StopHard() + } else { + r.listener.Stop() + } + r.listener = nil + } +} +func (r *replicationIngress) Stop() { + r.mu.Lock() + defer r.mu.Unlock() + r.closed = true + r.stopLocked(false) +} diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go new file mode 100644 index 0000000000..d9edda999b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_binary_test.go @@ -0,0 +1,230 @@ +//go:build subprocess && !windows + +package main_test + +import ( + "context" + "encoding/json" + "errors" + "net" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" + "time" + + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/transport" + "google.golang.org/grpc" +) + +// Controlled master stream exercises the real binary's normal assignment path. +// It does not model the master's placement or epoch-minting policy. +type ingressAssignments struct { + control.UnimplementedAssignmentServiceServer + control.UnimplementedObservationServiceServer + facts chan *control.AssignmentFact +} + +func (m *ingressAssignments) ReportHeartbeat(context.Context, *control.HeartbeatReport) (*control.HeartbeatAck, error) { + return &control.HeartbeatAck{}, nil +} +func (m *ingressAssignments) SubscribeAssignments(_ *control.SubscribeRequest, s control.AssignmentService_SubscribeAssignmentsServer) error { + for { + select { + case <-s.Context().Done(): + return s.Context().Err() + case f := <-m.facts: + if err := s.Send(f); err != nil { + return err + } + } + } +} +func ingressPortPair(t *testing.T) (string, string) { + t.Helper() + for i := 0; i < 100; i++ { + a, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + port := a.Addr().(*net.TCPAddr).Port + b, e := net.ListenTCP("tcp", &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: port + 1}) + if e == nil { + x, y := a.Addr().String(), b.Addr().String() + a.Close() + b.Close() + return x, y + } + a.Close() + } + t.Fatal("no adjacent free ports") + return "", "" +} +func ingressWait(t *testing.T, what string, fn func() bool) { + t.Helper() + end := time.Now().Add(10 * time.Second) + for !fn() { + if time.Now().After(end) { + t.Fatal(what) + } + time.Sleep(20 * time.Millisecond) + } +} +func ingressRefused(t *testing.T, addr string) { + t.Helper() + c, e := net.DialTimeout("tcp", addr, 300*time.Millisecond) + if c != nil { + _ = c.SetDeadline(time.Now().Add(300 * time.Millisecond)) + _ = transport.WriteMsg(c, transport.MsgProbeReq, transport.EncodeProbeReq(transport.ProbeRequest{Lineage: transport.RecoveryLineage{Epoch: 999, SessionID: 1, EndpointVersion: 1, FrontierHint: 1}})) + c.Close() + } + if !errors.Is(e, syscall.ECONNREFUSED) { + t.Fatalf("replication connection to %s: want connection refused, got %v", addr, e) + } +} +func TestBinaryReplicationIngressFollowsAssignedSlots(t *testing.T) { + exe := filepath.Join(t.TempDir(), "blockvolume") + cmd := exec.Command("go", "build", "-race", "-p", "4", "-o", exe, ".") + if b, e := cmd.CombinedOutput(); e != nil { + t.Fatalf("build: %v %s", e, b) + } + for _, mode := range []string{"legacy", "dual-lane"} { + t.Run(mode, func(t *testing.T) { + m := &ingressAssignments{facts: make(chan *control.AssignmentFact, 4)} + ln, e := net.Listen("tcp", "127.0.0.1:0") + if e != nil { + t.Fatal(e) + } + server := grpc.NewServer() + control.RegisterAssignmentServiceServer(server, m) + control.RegisterObservationServiceServer(server, m) + go server.Serve(ln) + t.Cleanup(server.Stop) + data, dual := ingressPortPair(t) + status := pickAddr(t) + ctrl := pickAddr(t) + root := t.TempDir() + logPath := filepath.Join(t.TempDir(), "volume.log") + log, e := os.Create(logPath) + if e != nil { + t.Fatal(e) + } + child := exec.Command(exe, "--master", ln.Addr().String(), "--server-id", "s1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", data, "--ctrl-addr", ctrl, "--status-addr", status, "--t1-readiness", "--durable-root", root, "--durable-impl", "walstore", "--durable-blocks", "64", "--heartbeat-interval", "50ms", "--recovery-mode", mode) + child.Stdout, child.Stderr = log, log + if e = child.Start(); e != nil { + t.Fatal(e) + } + done := make(chan error, 1) + go func() { done <- child.Wait() }() + t.Cleanup(func() { + child.Process.Signal(syscall.SIGTERM) + select { + case <-done: + case <-time.After(5 * time.Second): + child.Process.Kill() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("child reap timeout") + } + } + log.Close() + if t.Failed() { + b, _ := os.ReadFile(logPath) + t.Logf("binary log: %s", b) + } + }) + client := &http.Client{Timeout: 300 * time.Millisecond} + epoch := func(want float64) bool { + resp, e := client.Get("http://" + status + "/status?volume=v1") + if e != nil { + return false + } + defer resp.Body.Close() + var p map[string]any + if json.NewDecoder(resp.Body).Decode(&p) != nil { + return false + } + if want == 0 { + return true + } + return p["Epoch"] == want + } + ingressWait(t, "binary status not ready", func() bool { return epoch(0) }) + // No assignment: do not open an unauthorised replication socket. + ingressRefused(t, data) + ingressRefused(t, dual) + fact := func(e uint64, peers []*control.ReplicaDescriptor) *control.AssignmentFact { + return &control.AssignmentFact{VolumeId: "v1", ReplicaId: "r1", Epoch: e, EndpointVersion: e, DataAddr: data, CtrlAddr: ctrl, PeerSetGeneration: e, Peers: peers} + } + m.facts <- fact(1, nil) + ingressWait(t, "RF1 assignment not applied", func() bool { return epoch(1) }) + // An attempted higher-epoch frame cannot even establish a connection. + ingressRefused(t, data) + ingressRefused(t, dual) + // RF can grow only through the authoritative assignment stream. + peer := &control.ReplicaDescriptor{ReplicaId: "r2", Epoch: 2, EndpointVersion: 2, DataAddr: pickAddr(t), CtrlAddr: pickAddr(t)} + m.facts <- fact(2, []*control.ReplicaDescriptor{peer}) + ingressWait(t, "RF2 assignment not applied", func() bool { return epoch(2) }) + for _, addr := range []string{data, dual} { + if addr == dual && mode != "dual-lane" { + ingressRefused(t, addr) + continue + } + c, e := net.DialTimeout("tcp", addr, time.Second) + if e != nil { + t.Fatalf("RF2 listener %s: %v", addr, e) + } + c.Close() + } + // A withdrawn role must close existing idle connections as well as + // the listening socket, without waiting for the peer to disconnect. + held, e := net.DialTimeout("tcp", data, time.Second) + if e != nil { + t.Fatal(e) + } + defer held.Close() + m.facts <- fact(3, nil) + ingressWait(t, "RF1 shrink not applied", func() bool { return epoch(3) }) + _ = held.SetReadDeadline(time.Now().Add(time.Second)) + var one [1]byte + if _, err := held.Read(one[:]); err == nil { + t.Fatal("withdrawn connection still usable") + } else if n, ok := err.(net.Error); ok && n.Timeout() { + t.Fatal("withdrawn connection not closed") + } + ingressRefused(t, data) + ingressRefused(t, dual) + // A supporting slot also opens both configured lanes. Removal from + // the authoritative set closes them, even without a primary role. + supporting := fact(4, []*control.ReplicaDescriptor{{ReplicaId: "r1", Epoch: 4, EndpointVersion: 4, DataAddr: data, CtrlAddr: ctrl}}) + supporting.ReplicaId = "r2" + m.facts <- supporting + ingressWait(t, "supporting assignment not applied", func() bool { return epoch(4) }) + for _, addr := range []string{data, dual} { + if addr == dual && mode != "dual-lane" { + continue + } + c, e := net.DialTimeout("tcp", addr, time.Second) + if e != nil { + t.Fatalf("supporting listener %s: %v", addr, e) + } + c.Close() + } + excluded := fact(5, nil) + excluded.ReplicaId = "r2" + m.facts <- excluded + ingressWait(t, "excluded slot still listens", func() bool { + c, e := net.DialTimeout("tcp", data, 200*time.Millisecond) + if c != nil { + c.Close() + } + return errors.Is(e, syscall.ECONNREFUSED) + }) + ingressRefused(t, dual) + }) + } +} diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 01f4a1e563..f934dd7ec6 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -132,10 +132,11 @@ type Host struct { // 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 + selfFenceMu sync.Mutex + selfFence selfFencer + selfRole selfRole + selfEpoch uint64 + selfHasPeers bool // roleAdmissionFailed (G1) latches a failed role call on the listener // (a floor that could not be persisted, or a fence that did not drain). // While set, the frontend projection is not Healthy, so writes refuse @@ -404,7 +405,7 @@ func (h *Host) SetSelfFence(f selfFencer) error { if f == nil { return nil } - err := applySelfRole(f, h.selfRole, h.selfEpoch) + err := applySelfRoleWithPeers(f, h.selfRole, h.selfEpoch, h.selfHasPeers) h.latchRoleAdmission(h.selfRole, h.selfEpoch, err) return err } @@ -440,23 +441,32 @@ func (h *Host) RoleAdmissionFailure() (bool, string) { // desired role or touching the admission latch, so a stale success can never // reconcile a newer failure (codex01 R1 on #83). func (h *Host) fenceSelf(role selfRole, epoch uint64) error { + return h.fenceSelfWithPeers(role, epoch, true) +} + +func (h *Host) fenceSelfWithPeers(role selfRole, epoch uint64, hasPeers bool) error { h.selfFenceMu.Lock() defer h.selfFenceMu.Unlock() if epoch < h.selfEpoch { return fmt.Errorf("stale role call at epoch %d (current desired epoch %d)", epoch, h.selfEpoch) } - h.selfRole, h.selfEpoch = role, epoch + h.selfRole, h.selfEpoch, h.selfHasPeers = role, epoch, hasPeers if h.selfFence == nil { return nil } - err := applySelfRole(h.selfFence, role, epoch) + err := applySelfRoleWithPeers(h.selfFence, role, epoch, hasPeers) h.latchRoleAdmission(role, epoch, err) return err } -func applySelfRole(f selfFencer, role selfRole, epoch uint64) error { +// Optional listener lifecycle policy consumes only master-assigned peer slots. +// Called under selfFenceMu, before role admission; legacy fencers are unchanged. +func applySelfRoleWithPeers(f selfFencer, role selfRole, epoch uint64, hasPeers bool) error { switch role { case selfRolePrimary: + if gated, ok := f.(interface{ FenceAsPrimaryWithPeers(uint64, bool) error }); ok { + return gated.FenceAsPrimaryWithPeers(epoch, hasPeers) + } return f.FenceAsPrimary(epoch) case selfRoleReplica: return f.AdmitAsReplica(epoch) @@ -787,6 +797,11 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { h.emitSupportingReadyMarker(info) return } + // The new authoritative set excludes us: close assignment-gated + // ingress as well as withdrawing the frontend through recordOtherLine. + if err := h.fenceSelfWithPeers(selfRolePrimary, fact.Epoch, false); err != nil { + h.log.Printf("blockvolume: excluded replica ingress fence: %v", err) + } h.log.Printf("blockvolume: volume %s authority is now %s@%d (not this replica %s); recording supersede, not applying to adapter", h.cfg.VolumeID, fact.ReplicaId, fact.Epoch, h.cfg.ReplicaID) return @@ -833,7 +848,7 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // 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 { + if err := h.fenceSelfWithPeers(selfRolePrimary, info.Epoch, len(fact.Peers) > 0); 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)", diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 5757d6b69d..58667246b1 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -239,6 +239,8 @@ func (r *ReplicaListener) Stop() { // FIN/RST conns from a dead process; on localhost in-process tests, // nothing closes them, and Stop's wg.Wait would block forever. // +// Role withdrawal may also use this after FenceAsPrimary has drained all +// admitted mutations: idle peer connections must not hold a withdrawn endpoint. // Safe to call multiple times. Idempotent. // // This seam exists to make the restart-catch-up component test @@ -279,6 +281,15 @@ func (r *ReplicaListener) acceptLoop() { } } r.mu.Lock() + // Join admission with StopHard's connection snapshot. A connection + // accepted just before Close must not escape the shutdown snapshot. + select { + case <-r.stopCh: + r.mu.Unlock() + _ = conn.Close() + return + default: + } r.conns[conn] = struct{}{} r.mu.Unlock() r.wg.Add(1)