diff --git a/seaweed-block/core/host/volume/host.go b/seaweed-block/core/host/volume/host.go index 9214863741..63bc2fdd89 100644 --- a/seaweed-block/core/host/volume/host.go +++ b/seaweed-block/core/host/volume/host.go @@ -176,18 +176,22 @@ type Host struct { // re-applies the current role until it succeeds or is refused for good. // Under selfFenceMu. roleRetry bool - // supportMu orders the completion of a supporting assignment: the fact - // path's (after its role call) and runRoleRetry's (after a retried role - // call), so an older epoch's completion never lands after a newer one's. - // Lock order: supportMu, then selfFenceMu; the fact path takes it only - // after fenceSelf released selfFenceMu. Nothing under it applies a fact. - supportMu sync.Mutex - // pendingSupport (under supportMu): the supporting assignment a fact + // pendingSupport (under selfFenceMu): the supporting assignment a fact // skipped because its replica role call failed with an error a retry - // may outlast. runRoleRetry completes it once the role call succeeds - // while this host still wants the replica role at that epoch; a newer - // fact supersedes it (it moves selfEpoch or the role, or replaces it). + // may outlast. runRoleRetry completes it, under selfFenceMu, once the + // role call succeeds while the desired role is still replica at that + // epoch and no newer fact has been seen (factEpochSeen). pendingSupport *pendingSupport + // factEpochSeen (under selfFenceMu): the highest epoch of any fact + // applyFact has started on, recorded at its very start, before the fact + // acts in any way (the watchdog, the role call, the adapter). The retry + // completes a pending assignment, under selfFenceMu, only while no newer + // epoch was seen; a newer fact arriving meanwhile waits at that record + // until the completion is done, so none of its actions precede it and no + // older completion lands after a newer transition. The record is the + // only part of applyFact under the lock: facts applied concurrently (a + // replay beside the stream, one inside another's hook) do not nest it. + factEpochSeen uint64 // RF1Only admission state, one unit under rf1Mu (field access only, no // calls): the highest refused epoch with its reason ("" = cleared), and the // highest epoch an RF1 fact was admitted at. A clear removes only the @@ -529,11 +533,9 @@ func (h *Host) runRoleRetry(ctx context.Context) { return case <-time.After(delay): } - h.supportMu.Lock() h.selfFenceMu.Lock() if !h.roleRetry || h.selfFence == nil || h.selfRole != selfRoleReplica { h.selfFenceMu.Unlock() - h.supportMu.Unlock() delay = roleRetryMin continue } @@ -543,21 +545,23 @@ func (h *Host) runRoleRetry(ctx context.Context) { // replica role was first taken there. err := applySelfRoleWithPeers(h.selfFence, role, epoch, h.selfHasPeers) h.latchRoleAdmission(role, epoch, err) - h.selfFenceMu.Unlock() if err == nil { h.log.Printf("blockvolume: replica role at epoch %d admitted on retry", epoch) // Finish what the fact skipped when its role call failed, as the - // assignment path would have after a successful one. supportMu is - // held: a newer fact's completion waits for this one. - if p := h.pendingSupport; p != nil && p.info.Epoch == epoch { + // assignment path would have after a successful one, still under + // selfFenceMu: the desired role and epoch read above cannot move + // until it is done, so no newer transition lands in between. + // (The completion takes no host lock: the adapter's executor is + // local, the watchdog and the marker have their own.) + if p := h.pendingSupport; p != nil && p.info.Epoch == epoch && h.factEpochSeen <= epoch { h.pendingSupport = nil h.completeSupporting(p.info, p.primary) } - h.supportMu.Unlock() + h.selfFenceMu.Unlock() delay = roleRetryMin continue } - h.supportMu.Unlock() + h.selfFenceMu.Unlock() if delay *= 2; delay > roleRetryMax { delay = roleRetryMax } @@ -997,6 +1001,12 @@ func (h *Host) streamOnce(ctx context.Context) error { // OnAssignment could flip the projection Healthy before peers were // installed, admitting local-only writes with zero fan-out. func (h *Host) applyFact(fact *control.AssignmentFact) { + // Record the fact's epoch before it acts (see factEpochSeen). + h.selfFenceMu.Lock() + if fact.GetEpoch() > h.factEpochSeen { + h.factEpochSeen = fact.GetEpoch() + } + h.selfFenceMu.Unlock() // INV-AUTH-HOLDER-IDENTITY-001: matching r1 and loopback endpoints do not identify a host. if h.refusePrimaryAssignment(fact) { return @@ -1024,18 +1034,18 @@ func (h *Host) applyFact(fact *control.AssignmentFact) { // once it succeeds; a later fact supersedes it. h.log.Printf("blockvolume: volume %s could not admit its replica listener at epoch %d: %v — NOT admitting supporting replica (fail-closed)", h.cfg.VolumeID, info.Epoch, err) - h.supportMu.Lock() + h.selfFenceMu.Lock() h.pendingSupport = nil - if !errors.Is(err, ErrRoleRefused) { + if !errors.Is(err, ErrRoleRefused) && h.selfRole == selfRoleReplica && h.selfEpoch == info.Epoch { h.pendingSupport = &pendingSupport{info: info, primary: fact.ReplicaId} } - h.supportMu.Unlock() + h.selfFenceMu.Unlock() return } - h.supportMu.Lock() + h.selfFenceMu.Lock() h.pendingSupport = nil // this fact supersedes any skipped one + h.selfFenceMu.Unlock() h.completeSupporting(info, fact.ReplicaId) - h.supportMu.Unlock() return } // The new authoritative set excludes us: close assignment-gated diff --git a/seaweed-block/core/host/volume/role_retry_order_test.go b/seaweed-block/core/host/volume/role_retry_order_test.go new file mode 100644 index 0000000000..1743d27802 --- /dev/null +++ b/seaweed-block/core/host/volume/role_retry_order_test.go @@ -0,0 +1,164 @@ +package volume + +import ( + "context" + "errors" + "fmt" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/rpc/control" +) + +// orderLog is one sequence of the host's role calls and adapter assignments. +type orderLog struct { + mu sync.Mutex + seq []string +} + +func (o *orderLog) add(s string) { o.mu.Lock(); o.seq = append(o.seq, s); o.mu.Unlock() } +func (o *orderLog) snapshot() []string { + o.mu.Lock() + defer o.mu.Unlock() + return append([]string(nil), o.seq...) +} +func (o *orderLog) index(s string) int { + for i, e := range o.snapshot() { + if e == s { + return i + } + } + return -1 +} + +// orderListener fails its first replica role call, then records every role +// call it admits. +type orderListener struct { + log *orderLog + mu sync.Mutex + fails int +} + +func (l *orderListener) FenceAsPrimary(e uint64) error { + l.log.add(fmt.Sprintf("primary@%d", e)) + return nil +} +func (l *orderListener) AdmitAsReplica(e uint64) error { + l.mu.Lock() + defer l.mu.Unlock() + if l.fails > 0 { + l.fails-- + return errors.New("replica floor record write: permission denied") + } + l.log.add(fmt.Sprintf("replica@%d", e)) + return nil +} + +// heldAdapter records each assignment when it returns; the one at holdAt +// waits in OnAssignment until release is closed. +type heldAdapter struct { + log *orderLog + holdAt uint64 + entered, release chan struct{} +} + +func (a *heldAdapter) OnAssignment(info adapter.AssignmentInfo) adapter.ApplyLog { + if info.Epoch == a.holdAt { + close(a.entered) + <-a.release + } + a.log.add(fmt.Sprintf("assign@%d", info.Epoch)) + return adapter.ApplyLog{} +} + +// The retry's completion of a skipped supporting assignment at epoch 2 is +// held in its first step while a newer fact at epoch 3 arrives: this host's +// own primary line, or a line that excludes it. The completion must finish +// before the newer transition takes its role, so no older completion lands +// after it: the adapter does not go back to epoch 2, the primary watchdog +// keeps epoch 3, and no supporting admission or marker for 2 follows. +func TestRoleRetryCompletionNeverLandsAfterANewerTransition(t *testing.T) { + min, max := roleRetryMin, roleRetryMax + roleRetryMin, roleRetryMax = time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { roleRetryMin, roleRetryMax = min, max }) + + selfPrimary := func() *control.AssignmentFact { + return &control.AssignmentFact{ServerId: "sB", VolumeId: "vol1", ReplicaId: "rB", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", PeerSetGeneration: 3} + } + excluding := func() *control.AssignmentFact { + return &control.AssignmentFact{VolumeId: "vol1", ReplicaId: "rA", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:3", CtrlAddr: "127.0.0.1:4", PeerSetGeneration: 3, + Peers: []*control.ReplicaDescriptor{{ReplicaId: "rC", Epoch: 3, EndpointVersion: 1, DataAddr: "127.0.0.1:7", CtrlAddr: "127.0.0.1:8"}}} + } + for name, newer := range map[string]func() *control.AssignmentFact{"self-primary": selfPrimary, "excluding": excluding} { + t.Run(name, func(t *testing.T) { + markers := make(chan adapter.AssignmentInfo, 8) + h, err := New(Config{MasterAddr: "127.0.0.1:1", ServerID: "sB", VolumeID: "vol1", ReplicaID: "rB", DataAddr: "127.0.0.1:5", CtrlAddr: "127.0.0.1:6", ReadyMarker: markers}) + if err != nil { + t.Fatal(err) + } + log := &orderLog{} + adpt := &heldAdapter{log: log, holdAt: 2, entered: make(chan struct{}), release: make(chan struct{})} + h.adpt = adpt + if err := h.SetSelfFence(&orderListener{log: log, fails: 1}); err != nil { + t.Fatal(err) + } + h.applyFact(supportingFact(2)) // its role call fails: the assignment waits for the retry + + ctx, cancel := context.WithCancel(context.Background()) + h.wg.Add(1) + go h.runRoleRetry(ctx) + defer func() { cancel(); h.wg.Wait() }() + + select { + case <-adpt.entered: // the retry's role call succeeded; its completion is held + case <-time.After(2 * time.Second): + t.Fatal("the retry never completed the skipped assignment") + } + done := make(chan struct{}) + go func() { h.applyFact(newer()); close(done) }() + time.Sleep(100 * time.Millisecond) // the newer fact runs as far as it can + close(adpt.release) + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("the newer fact never finished") + } + + deadline := time.Now().Add(2 * time.Second) + for log.index("assign@2") < 0 && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + seq := log.snapshot() + old, newerRole := log.index("assign@2"), log.index("primary@3") + if old < 0 || newerRole < 0 { + t.Fatalf("sequence %v; want the completion at 2 and the newer role call at 3", seq) + } + if old > newerRole { + t.Fatalf("sequence %v: the completion for epoch 2 landed after the newer transition at 3", seq) + } + if name == "self-primary" { + if last := seq[len(seq)-1]; last != "assign@3" { + t.Fatalf("sequence %v: the adapter ended at %s; want assign@3", seq, last) + } + h.wd.mu.Lock() + pe := h.wd.primaryEpoch + h.wd.mu.Unlock() + if pe != 3 { + t.Fatalf("primary watchdog epoch %d after the primary line at 3; want 3 (an old supporting admission cleared it)", pe) + } + } + close(markers) + var order []uint64 + for m := range markers { + order = append(order, m.Epoch) + } + for i := 1; i < len(order); i++ { + if order[i] < order[i-1] { + t.Fatalf("ready markers %v: an old marker followed a newer one", order) + } + } + }) + } +}