diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 30cafb9342..b4038436f0 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -127,7 +127,11 @@ type Publisher struct { mu sync.Mutex state map[subKey]assignmentState - subs map[subKey][]*subscription + // replicas indexes state by volume: the replica ids of every key of + // that volume. Kept by setStateLocked, the only writer of state, so a + // per-volume read costs that volume's replicas, not every line. + replicas map[string]map[string]struct{} + subs map[subKey][]*subscription // P14 S5 — durable authority store. Optional; nil means // in-memory only (existing behavior, used by tests and @@ -248,6 +252,7 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { p := &Publisher{ dir: dir, state: make(map[subKey]assignmentState), + replicas: map[string]map[string]struct{}{}, subs: make(map[subKey][]*subscription), writeSeqByVolume: map[string]uint64{}, workspace: map[string]*WorkspaceState{}, @@ -301,7 +306,7 @@ func (p *Publisher) reloadFromStore() { loaded.info.Primary = *rec.Primary } p.captureAssignmentOwner(&loaded.info, rec.Workspace) - p.state[key] = loaded + p.setStateLocked(key, loaded) if rec.WriteSeq > p.writeSeqByVolume[rec.VolumeID] { p.writeSeqByVolume[rec.VolumeID] = rec.WriteSeq } @@ -556,7 +561,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // any slot of the volume holds an authority line, a Bind for // another slot would mint a second epoch-1 line beside it. // Moving authority to another slot is IntentReassign. - if bound, ok := boundReplicaForVolume(p.state, ask.VolumeID); ok { + if bound, ok := boundReplicaForVolume(p.volumeStateLocked(ask.VolumeID), ask.VolumeID); ok { p.mu.Unlock() return fmt.Errorf("%w: volume %s is already bound to replica %s; use Reassign", ErrBindAlreadyBound, ask.VolumeID, bound) @@ -625,7 +630,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // establishment is the IntentBind path, not this one — // using Reassign to create a volume's very first binding // would confuse the per-volume monotonic line. - maxEpoch := maxPublishedEpochForVolume(p.state, ask.VolumeID) + maxEpoch := maxPublishedEpochForVolume(p.volumeStateLocked(ask.VolumeID), ask.VolumeID) if maxEpoch == 0 { p.mu.Unlock() return ErrReassignNotBound @@ -661,7 +666,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // planned (after the planned-move guard, no fence), or heal (the // line's own primary, at this epoch). No path mints one without. if ask.Evidence.Kind == adapter.PrimaryKindPromotion { - if err := promotionBasisHolds(ask, next.Epoch, p.state, maxEpoch); err != nil { + if err := promotionBasisHolds(ask, next.Epoch, p.volumeStateLocked(ask.VolumeID), maxEpoch); err != nil { p.mu.Unlock() return fmt.Errorf("%w: volume %s replica %s: %v", ErrPromotionUnfenced, ask.VolumeID, ask.ReplicaID, err) } @@ -726,7 +731,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.workspace[ask.VolumeID] = issuedWorkspace } - p.state[k] = assignmentState{info: next, present: true} + p.setStateLocked(k, assignmentState{info: next, present: true}) if issuedWorkspace != nil { // The issued move starts the new holder's lease (issuedAt+TTL grant). p.publishIssuedLeaseLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL)) @@ -754,6 +759,39 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr return nil } +// setStateLocked records the state of key k and indexes it under its +// volume. It is the only writer of p.state. p.mu held. +func (p *Publisher) setStateLocked(k subKey, st assignmentState) { + p.state[k] = st + r := p.replicas[k.volumeID] + if r == nil { + r = map[string]struct{}{} + p.replicas[k.volumeID] = r + } + r[k.replicaID] = struct{}{} +} + +// volumeStateLocked is the state of every key of one volume, read through +// the index: O(replicas of the volume), whatever the number of volumes. +// p.mu held. +func (p *Publisher) volumeStateLocked(volumeID string) map[subKey]assignmentState { + out := make(map[subKey]assignmentState, len(p.replicas[volumeID])) + for r := range p.replicas[volumeID] { + k := subKey{volumeID: volumeID, replicaID: r} + if st, ok := p.state[k]; ok { + out[k] = st + } + } + if check := testLineIndexCheck; check != nil { + check(p, volumeID, out) + } + return out +} + +// testLineIndexCheck, set by tests, is called with every per-volume read +// of the index, so the package's tests check the index against the scan. +var testLineIndexCheck func(p *Publisher, volumeID string, got map[subKey]assignmentState) + func safeInvokePublishObserver(observer func(PublishEvent), event PublishEvent) { defer func() { _ = recover() diff --git a/seaweed-block/core/authority/line_index_test.go b/seaweed-block/core/authority/line_index_test.go new file mode 100644 index 0000000000..725fbb80c3 --- /dev/null +++ b/seaweed-block/core/authority/line_index_test.go @@ -0,0 +1,102 @@ +package authority + +import ( + "fmt" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" +) + +// Every per-volume read of the line index, in every test of this package, +// equals a scan of the whole state restricted to that volume. +func init() { + testLineIndexCheck = func(p *Publisher, volumeID string, got map[subKey]assignmentState) { + want := map[subKey]assignmentState{} + for k, st := range p.state { + if k.volumeID == volumeID { + want[k] = st + } + } + if !reflect.DeepEqual(got, want) { + panic(fmt.Sprintf("authority: line index for volume %q holds %v, the scan %v", volumeID, got, want)) + } + } +} + +// A per-volume authority read costs that volume's replicas, not every +// line: reading one volume among 64,000 takes about as long as among +// 1,000 (the scan it replaces grows 64 times). +func TestVolumeAuthorityLineCostIsPerVolume(t *testing.T) { + saved := testLineIndexCheck + testLineIndexCheck = nil // the check itself scans; time the read alone + t.Cleanup(func() { testLineIndexCheck = saved }) + perRead := func(volumes int) time.Duration { + p := NewPublisher(nil) + p.mu.Lock() + for i := 0; i < volumes; i++ { + for _, r := range []string{"r1", "r2"} { + p.setStateLocked(subKey{volumeID: fmt.Sprintf("v%06d", i), replicaID: r}, assignmentState{info: adapter.AssignmentInfo{VolumeID: fmt.Sprintf("v%06d", i), ReplicaID: r, Epoch: 1}, present: true}) + } + } + p.mu.Unlock() + const reads = 2000 + best := time.Duration(1 << 62) + for round := 0; round < 3; round++ { + start := time.Now() + for i := 0; i < reads; i++ { + if _, ok := p.VolumeAuthorityLine(fmt.Sprintf("v%06d", i%volumes)); !ok { + t.Fatal("no line") + } + } + if d := time.Since(start) / reads; d < best { + best = d + } + } + return best + } + small, large := perRead(1000), perRead(64000) + t.Logf("per read: %v at 1,000 volumes, %v at 64,000", small, large) + if large > 8*small+5*time.Microsecond { + t.Fatalf("a read among 64,000 volumes took %v, among 1,000 %v: the read scans every line", large, small) + } +} + +// The index is right only while setStateLocked is the one writer of +// p.state: a source scan of the package's non-test files finds every +// assignment to, delete from or replacement of the state map, and fails on +// any outside it (a new writer must keep the index too). +func TestLineIndexHasOneWriter(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + write := regexp.MustCompile(`\bp\.state\[[^\]]*\]\s*=[^=]|\bdelete\(p\.state,|\bp\.state\s*=[^=]`) + var sites []string + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + inSetter := false + for i, line := range strings.Split(string(b), "\n") { + if strings.HasPrefix(line, "func ") { + inSetter = strings.HasPrefix(line, "func (p *Publisher) setStateLocked(") + } + if write.MatchString(line) && !inSetter { + sites = append(sites, fmt.Sprintf("%s:%d: %s", f, i+1, strings.TrimSpace(line))) + } + } + } + if len(sites) != 0 { + t.Fatalf("p.state is written outside setStateLocked, which keeps the line index:\n%s", strings.Join(sites, "\n")) + } +} diff --git a/seaweed-block/core/authority/policy.go b/seaweed-block/core/authority/policy.go index cdf0c14232..11fab3639b 100644 --- a/seaweed-block/core/authority/policy.go +++ b/seaweed-block/core/authority/policy.go @@ -99,7 +99,7 @@ func (p *Publisher) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) func (p *Publisher) volumeLineLocked(volumeID string) (AuthorityBasis, bool) { var best AuthorityBasis any := false - for k, st := range p.state { + for k, st := range p.volumeStateLocked(volumeID) { if !st.present || k.volumeID != volumeID { continue } diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 3bd2de600c..47ed4cceff 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -379,7 +379,7 @@ func (p *Publisher) WorkspaceSourceMoved(volume, replica, server string) (Publis func (p *Publisher) workspaceLineLocked(volume string) (subKey, assignmentState, bool) { var key subKey var line assignmentState - for k, s := range p.state { + for k, s := range p.volumeStateLocked(volume) { if k.volumeID == volume && s.present && s.info.Epoch > line.info.Epoch { key, line = k, s } @@ -550,7 +550,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } } - max := maxPublishedEpochForVolume(p.state, q.VolumeID) + max := maxPublishedEpochForVolume(p.volumeStateLocked(q.VolumeID), q.VolumeID) for _, r := range s.Moves { if r.NewEpoch > max { max = r.NewEpoch diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ef00e39956..832ab8175c 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -157,7 +157,10 @@ type Host struct { lifecycle *LifecycleStores // RPC registration/place/move/ACK/delete and product ticks serialize here. // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). - workspaceMu sync.Mutex + workspaceMu sync.Mutex + // bindingRetry: volumes whose binding reconcile failed, retried with the + // next call's own volume (workspaceMu held). + bindingRetry map[string]bool events *eventRing promotionMu sync.RWMutex promotionProber PromotionEvidenceProvider diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index fd9986d824..3bde3751ac 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -32,7 +32,7 @@ func (s *services) RegisterWorkspaceBinding(ctx context.Context, q *control.Work if err := ctx.Err(); err != nil { return nil, workspaceError(err) } - if err := s.host.reconcileWorkspaceBindings(); err != nil { + if err := s.host.reconcileWorkspaceCall(q.GetVolumeId()); err != nil { return nil, workspaceError(err) } if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok { @@ -133,29 +133,56 @@ func (h *Host) placementSourceHost(volume, replica string) string { // Recover retirement after a crash between the authority ACK/issued record // and binding persistence. Epoch-tagged retirements cannot retire a later // re-registration when an old Move/ACK is retried or replayed on restart. -// Caller owns workspaceMu, or Host.New has not exposed the host yet. +// Caller owns workspaceMu, or Host.New has not exposed the host yet. Every +// volume: the start's pass. func (h *Host) reconcileWorkspaceBindings() error { for _, v := range h.lifecycle.Volumes.ListVolumes() { - volume := v.Spec.VolumeID - state := h.Publisher().WorkspaceState(volume) - if state == nil { - continue + if err := h.reconcileWorkspaceBinding(v.Spec.VolumeID); err != nil { + return err } - for _, m := range state.Moves { - // A move must not retire its own target reservation. A same-host - // successor reuses it; a later ACK still retires that epoch below. - if m.Issued && m.OldHost != m.NewHost { - if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil { - return err - } + } + return nil +} + +// reconcileWorkspaceCall is a call's reconcile (a register, an ACK, a move): +// the call's own volume, and every volume whose reconcile failed before, so a +// failed retirement is retried by the next call as the whole pass did, at the +// cost of the volumes it touches, not every volume. workspaceMu held. +func (h *Host) reconcileWorkspaceCall(volume string) error { + if h.bindingRetry == nil { + h.bindingRetry = map[string]bool{} + } + h.bindingRetry[volume] = true + for v := range h.bindingRetry { + if err := h.reconcileWorkspaceBinding(v); err != nil { + return err + } + delete(h.bindingRetry, v) + } + return nil +} + +// reconcileWorkspaceBinding retires the bindings one volume's moves and ACK +// left behind. +func (h *Host) reconcileWorkspaceBinding(volume string) error { + state := h.Publisher().WorkspaceState(volume) + if state == nil { + return nil + } + for _, m := range state.Moves { + // A move must not retire its own target reservation. A same-host + // successor reuses it; a later ACK still retires that epoch below. + if m.Issued && m.OldHost != m.NewHost { + if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil { + return err } } - if a := state.Ack; a != nil { - host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch) - if host != "" { - if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil { - return err - } + } + if a := state.Ack; a != nil { + host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch) + if host != "" { + if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil { + return err } } } diff --git a/seaweed-block/core/host/master/workspace_binding_call_test.go b/seaweed-block/core/host/master/workspace_binding_call_test.go new file mode 100644 index 0000000000..8290910075 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_binding_call_test.go @@ -0,0 +1,66 @@ +package master + +import ( + "errors" + "reflect" + "runtime" + "testing" +) + +// A call's binding reconcile (register, ACK, move) is the whole pass +// restricted to the volumes it touches: its own volume, and any volume whose +// reconcile failed before. Another volume's call retires nothing of a volume +// it does not touch; the volume's own call retires exactly what the whole +// pass retires; and an interrupted reconcile is finished by the next call, +// whichever volume that call is for. +func TestWorkspaceBindingCallReconcilesItsVolumeAndRetries(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("requires the binding store's supported directory fsync") + } + want := []bindingRetirement{{"recover", "node-a", 1}, {"recover", "node-b", 2}, {"recover", "node-c", 4}} + + h := bindingReconcileHistory(t, false) + rec := &interruptedBindingStore{workspaceBindingStore: h.lifecycle.WorkspaceBindings} + h.workspaceMu.Lock() + h.lifecycle.WorkspaceBindings = rec + err := h.reconcileWorkspaceCall("other") + h.workspaceMu.Unlock() + if err != nil || len(rec.calls) != 0 { + t.Fatalf("another volume's call retired %+v (%v): it must touch only its own volume", rec.calls, err) + } + h.workspaceMu.Lock() + err = h.reconcileWorkspaceCall("recover") + h.workspaceMu.Unlock() + if err != nil || !reflect.DeepEqual(rec.calls, want) { + t.Fatalf("the volume's own call retired %+v (%v), the whole pass retires %+v", rec.calls, err, want) + } + + h2 := bindingReconcileHistory(t, false) + fault := &interruptedBindingStore{workspaceBindingStore: h2.lifecycle.WorkspaceBindings, at: 2} + h2.workspaceMu.Lock() + h2.lifecycle.WorkspaceBindings = fault + err = h2.reconcileWorkspaceCall("recover") + h2.workspaceMu.Unlock() + if !errors.Is(err, errBindingReconcileInterrupted) { + t.Fatalf("interruption not propagated: %v", err) + } + h2.workspaceMu.Lock() + err = h2.reconcileWorkspaceCall("other") + h2.workspaceMu.Unlock() + if err != nil { + t.Fatal(err) + } + got, _, err := fault.workspaceBindingStore.Get("recover") + if err != nil { + t.Fatal(err) + } + for _, b := range got { + epoch := map[string]uint64{"node-a": 1, "node-b": 2, "node-c": 4}[b.ServerID] + if !b.Retired || b.RetiredEpoch != epoch { + t.Fatalf("the next call did not finish the interrupted volume's retirements: %+v", got) + } + } + if len(h2.bindingRetry) != 0 { + t.Fatalf("volumes still marked for retry: %v", h2.bindingRetry) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index ac134b6fc2..95fa2e3c07 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -243,7 +243,7 @@ func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.Workspace return nil, workspaceError(err) } recorded = time.Now() - if err := s.host.reconcileWorkspaceBindings(); err != nil { + if err := s.host.reconcileWorkspaceCall(id.GetVolumeId()); err != nil { return nil, workspaceError(err) } return &control.WorkspaceEmpty{}, nil @@ -388,7 +388,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) // The move is issued from here on: record it for the audit log before // anything else can fail. issued = s.grantWithLostRange(r) - if err = s.host.reconcileWorkspaceBindings(); err != nil { + if err = s.host.reconcileWorkspaceCall(q.GetVolumeId()); err != nil { postIssue = err return nil, postIssueError(q, err) }