diff --git a/seaweed-block/cmd/blockvolume/replication_ingress.go b/seaweed-block/cmd/blockvolume/replication_ingress.go index 89ab03da31..5ecd7a8eec 100644 --- a/seaweed-block/cmd/blockvolume/replication_ingress.go +++ b/seaweed-block/cmd/blockvolume/replication_ingress.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/seaweedfs/seaweed-block/core/recovery" + "github.com/seaweedfs/seaweed-block/core/replication" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/transport" ) @@ -18,6 +19,7 @@ type replicationIngress struct { mu sync.Mutex addr, volumeID, floorPath string store storage.LogicalStorage + applyGate *replication.ReplicaApplyGate dualLane bool // rf1Only, when set, refuses every role with replica slots with this reason // (walstore-chunk). The host latches the error: no role is adopted, not Healthy. @@ -86,8 +88,12 @@ func (r *replicationIngress) roleLocked(epoch uint64, primary bool) error { listener := r.listener fresh := listener == nil if fresh { + // One version map per replica store, surviving listener role transitions. + if r.applyGate == nil { + r.applyGate = replication.NewReplicaApplyGate(r.store) + } var err error - listener, err = transport.NewReplicaListenerWithFloor(r.addr, r.store, r.volumeID, r.floorPath) + listener, err = transport.NewReplicaListenerWithFloorAndApplyHook(r.addr, r.store, r.volumeID, r.floorPath, r.applyGate) if err != nil { return err } diff --git a/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go new file mode 100644 index 0000000000..eb37cc413b --- /dev/null +++ b/seaweed-block/cmd/blockvolume/replication_ingress_apply_test.go @@ -0,0 +1,52 @@ +package main + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestReplicationIngressSharesApplyVersionsAcrossSessions(t *testing.T) { + store := storage.NewBlockStore(64, 4096) + r := newReplicationIngress(flags{dataAddr: "127.0.0.1:0", volumeID: "vol1"}, store) + if err := r.AdmitAsReplica(1); err != nil { + t.Fatal(err) + } + t.Cleanup(r.Stop) + want := bytes.Repeat([]byte{0xBB}, 4096) + ship := func(session, lsn uint64, data []byte, recovery bool) { + c, err := net.DialTimeout("tcp", r.listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + lineage := transport.RecoveryLineage{SessionID: session, Epoch: 1, EndpointVersion: 1, TargetLSN: 120} + send := func(kind byte, data []byte) { + if err := transport.WriteMsg(c, kind, data); err != nil { + t.Fatal(err) + } + } + if recovery { + send(transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)) + } + send(transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 5, Data: data, LSN: lsn})) + send(transport.MsgBarrierReq, transport.EncodeLineage(lineage)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + ship(1, 120, want, false) + ship(2, 95, bytes.Repeat([]byte{0xAA}, 4096), true) + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("production ingress allowed cross-session byte regression: err=%v", err) + } +} diff --git a/seaweed-block/core/adapter/adapter.go b/seaweed-block/core/adapter/adapter.go index bc79ef4505..8994bc89ab 100644 --- a/seaweed-block/core/adapter/adapter.go +++ b/seaweed-block/core/adapter/adapter.go @@ -384,8 +384,9 @@ func (a *VolumeReplicaAdapter) applyBatchAndExecute(events []engine.Event, event log.EventKind = eventKind } - var cmds []engine.Command + var queued []queuedCommand for _, ev := range events { + var cmds []engine.Command result := engine.Apply(&a.state, ev) a.trace = append(a.trace, result.Trace...) log.Projection = result.Projection @@ -407,21 +408,22 @@ func (a *VolumeReplicaAdapter) applyBatchAndExecute(events []engine.Event, event log.Commands = append(log.Commands, kind) cmds = append(cmds, cmd) } - } - // Feed session lifecycle events back into engine while still under lock - // (these are synchronous, no external calls). - sessionEvents, queued := a.prepareQueuedCommands(cmds) - for _, sev := range sessionEvents { - sr := engine.Apply(&a.state, sev) - a.trace = append(a.trace, sr.Trace...) - log.Projection = sr.Projection - log.Trace = append(log.Trace, sr.Trace...) - for _, cmd := range sr.Commands { - kind := engine.CommandKind(cmd) - a.cmdLog = append(a.cmdLog, kind) - log.Commands = append(log.Commands, kind) - queued = append(queued, queuedCommand{cmd: cmd}) + // Reserve recovery before applying the next event in this observation. + // Otherwise both reachability and facts can emit a Start for an idle slot. + sessionEvents, prepared := a.prepareQueuedCommands(cmds) + queued = append(queued, prepared...) + for _, sev := range sessionEvents { + sr := engine.Apply(&a.state, sev) + a.trace = append(a.trace, sr.Trace...) + log.Projection = sr.Projection + log.Trace = append(log.Trace, sr.Trace...) + for _, cmd := range sr.Commands { + kind := engine.CommandKind(cmd) + a.cmdLog = append(a.cmdLog, kind) + log.Commands = append(log.Commands, kind) + queued = append(queued, queuedCommand{cmd: cmd}) + } } } a.mu.Unlock() @@ -573,6 +575,11 @@ func (a *VolumeReplicaAdapter) executeCommand(q queuedCommand) { a.executor.InvalidateSession(c.ReplicaID, c.SessionID, c.Reason) case engine.PublishHealthy: + if c.CertifiedPrefix != 0 { + if publisher, ok := a.executor.(RecoveryPrefixPublisher); ok { + publisher.PublishRecoveryPrefix(c.ReplicaID, c.RecoverySessionID, c.Epoch, c.EndpointVersion, c.CertifiedPrefix) + } + } a.executor.PublishHealthy(c.ReplicaID) case engine.PublishDegraded: diff --git a/seaweed-block/core/adapter/executor.go b/seaweed-block/core/adapter/executor.go index 8807399726..ba6e284fea 100644 --- a/seaweed-block/core/adapter/executor.go +++ b/seaweed-block/core/adapter/executor.go @@ -163,3 +163,9 @@ type DurableAckResult struct { type DurableAckCallbackSetter interface { SetOnDurableAck(fn OnDurableAck) } + +// RecoveryPrefixPublisher forwards the engine's explicit completed-prefix +// certificate. Plain healthy/probe or storage Sync facts carry no certificate. +type RecoveryPrefixPublisher interface { + PublishRecoveryPrefix(replicaID string, sessionID, epoch, endpointVersion, prefix uint64) +} diff --git a/seaweed-block/core/adapter/normalize.go b/seaweed-block/core/adapter/normalize.go index 341a2ce314..082ab4e768 100644 --- a/seaweed-block/core/adapter/normalize.go +++ b/seaweed-block/core/adapter/normalize.go @@ -111,8 +111,11 @@ func NormalizeAssignment(a AssignmentInfo) engine.Event { // NormalizeProbe converts a probe result into engine events. // A successful probe produces up to 2 events: -// 1. ProbeSucceeded (reachability) -// 2. RecoveryFactsObserved (R/S/H boundaries) +// 1. RecoveryFactsObserved (R/S/H boundaries) +// 2. ProbeSucceeded (reachability) +// +// Fresh boundaries precede reachability so its decision cannot reserve a +// recovery using the previous probe's retention window. // // A failed probe produces 1 event: // 1. ProbeFailed @@ -132,6 +135,12 @@ func NormalizeProbe(p ProbeResult) []engine.Event { } events := []engine.Event{ + engine.RecoveryFactsObserved{ + ReplicaID: p.ReplicaID, + EndpointVersion: p.EndpointVersion, + TransportEpoch: p.TransportEpoch, + R: p.ReplicaFlushedLSN, S: p.PrimaryTailLSN, H: p.PrimaryHeadLSN, + }, engine.ProbeSucceeded{ ReplicaID: p.ReplicaID, EndpointVersion: p.EndpointVersion, @@ -139,15 +148,6 @@ func NormalizeProbe(p ProbeResult) []engine.Event { }, } - events = append(events, engine.RecoveryFactsObserved{ - ReplicaID: p.ReplicaID, - EndpointVersion: p.EndpointVersion, - TransportEpoch: p.TransportEpoch, - R: p.ReplicaFlushedLSN, - S: p.PrimaryTailLSN, - H: p.PrimaryHeadLSN, - }) - return events } diff --git a/seaweed-block/core/adapter/recovery_dedup_test.go b/seaweed-block/core/adapter/recovery_dedup_test.go new file mode 100644 index 0000000000..721c937c33 --- /dev/null +++ b/seaweed-block/core/adapter/recovery_dedup_test.go @@ -0,0 +1,124 @@ +package adapter + +import ( + "strconv" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/engine" +) + +func dedupAdapter(t *testing.T) (*VolumeReplicaAdapter, *mockExecutor, ProbeResult) { + t.Helper() + exec := newMockExecutor() + exec.autoClose = false + // The automatic probe is irrelevant to this controlled delivery schedule. + // Its wrong-replica result is rejected regardless of when it returns. + exec.probeResults["r1"] = ProbeResult{ReplicaID: "other"} + a := NewVolumeReplicaAdapter(exec) + a.OnAssignment(AssignmentInfo{VolumeID: "vol1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + probe := ProbeResult{ReplicaID: "r1", Success: true, EndpointVersion: 1, TransportEpoch: 1, + ReplicaFlushedLSN: 50, PrimaryTailLSN: 10, PrimaryHeadLSN: 100} + a.OnProbeResult(probe) + t.Cleanup(func() { + exec.mu.Lock() + var sid, target uint64 + for _, start := range exec.starts { + if start.sessionID > sid { + sid, target = start.sessionID, start.targetLSN + } + } + exec.mu.Unlock() + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: sid, Success: true, AchievedLSN: target}) + }) + return a, exec, probe +} + +func TestAdapter_OneRecoveryPreparedWithinProbeBatch(t *testing.T) { + a, exec, probe := dedupAdapter(t) + sid := exec.latestSessionID("StartCatchUp") + // A failed start permits a new probe to retry. Both reachability and facts + // in that one probe must see the first newly prepared recovery session. + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: sid, FailureKind: engine.RecoveryFailureStartTimeout}) + a.OnProbeResult(probe) + if got := countStarts(exec, "StartCatchUp"); got != 2 { + t.Fatalf("one probe batch emitted duplicate recovery: starts=%d want initial+one retry", got) + } +} + +func TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery(t *testing.T) { + a, exec, probe := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), FailureKind: engine.RecoveryFailureStartTimeout}) + probe.PrimaryTailLSN = 60 // the former catch-up prefix is now recycled + a.OnProbeResult(probe) + if catchup, rebuild := countStarts(exec, "StartCatchUp"), countStarts(exec, "StartRebuild"); catchup != 1 || rebuild != 1 { + t.Fatalf("probe reserved recovery from stale bounds: catchup=%d rebuild=%d", catchup, rebuild) + } +} + +func TestAdapter_OneRecoveryFromPostCloseStalledAck(t *testing.T) { + for _, kind := range []string{"StartCatchUp", "StartRebuild"} { + t.Run(kind, func(t *testing.T) { + a, exec, _ := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + initial, tail := 1, uint64(10) + if kind == "StartRebuild" { + initial, tail = 0, 110 + } + for i := 0; i < 8; i++ { + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: tail, PrimaryHeadLSN: uint64(200 + i)}) + if got := countStarts(exec, kind); got > initial { + if got != initial+1 { + t.Fatalf("one stalled ack emitted duplicate recovery: kind=%s starts=%d want=%d", kind, got, initial+1) + } + return + } + } + t.Fatal("stalled ack never requested legitimate new recovery") + }) + } +} + +func TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery(t *testing.T) { + for _, n := range []int{8, 5} { + t.Run(strconv.Itoa(n), func(t *testing.T) { + a, exec, probe := dedupAdapter(t) + a.OnSessionClose(SessionCloseResult{ReplicaID: "r1", SessionID: exec.latestSessionID("StartCatchUp"), Success: true, AchievedLSN: 100}) + a.OnDurableAck(DurableAckResult{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + if p := a.Projection(); p.Mode != engine.ModeHealthy { + t.Fatalf("precondition not healthy: %+v", p) + } + var wg sync.WaitGroup + start := make(chan struct{}) + for i := 0; i < n; i++ { + wg.Add(1) + go func() { defer wg.Done(); <-start; a.OnProbeResult(probe) }() + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(start) }) } + t.Cleanup(func() { + release() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("concurrent probe workers did not settle during cleanup") + } + }) + release() + select { + case <-done: + case <-time.After(3 * time.Second): + t.Fatal("concurrent probe workers did not settle") + } + if got := countStarts(exec, "StartCatchUp"); got != 1 { + t.Fatalf("identical delayed probes restarted healthy recovery: starts=%d path=%v", got, a.CommandLog()) + } + if p := a.Projection(); p.Mode != engine.ModeHealthy { + t.Fatalf("old facts regressed healthy replica: %+v", p) + } + }) + } +} diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 52f8d7fe1f..85e5bd9bcf 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -172,6 +172,10 @@ type Publisher struct { leaseClosing bool extWG sync.WaitGroup extendFailures map[string]int // guarded by mu + + // testAfterIssuePublish, when set by a test, runs under mu right after + // an issued move's lease view is published. + testAfterIssuePublish func(volume string) } // PublicationAdmission surrounds an ordinary mint with local ownership/lifetime @@ -478,9 +482,10 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } var issuedWorkspace *WorkspaceState var reservedEpoch uint64 + var issuedAt time.Time if grant != nil { var err error - issuedWorkspace, reservedEpoch, err = p.prepareWorkspaceMoveLocked(ask, *grant) + issuedWorkspace, reservedEpoch, issuedAt, err = p.prepareWorkspaceMoveLocked(ask, *grant) if err != nil { p.mu.Unlock() return err @@ -609,9 +614,14 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr } p.state[k] = assignmentState{info: next, present: true} - p.refreshLeaseViewLocked(ask.VolumeID) if issuedWorkspace != nil { - p.setLeaseDeadlineLocked(ask.VolumeID, time.Time{}, false) // the issued move clears the lease + // The issued move starts the new holder's lease (issuedAt+TTL grant). + p.publishIssuedLeaseLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL)) + if hook := p.testAfterIssuePublish; hook != nil { + hook(ask.VolumeID) + } + } else { + p.refreshLeaseViewLocked(ask.VolumeID) } // Snapshot subscribers under lock, release the lock BEFORE diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 6d6301e1b3..b197774f0d 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -270,29 +270,81 @@ func sameWorkspaceRequest(r WorkspaceMoveRecord, q WorkspaceMoveRequest) bool { r.TargetDataAddr == q.TargetDataAddr && r.TargetCtrlAddr == q.TargetCtrlAddr } +// WorkspaceForcedMoveAdmitted reports whether a forced move of volume away +// from holder at epoch is admitted now: the lease expiry and the granted or +// restart deadline, each plus the clock-skew margin, have passed. A caller +// reads HEAD only after this returns nil: by then the holder's own lease has +// expired, so it starts no new claim or cut. HEAD is not frozen: a claim the +// holder or an earlier one sent may still land (ownership only, RemoteLSN +// unchanged), and the next holder's higher-epoch claim supersedes it. The +// move itself checks admission again. A request id the journal already holds is +// left to MoveWorkspace: its replay never uses a new HEAD. +func (p *Publisher) WorkspaceForcedMoveAdmitted(ctx context.Context, volume, requestID, holder string, epoch uint64) error { + if err := ctx.Err(); err != nil { + return err + } + p.mu.Lock() + defer p.mu.Unlock() + _, line, ok := p.workspaceLineLocked(volume) + s := p.workspace[volume] + if s != nil { + for _, r := range s.Moves { + if r.RequestID == requestID { + return nil + } + } + } + if !ok || line.info.Epoch != epoch || line.info.ReplicaID != holder || s == nil || s.Lease == nil { + return fmt.Errorf("workspace move: missing or changed authority/lease") + } + _, err := p.forcedMoveAdmissionLocked(volume, s.Lease) + return err +} + +// forcedMoveAdmissionLocked returns the audit bound of the lost range when a +// forced move is admitted. Caller holds p.mu. +func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLease) (int64, error) { + now := p.workspaceNow() + skew := p.workspaceSkew(lease) + deadline := p.leaseDeadlineLocked(volume) + if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { + return 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") + } + // The audit bound only, in wall time: the admission above keeps both + // predicates (the deadline's monotonic reading included). + lostUntil := time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() + if d := deadline.Add(skew).UnixNano(); d > lostUntil { + lostUntil = d + } + return lostUntil, nil +} + +// issueWorkspaceMove marks the move issued and starts the new holder's lease +// in the same write as the new epoch, so a holder that dies before its first +// renewal still leaves a lease that expires and admits a forced move. +func (p *Publisher) issueWorkspaceMove(s *WorkspaceState, idx int, now time.Time) { + r := &s.Moves[idx] + r.Issued = true + s.Lease, _ = p.newWorkspaceLease(r.NewReplicaID, r.NewEpoch, now) + s.Ack = nil +} + // Called only under Publisher.mu. First persist a reservation with the OLD // assignment. The subsequent authority write includes that same journal record. // A crash at either boundary cannot expose an epoch without its grant record. -func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGrant) (*WorkspaceState, uint64, error) { +// The returned time is the issue time the new holder's lease starts from. +func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGrant) (*WorkspaceState, uint64, time.Time, error) { q, h := g.request, g.head _, line, ok := p.workspaceLineLocked(q.VolumeID) s := cloneWorkspace(p.workspace[q.VolumeID]) if !ok || line.info.Epoch != q.ExpectedEpoch || line.info.ReplicaID != q.ExpectedReplicaID || s == nil || s.Lease == nil { - return nil, 0, fmt.Errorf("workspace move: missing or changed authority/lease") + return nil, 0, time.Time{}, fmt.Errorf("workspace move: missing or changed authority/lease") } var lostUntil int64 if q.Kind == "forced" { - now := p.workspaceNow() - skew := p.workspaceSkew(s.Lease) - deadline := p.leaseDeadlineLocked(q.VolumeID) - if now.Before(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { - return nil, 0, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") - } - // The audit bound only, in wall time: the admission above keeps both - // predicates (the deadline's monotonic reading included). - lostUntil = time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).UnixNano() - if d := deadline.Add(skew).UnixNano(); d > lostUntil { - lostUntil = d + var err error + if lostUntil, err = p.forcedMoveAdmissionLocked(q.VolumeID, s.Lease); err != nil { + return nil, 0, time.Time{}, err } } // A restart may resume the identical durable reservation; it never grants @@ -300,7 +352,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra for idx, r := range s.Moves { if r.RequestID == q.RequestID { if r.Issued || !sameWorkspaceRequest(r, q) { - return nil, 0, fmt.Errorf("workspace move reservation differs") + return nil, 0, time.Time{}, fmt.Errorf("workspace move reservation differs") } // A forced reservation issues only with the exact range recorded // before it; a missing one (a reservation older than lost ranges, @@ -308,21 +360,29 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra // request records a fresh range. if r.Kind == "forced" { if _, ok := p.lostRangeLocked(q.VolumeID, r.RequestID, r.NewEpoch); !ok { - return nil, 0, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) + return nil, 0, time.Time{}, fmt.Errorf("workspace forced move reservation %s has no recorded lost range; retry with a new request id", r.RequestID) } } - s.Moves[idx].Issued = true - s.Lease = nil - s.Ack = nil - return s, r.NewEpoch, nil + now := p.workspaceNow() + p.issueWorkspaceMove(s, idx, now) + return s, r.NewEpoch, now, nil } } - if h.Gen == 0 || h.Epoch != q.ExpectedEpoch || h.Holder != q.ExpectedHost+"/"+q.ExpectedReplicaID { - return nil, 0, fmt.Errorf("workspace move: HEAD not owned by expected holder") + owned := h.Gen != 0 && h.Epoch == q.ExpectedEpoch && h.Holder == q.ExpectedHost+"/"+q.ExpectedReplicaID + if !owned && q.Kind == "forced" { + // Admitted (the expected holder's lease has expired) and HEAD read + // after that: a HEAD at an older epoch means the expected holder + // never claimed it, or an earlier holder's late claim landed. The + // lost range starts at this HEAD's RemoteLSN. A HEAD at the expected + // or a higher epoch that is not the expected holder's stays refused. + owned = h.Gen != 0 && h.Epoch < q.ExpectedEpoch + } + if !owned { + return nil, 0, time.Time{}, fmt.Errorf("workspace move: HEAD not owned by expected holder") } if q.Kind == "clean" { if !h.Detached || !s.Lease.Revoking || s.Ack == nil || s.Ack.ReplicaID != q.ExpectedReplicaID || s.Ack.Epoch != q.ExpectedEpoch || s.Ack.HeadGen != h.Gen { - return nil, 0, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") + return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } } max := maxPublishedEpochForVolume(p.state, q.VolumeID) @@ -332,22 +392,21 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra } } if max == ^uint64(0) { - return nil, 0, fmt.Errorf("workspace epoch exhausted") + return nil, 0, time.Time{}, fmt.Errorf("workspace epoch exhausted") } r := WorkspaceMoveRecord{RequestID: q.RequestID, VolumeID: q.VolumeID, OldHost: q.ExpectedHost, NewHost: q.TargetHost, OldReplicaID: q.ExpectedReplicaID, NewReplicaID: q.TargetReplicaID, Kind: q.Kind, OldEpoch: q.ExpectedEpoch, NewEpoch: max + 1, HeadGen: h.Gen, RemoteLSN: h.RemoteLSN, TargetDataAddr: q.TargetDataAddr, TargetCtrlAddr: q.TargetCtrlAddr} if q.Kind == "forced" { lost := WorkspaceLostRange{RequestID: r.RequestID, NewEpoch: r.NewEpoch, OldReplicaID: r.OldReplicaID, OldEpoch: r.OldEpoch, LostAfterLSN: r.RemoteLSN, LostUntilNS: lostUntil} if err := p.recordLostRangeLocked(q.VolumeID, lost); err != nil { - return nil, 0, err + return nil, 0, time.Time{}, err } } s.Moves = append(s.Moves, r) if err := p.persistWorkspaceLocked(q.VolumeID, s); err != nil { - return nil, 0, err + return nil, 0, time.Time{}, err } - s.Moves[len(s.Moves)-1].Issued = true - s.Lease = nil - s.Ack = nil - return s, r.NewEpoch, nil + now := p.workspaceNow() + p.issueWorkspaceMove(s, len(s.Moves)-1, now) + return s, r.NewEpoch, now, nil } diff --git a/seaweed-block/core/authority/workspace_forced_admission_test.go b/seaweed-block/core/authority/workspace_forced_admission_test.go new file mode 100644 index 0000000000..39329f88fc --- /dev/null +++ b/seaweed-block/core/authority/workspace_forced_admission_test.go @@ -0,0 +1,36 @@ +package authority + +import ( + "context" + "strings" + "testing" + "time" +) + +// WorkspaceForcedMoveAdmitted gives the move's own answer: refused before +// the lease expiry plus skew, admitted at it; a journaled request id is left +// to MoveWorkspace (its replay uses no new HEAD). +func TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + barrier := issued.Add(grantTTL + grantTTL/2 + p.workspaceSkew(p.WorkspaceState("v").Lease)) + now = barrier.Add(-time.Nanosecond) + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("admitted before expiry+skew: %v", err) + } + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 1); err == nil || !strings.Contains(err.Error(), "missing or changed authority/lease") { + t.Fatalf("admitted a stale epoch: %v", err) + } + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "clean", "r", 1); err != nil { + t.Fatalf("a journaled request id must be left to MoveWorkspace: %v", err) + } + now = barrier + if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err != nil { + t.Fatal("refused after expiry+skew:", err) + } + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/authority/workspace_issue_publish_structure_test.go b/seaweed-block/core/authority/workspace_issue_publish_structure_test.go new file mode 100644 index 0000000000..c9ca23bcb6 --- /dev/null +++ b/seaweed-block/core/authority/workspace_issue_publish_structure_test.go @@ -0,0 +1,166 @@ +package authority + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// publisherMethods parses this package's production files and returns every +// *Publisher method declaration by name. +func publisherMethods(t *testing.T) map[string]*ast.FuncDecl { + t.Helper() + paths, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + out := map[string]*ast.FuncDecl{} + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + src, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + file, err := parser.ParseFile(fset, path, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range file.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Recv == nil || len(fn.Recv.List) != 1 || fn.Body == nil { + continue + } + typ := fn.Recv.List[0].Type + if star, ok := typ.(*ast.StarExpr); ok { + typ = star.X + } + if id, ok := typ.(*ast.Ident); ok && id.Name == "Publisher" { + out[fn.Name.Name] = fn + } + } + } + return out +} + +// leaseMuCall reports whether call is .leaseMu.(). +func leaseMuCall(call *ast.CallExpr, method string) bool { + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != method { + return false + } + inner, ok := sel.X.(*ast.SelectorExpr) + return ok && inner.Sel.Name == "leaseMu" +} + +// The issued move's lease view and its initial deadline are published in +// ONE leaseMu hold (INV-LEASE-VIEW-001): a renewal of the new epoch sees both +// or neither. Structural guard: publishIssuedLeaseLocked takes leaseMu +// exactly once, holds it (deferred unlock) across both the derived-view and +// the deadline assignment, and calls no other Publisher method that takes +// leaseMu, directly or transitively. A split into two sections (for example +// refreshLeaseViewLocked then setLeaseDeadlineLocked) fails it. +func TestWorkspaceIssuePublishIsOneLeaseHold(t *testing.T) { + methods := publisherMethods(t) + callees := map[string][]string{} + direct := map[string]bool{} + for name, fn := range methods { + ast.Inspect(fn.Body, func(n ast.Node) bool { + call, ok := n.(*ast.CallExpr) + if !ok { + return true + } + if leaseMuCall(call, "Lock") { + direct[name] = true + } else if sel, ok := call.Fun.(*ast.SelectorExpr); ok { + if _, isMethod := methods[sel.Sel.Name]; isMethod { + callees[name] = append(callees[name], sel.Sel.Name) + } + } + return true + }) + } + takes := map[string]bool{} + for name := range direct { + takes[name] = true + } + for changed := true; changed; { + changed = false + for name, cs := range callees { + for _, c := range cs { + if takes[c] && !takes[name] { + takes[name], changed = true, true + } + } + } + } + // The analysis is not vacuous: the two halves of a split publication + // are known lease-taking methods. + for _, name := range []string{"refreshLeaseViewLocked", "setLeaseDeadlineLocked", "leaseDeadlineLocked"} { + if !takes[name] { + t.Fatalf("structure scan does not see %s take leaseMu; the guard would be vacuous", name) + } + } + + fn := methods["publishIssuedLeaseLocked"] + if fn == nil { + t.Fatal("publishIssuedLeaseLocked not found") + } + var locks, unlocks, deferredUnlocks int + var lockPos token.Pos + var viewSet, deadlineSet []token.Pos + var lockingCallees []string + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.DeferStmt: + if leaseMuCall(x.Call, "Unlock") { + deferredUnlocks++ + return false + } + case *ast.CallExpr: + switch { + case leaseMuCall(x, "Lock"): + locks++ + lockPos = x.Pos() + case leaseMuCall(x, "Unlock"): + unlocks++ + default: + if sel, ok := x.Fun.(*ast.SelectorExpr); ok && takes[sel.Sel.Name] { + lockingCallees = append(lockingCallees, sel.Sel.Name) + } + } + case *ast.AssignStmt: + for _, lhs := range x.Lhs { + if sel, ok := lhs.(*ast.SelectorExpr); ok { + switch sel.Sel.Name { + case "d": + viewSet = append(viewSet, x.Pos()) + case "deadline": + deadlineSet = append(deadlineSet, x.Pos()) + } + } + } + } + return true + }) + if locks != 1 || deferredUnlocks != 1 || unlocks != 0 { + t.Fatalf("publishIssuedLeaseLocked must take leaseMu exactly once and hold it to return (defer Unlock): Lock %d, deferred Unlock %d, explicit Unlock %d", locks, deferredUnlocks, unlocks) + } + if len(lockingCallees) != 0 { + t.Fatalf("publishIssuedLeaseLocked calls methods that take leaseMu (a second lease hold): %v", lockingCallees) + } + if len(viewSet) == 0 || len(deadlineSet) == 0 { + t.Fatalf("publishIssuedLeaseLocked must set both the derived view (lv.d: %d) and the deadline (lv.deadline: %d)", len(viewSet), len(deadlineSet)) + } + for _, pos := range append(append([]token.Pos{}, viewSet...), deadlineSet...) { + if pos < lockPos { + t.Fatal("publishIssuedLeaseLocked sets the view or the deadline before taking leaseMu") + } + } +} diff --git a/seaweed-block/core/authority/workspace_issue_publish_test.go b/seaweed-block/core/authority/workspace_issue_publish_test.go new file mode 100644 index 0000000000..3c650a87dc --- /dev/null +++ b/seaweed-block/core/authority/workspace_issue_publish_test.go @@ -0,0 +1,62 @@ +package authority + +import ( + "context" + "testing" + "time" +) + +// A renewal of the new epoch that lands right after an issued move is +// published (the seam runs under the publisher lock, where only the leaf +// renewal path can run) raises the deadline; the issue must not lower it +// afterwards, or a later renewal inside that outstanding grant is refused. +func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + now = now.Add(100 * time.Millisecond) + issued := now + var grant WorkspaceLease + var hooked int + p.testAfterIssuePublish = func(volume string) { + hooked++ + now = issued.Add(200 * time.Millisecond) + l, err := p.RenewWorkspaceLease(ctx, volume, "r", 2) + if err != nil { + t.Errorf("renewal of the new epoch at the issue publication: %v", err) + return + } + grant = l + } + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + if r, err := p.MoveWorkspace(ctx, req, predecessorHead); err != nil || r.NewEpoch != 2 { + t.Fatal("clean move:", r, err) + } + p.testAfterIssuePublish = nil + if hooked != 1 || grant.Epoch != 2 || grant.ExpiresAtNS != issued.Add(200*time.Millisecond+grantTTL).UnixNano() { + t.Fatalf("seam ran %d times, grant %+v", hooked, grant) + } + if got := p.leaseDeadlineLockedForTest("v"); got.UnixNano() < grant.ExpiresAtNS { + t.Fatalf("the issue lowered the deadline to %s below the outstanding grant %s", got, time.Unix(0, grant.ExpiresAtNS)) + } + // Past issue+TTL but inside the outstanding grant: the holder still renews. + now = issued.Add(grantTTL + 50*time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("renewal inside the outstanding grant:", err) + } + assertLeaseViewMatches(t, p, "after issue and renewal") + p.CloseWorkspaceExtenders() +} diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 2a43a9c5b9..7d35415762 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -186,8 +186,10 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { t.Fatal(err) } check("clean move issued") - if p.leaseDeadlineLockedForTest("v") != (time.Time{}) { - t.Fatal("move issue kept the old deadline") + // The issue replaces the old holder's deadline with the new holder's + // first grant: issue time (10 s) + TTL. + if got := p.leaseDeadlineLockedForTest("v"); !got.Equal(c.sec(40)) { + t.Fatalf("move issue deadline %s; want the new holder's issue+TTL %s", got, c.sec(40)) } // w: forced move whose issue write fails after the reservation persisted. c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20) @@ -940,10 +942,13 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if extensions.Load() == 0 { t.Fatal("no horizon-extension write was observed") } - if st := p.WorkspaceState(vol(forcedVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" { + // An issued move starts the new holder's lease at the new epoch. + if st := p.WorkspaceState(vol(forcedVol)); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" || + st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { t.Fatalf("forced move not issued: %+v", st) } - if st := p.WorkspaceState(vol(cleanVol)); st == nil || st.Lease != nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" { + if st := p.WorkspaceState(vol(cleanVol)); st == nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" || + st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { t.Fatalf("clean move not issued: %+v", st) } assertLeaseViewMatches(t, p, "after concurrency") @@ -959,8 +964,8 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } for i := 0; i < n; i++ { st := p.WorkspaceState(vol(i)) - if st == nil || st.Lease == nil { - continue // a completed move cleared the lease (out of S1's scope) + if st == nil || st.Lease == nil || st.Lease.Epoch != 1 { + continue // a completed move started the next epoch's lease (out of S1's scope) } if onDisk[vol(i)] < st.Lease.ExpiresAtNS || st.Lease.ExpiresAtNS < maxGrant[i].Load() { t.Fatalf("%s: S1 broken: disk %d, published horizon %d, max grant %d", vol(i), onDisk[vol(i)], st.Lease.ExpiresAtNS, maxGrant[i].Load()) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index 6cfc82d8a5..758c86766b 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -68,6 +68,25 @@ func (p *Publisher) refreshLeaseViewLocked(volume string) { lv.d = d } +// publishIssuedLeaseLocked publishes an issued move's derived view (the new +// epoch and the new holder's lease) and that lease's initial deadline in one +// leaseMu section: a renewal of the new epoch sees both or neither, so the +// issue never lowers a deadline a renewal has raised. Caller holds p.mu. +func (p *Publisher) publishIssuedLeaseLocked(volume string, deadline time.Time) { + d := p.deriveLeaseLocked(volume) + p.leaseMu.Lock() + defer p.leaseMu.Unlock() + lv := p.leaseViews[volume] + if lv == nil { + lv = &leaseView{} + p.leaseViews[volume] = lv + } + lv.d = d + if deadline.After(lv.deadline) { + lv.deadline = deadline + } +} + // leaseDeadlineLocked reads the granted deadline. Caller holds p.mu. func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { p.leaseMu.Lock() @@ -78,7 +97,7 @@ func (p *Publisher) leaseDeadlineLocked(volume string) time.Time { return time.Time{} } -// setLeaseDeadlineLocked replaces the deadline (restart rule, move issue) or, +// setLeaseDeadlineLocked replaces the deadline (restart rule) or, // with raise, raises it to at least t (a grant). Caller holds p.mu. func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise bool) { d := p.deriveLeaseLocked(volume) @@ -201,7 +220,8 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri } // firstWorkspaceGrant creates a lease synchronously under p.mu (one write per -// assignment epoch). A host whose first renewal fails does not fence: it has +// assignment epoch) for an epoch that has none: a move issue already started +// its holder's lease. A host whose first renewal fails does not fence: it has // no deadline yet and retries. The durable horizon starts at now+1.5*TTL. func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { p.mu.Lock() @@ -226,17 +246,22 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri p.mu.Unlock() return WorkspaceLease{}, fmt.Errorf("workspace lease: created concurrently; retry") } - now := p.workspaceNow() - skew := int64(p.workspaceSkew(nil)) - grant := now.Add(p.workspaceTTL) - s.Lease = &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: skew} + lease, grant := p.newWorkspaceLease(holder, epoch, p.workspaceNow()) + s.Lease = lease if err := p.persistWorkspaceLocked(volume, s); err != nil { p.mu.Unlock() return WorkspaceLease{}, err } p.setLeaseDeadlineLocked(volume, grant, true) p.mu.Unlock() - return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: skew}, nil + return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil +} + +// newWorkspaceLease starts a lease at now: the durable horizon is +// now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a +// move issue start a lease this way. +func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) { + return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } // extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go new file mode 100644 index 0000000000..d57b36760e --- /dev/null +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -0,0 +1,313 @@ +package authority + +import ( + "context" + "strings" + "sync/atomic" + "testing" + "time" +) + +// countPutStore counts authority writes. +type countPutStore struct { + AuthorityStore + puts atomic.Int64 +} + +func (s *countPutStore) Put(r DurableRecord) error { + s.puts.Add(1) + return s.AuthorityStore.Put(r) +} + +const grantTTL = time.Second + +// The predecessor's detached HEAD: the grantee of the clean move below never +// claims it, so HEAD keeps naming the predecessor. +var predecessorHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/r", RemoteLSN: 42, Detached: true} + +// cleanMoveToGrantee binds v to r at epoch 1, then moves it cleanly from +// old-node to new-node (epoch 2) at the returned issue time. +func cleanMoveToGrantee(t *testing.T, store AuthorityStore, now *time.Time) (*Publisher, time.Time) { + t.Helper() + ctx := context.Background() + p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return *now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + *now = now.Add(100 * time.Millisecond) + req := WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} + r, err := p.MoveWorkspace(ctx, req, predecessorHead) + if err != nil || !r.Issued || r.NewEpoch != 2 { + t.Fatal("clean move to the grantee:", r, err) + } + return p, *now +} + +// assertGranteeLease checks the lease the move issue started: the grantee's +// identity at the new epoch, horizon issue+1.5*TTL, not revoking, no ACK. +func assertGranteeLease(t *testing.T, p *Publisher, issued time.Time) { + t.Helper() + st := p.WorkspaceState("v") + want := WorkspaceLease{ReplicaID: "r", Epoch: 2, ExpiresAtNS: issued.Add(grantTTL + grantTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))} + if st == nil || st.Lease == nil || *st.Lease != want || st.Ack != nil { + t.Fatalf("move issue must start the grantee's lease %+v; state %+v", want, st) + } +} + +func forcedFromGrantee(id string) WorkspaceMoveRequest { + return WorkspaceMoveRequest{RequestID: id, VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} +} + +// A grantee that dies between its grant and its HEAD claim never renews: +// the lease the move issue started expires, and a forced move to a third +// host is admitted after its expiry plus the skew margin, never before. The +// same holds when blockmaster restarts between the issue and the forced move. +func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) { + for _, restart := range []bool{false, true} { + name := "same-master" + if restart { + name = "restart" + } + t.Run(name, func(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + assertGranteeLease(t, p, issued) + assertLeaseViewMatches(t, p, "after issue") + if lease, ok := p.WorkspaceLeaseReply("v"); !ok || lease.Epoch != 2 || lease.ExpiresAtNS != issued.Add(grantTTL).UnixNano() { + t.Fatalf("reported lease after issue: %+v %v; want the issue+TTL grant", lease, ok) + } + if restart { + now = now.Add(200 * time.Millisecond) + p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + assertGranteeLease(t, p, issued) + assertLeaseViewMatches(t, p, "after restart") + } + skew := p.workspaceSkew(p.WorkspaceState("v").Lease) + // The horizon (issue+1.5*TTL) is the later bound: the deadline is + // issue+TTL, or restart+TTL after a restart 0.2*TTL later. + barrier := issued.Add(grantTTL + grantTTL/2 + skew) + // The predecessor's lease (renewed 0.1 s before the issue) has + // expired plus skew by then: only the grant's lease may admit. + if old := issued.Add(-100*time.Millisecond + grantTTL + grantTTL/2 + skew); !barrier.Add(-time.Nanosecond).After(old) { + t.Fatal("test clock does not separate the predecessor's barrier from the grant's") + } + now = barrier.Add(-time.Nanosecond) + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("forced move before expiry+skew: %v", err) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { + t.Fatal("early refusal changed authority or journal", line) + } + now = barrier + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), predecessorHead) + if err != nil { + t.Fatal("forced move after expiry+skew:", err) + } + if !r.Issued || r.NewEpoch != 3 || r.NewHost != "third-node" || r.HeadGen != predecessorHead.Gen || r.RemoteLSN != predecessorHead.RemoteLSN { + t.Fatalf("forced grant %+v", r) + } + lost := p.WorkspaceLostRanges("v") + if len(lost) != 1 || lost[0].NewEpoch != 3 || lost[0].OldEpoch != 2 || lost[0].LostAfterLSN != predecessorHead.RemoteLSN { + t.Fatalf("lost range %+v", lost) + } + if st := p.WorkspaceState("v"); st.Lease == nil || st.Lease.Epoch != 3 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("forced issue must start the next holder's lease: %+v", st.Lease) + } + assertLeaseViewMatches(t, p, "after forced move") + }) + } +} + +// The HEAD rule: after admission, a forced move from a grantee that never +// claimed HEAD accepts any HEAD at an older epoch (its Gen and RemoteLSN may +// have moved, e.g. by an earlier holder's late claim); the lost range starts +// at that HEAD's RemoteLSN. A HEAD at the expected or a higher epoch that is +// not the grantee's, or no HEAD, is refused. Clean moves never accept it. +func TestWorkspaceUnclaimedGrantHEADRule(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + + // Clean: even with the grantee's revocation ACK naming that HEAD + // generation, the predecessor's HEAD is not the grantee's. + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 2); err != nil { + t.Fatal("revoke the grantee's issued lease:", err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 2, HeadGen: predecessorHead.Gen}); err != nil { + t.Fatal(err) + } + clean := forcedFromGrantee("clean-2") + clean.Kind, clean.Force = "clean", false + if _, err := p.MoveWorkspace(ctx, clean, predecessorHead); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { + t.Fatalf("clean move accepted the predecessor's HEAD: %v", err) + } + + now = issued.Add(10 * grantTTL) + refused := map[string]WorkspaceHead{} + h := predecessorHead + h.Epoch = 2 + refused["expected epoch, another holder"] = h + h = WorkspaceHead{Gen: 9, Epoch: 3, Holder: "third-node/r", RemoteLSN: 50} + refused["epoch above expected"] = h + h = predecessorHead + h.Gen = 0 + refused["no HEAD"] = h + for what, h := range refused { + if _, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-"+what), h); err == nil || !strings.Contains(err.Error(), "HEAD not owned by expected holder") { + t.Fatalf("%s: forced move accepted %+v: %v", what, h, err) + } + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(p.WorkspaceState("v").Moves) != 1 { + t.Fatal("a refused HEAD changed authority or journal", line) + } + // An older-epoch HEAD whose Gen and RemoteLSN moved since the issue. + moved := predecessorHead + moved.Gen, moved.RemoteLSN = predecessorHead.Gen+1, predecessorHead.RemoteLSN+8 + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced"), moved) + if err != nil || r.NewEpoch != 3 || r.HeadGen != moved.Gen || r.RemoteLSN != moved.RemoteLSN { + t.Fatal("forced move with an older-epoch HEAD:", r, err) + } + if lost := p.WorkspaceLostRanges("v"); len(lost) != 1 || lost[0].LostAfterLSN != moved.RemoteLSN { + t.Fatalf("lost range must start at the fresh HEAD's RemoteLSN: %+v", lost) + } + // A chain: the epoch-3 grantee dies unclaimed too. + now = now.Add(10 * grantTTL) + next := forcedFromGrantee("forced-again") + next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 + if r, err := p.MoveWorkspace(ctx, next, moved); err != nil || r.NewEpoch != 4 { + t.Fatal("second unclaimed grant:", r, err) + } +} + +// The grantee's first renewal is an ordinary renewal of the lease the issue +// started: no authority write, no new epoch; the old epoch stays refused. +func TestWorkspaceUnclaimedGrantGranteeRenewsNormally(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + store := &countPutStore{AuthorityStore: disk} + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, store, &now) + writes := store.puts.Load() + now = issued.Add(100 * time.Millisecond) + l, err := p.RenewWorkspaceLease(ctx, "v", "r", 2) + if err != nil { + t.Fatal("grantee's first renewal:", err) + } + if l.Epoch != 2 || l.ReplicaID != "r" || l.ExpiresAtNS != now.Add(grantTTL).UnixNano() { + t.Fatalf("first renewal %+v", l) + } + if store.puts.Load() != writes { + t.Fatalf("first renewal wrote %d authority records; the issue already persisted the lease", store.puts.Load()-writes) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("old epoch renewed after the move") + } + // Past 0.25*TTL the renewal starts an extension of the issued lease. + now = issued.Add(grantTTL / 2) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal(err) + } + st := p.WorkspaceState("v") + for wait := time.Now().Add(5 * time.Second); time.Now().Before(wait) && (st.Lease == nil || st.Lease.ExpiresAtNS == issued.Add(grantTTL+grantTTL/2).UnixNano()); st = p.WorkspaceState("v") { + time.Sleep(5 * time.Millisecond) + } + p.CloseWorkspaceExtenders() + if st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("issued lease not extended: %+v", st.Lease) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(st.Moves) != 1 { + t.Fatal("renewals changed authority", line) + } + assertLeaseViewMatches(t, p, "after renewals") +} + +// A forced reservation resumed after a crash issues through the replay path, +// which starts the new holder's lease the same way. +func TestWorkspaceReplayedIssueStartsGranteeLease(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + fault := &workspaceFailStore{AuthorityStore: disk} + now := time.Unix(1000, 0) + p := NewPublisher(nil, WithStore(fault), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { + t.Fatal(err) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + now = now.Add(3 * grantTTL) + req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} + head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/r", RemoteLSN: 42} + fault.failIssue = true + if _, err := p.MoveWorkspace(ctx, req, head); err == nil { + t.Fatal("injected crash ignored") + } + loaded := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(grantTTL, func() time.Time { return now })) + now = now.Add(2 * grantTTL) // past the restart deadline plus skew + r, err := loaded.MoveWorkspace(ctx, req, WorkspaceHead{}) + if err != nil || !r.Issued || r.NewEpoch != 2 { + t.Fatal("replayed issue:", r, err) + } + assertGranteeLease(t, loaded, now) + assertLeaseViewMatches(t, loaded, "after replayed issue") + if _, err := loaded.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("grantee renewal after the replayed issue:", err) + } + // Unrenewed after this, the replayed grant expires like any other. + now = now.Add(grantTTL + grantTTL/2 + loaded.workspaceSkew(nil)) + next := WorkspaceMoveRequest{RequestID: "m2", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + if r, err := loaded.MoveWorkspace(ctx, next, head); err != nil || r.NewEpoch != 3 { + t.Fatal("forced move after the replayed grant expired:", r, err) + } +} + +// The double fault: grantee 1 renews and sends its HEAD claim, then stalls; +// its lease expires and a forced move grants grantee 2 against the +// predecessor's HEAD; grantee 1's in-flight claim lands afterwards (HEAD +// moves to its epoch and the next generation); grantee 2 dies unclaimed. +// The next forced move must still be admitted on that older-epoch HEAD, with +// the lost range from its RemoteLSN; never refused for good. +func TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign(t *testing.T) { + ctx := context.Background() + disk, _ := newTempStore(t) + now := time.Unix(1000, 0) + p, issued := cleanMoveToGrantee(t, disk, &now) + now = issued.Add(100 * time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { + t.Fatal("grantee 1 renewal:", err) + } + // Grantee 1's claim is in flight; it renews no more. + now = now.Add(10 * grantTTL) + r, err := p.MoveWorkspace(ctx, forcedFromGrantee("forced-1"), predecessorHead) + if err != nil || r.NewEpoch != 3 { + t.Fatal("forced move to grantee 2:", r, err) + } + late := WorkspaceHead{Gen: predecessorHead.Gen + 1, Epoch: 2, Holder: "new-node/r", RemoteLSN: predecessorHead.RemoteLSN} + // Grantee 2 dies unclaimed. + now = now.Add(10 * grantTTL) + next := forcedFromGrantee("forced-2") + next.ExpectedHost, next.TargetHost, next.ExpectedEpoch = "third-node", "fourth-node", 3 + r, err = p.MoveWorkspace(ctx, next, late) + if err != nil || r.NewEpoch != 4 || r.HeadGen != late.Gen || r.RemoteLSN != late.RemoteLSN { + t.Fatal("forced move after grantee 1's late claim and grantee 2's death:", r, err) + } + lost := p.WorkspaceLostRanges("v") + if len(lost) != 2 || lost[1].NewEpoch != 4 || lost[1].LostAfterLSN != late.RemoteLSN { + t.Fatalf("lost ranges %+v", lost) + } + if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 4 { + t.Fatal("authority line", line) + } +} diff --git a/seaweed-block/core/calibration/scenarios.go b/seaweed-block/core/calibration/scenarios.go index 1b69b5378f..94c364e74c 100644 --- a/seaweed-block/core/calibration/scenarios.go +++ b/seaweed-block/core/calibration/scenarios.go @@ -1,6 +1,7 @@ package calibration import ( + "fmt" "strings" "time" @@ -302,6 +303,7 @@ func (*scenarioC5OrderStable) Expect() Expected { DataIntegrityExpected: true, } } + // perturbation is one of the concrete interleaving patterns C5 runs. // Each produces the SAME underlying facts on the SAME replica (r1) // but delivers events to the adapter in a different order, timing, or @@ -324,11 +326,11 @@ func (*scenarioC5OrderStable) Expect() Expected { type perturbation int const ( - pertBaseline perturbation = iota // assign + wait - pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives - pertPreAssignStorm // 8 concurrent pre-assign probes, then assign - pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent) - pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait + pertBaseline perturbation = iota // assign + wait + pertPreAssignProbe // one valid pre-assign probe, wiped when identity arrives + pertPreAssignStorm // 8 concurrent pre-assign probes, then assign + pertRepeatAssign // assign twice with identical epoch/endpointVersion (idempotent) + pertStaggeredAssign // 5 concurrent assigns with identical identity, then wait ) func (*scenarioC5OrderStable) Run() (Observed, error) { @@ -345,6 +347,7 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { sameDecision := true sameFinalMode := true sameRecoverySig := true + var divergentPath []string sameCloseCount := true dataOK := true @@ -381,6 +384,9 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { } if sig != firstSig { sameRecoverySig = false + if divergentPath == nil { + divergentPath = append([]string{fmt.Sprintf("perturbation=%d baseline=%v", p, first.CommandPath)}, obs.CommandPath...) + } } if obs.CloseEventCount != first.CloseEventCount { sameCloseCount = false @@ -401,10 +407,9 @@ func (*scenarioC5OrderStable) Run() (Observed, error) { } if !sameRecoverySig { // Pollute the command path marker so the reader cannot miss - // that the recovery signature drifted. The baseline first-run - // path is preserved alongside the marker so divergence-log - // authors can still see what the first run looked like. - out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, first.CommandPath...) + // that the recovery signature drifted. Preserve the actual divergent + // perturbation and path alongside the baseline. + out.CommandPath = append([]string{"DIVERGED_ACROSS_RUNS_RECOVERY_SIG"}, divergentPath...) } if !sameCloseCount { // Set CloseEventCount to a negative sentinel so the JSON @@ -446,13 +451,8 @@ func extractRecoverySignature(path []string) recoverySignature { // R/S/H); only the delivery shape — timing, ordering, concurrency, // assignment idempotence — varies. // -// All post-assignment probe variations are deliberately omitted: a -// probe fired with pre-captured facts after the engine has converged -// would deliver STALE R to the engine and legitimately trigger -// re-recovery. Treating that as a C5 failure would conflate engine -// correctness with A1/A4. Treating it as a C5 success would require -// gating the engine's fact-processing, which is a route change that -// belongs outside Phase 06. +// Delayed same-identity probes cannot lower completed durable R; the +// concurrent variants exercise both pending and post-completion delivery. func applyPerturbation(h *harness, p perturbation) { _, _, pH := h.primaryStore.Boundaries() rR, rS, _ := h.replicaStore.Boundaries() diff --git a/seaweed-block/core/calibration/scenarios_test.go b/seaweed-block/core/calibration/scenarios_test.go index 6ea75164a2..0ad50a4fc9 100644 --- a/seaweed-block/core/calibration/scenarios_test.go +++ b/seaweed-block/core/calibration/scenarios_test.go @@ -124,7 +124,7 @@ func TestC5_OrderStableAcrossRuns(t *testing.T) { // Recovery-signature divergence is signaled by a sentinel element // prepended to CommandPath. The scenario run must not hit this. if len(obs.CommandPath) > 0 && obs.CommandPath[0] == "DIVERGED_ACROSS_RUNS_RECOVERY_SIG" { - t.Fatalf("C5: recovery signature drifted across runs; first-run path=%v", obs.CommandPath[1:]) + t.Fatalf("C5: recovery signature drifted across runs; divergent perturbation/path=%v", obs.CommandPath[1:]) } // CloseEventCount sentinel: negative is used to flag cross-run // drift in the number of SessionClosedCompleted events. A legit diff --git a/seaweed-block/core/engine/apply.go b/seaweed-block/core/engine/apply.go index 9616689808..f0ef93008f 100644 --- a/seaweed-block/core/engine/apply.go +++ b/seaweed-block/core/engine/apply.go @@ -295,7 +295,10 @@ func applyRecoveryFacts(st *ReplicaState, e RecoveryFactsObserved, r *ApplyResul trace("stale_recovery_facts", reason) return } - st.Recovery.R = e.R + // Within one identity, delayed probes cannot undo completed durable work. + // An identity-changing assignment resets the recovery facts. + st.Recovery.R = max(st.Recovery.R, e.R) + st.Recovery.FactsMissing = !e.ProgressFact().PrimaryBoundsKnown st.Recovery.S = e.S st.Recovery.H = e.H @@ -309,6 +312,11 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra return } fact := e.ProgressFact() + if st.Recovery.FactsMissing { + st.Recovery.R = max(st.Recovery.R, fact.ReplicaR) + st.Recovery.S, st.Recovery.H = fact.PrimaryS, fact.PrimaryH + st.Recovery.FactsMissing = false + } updateDurableAckLagState(st, fact) if fact.ReplicaR > st.Recovery.DurableAckR || !st.Recovery.DurableAckKnown { st.Recovery.DurableAckR = fact.ReplicaR @@ -347,6 +355,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra TargetLSN: fact.PrimaryH, }) trace("command", "StartCatchUp (durable ack stalled)") + return // this observation already selected and emitted its recovery } if lag == LagDecisionStartRebuild && canEmitRecoveryFromDurableAck(st) { st.Recovery.R = st.Recovery.DurableAckR @@ -362,6 +371,7 @@ func applyDurableAck(st *ReplicaState, e DurableAckObserved, r *ApplyResult, tra TargetLSN: fact.PrimaryH, }) trace("command", "StartRebuild (durable ack below retention)") + return // do not emit a second recovery through post-close decide } if st.Recovery.PostCloseDurableAckKnown { decide(st, r, trace) @@ -441,6 +451,12 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { trace("decision", "unknown (not reachable)") return } + if st.Recovery.FactsMissing { + st.Recovery.Decision = DecisionUnknown + st.Recovery.DecisionReason = "no_boundaries" + trace("decision", "unknown (missing probe facts)") + return + } fact := RecoveryFactsObserved{ ReplicaID: st.Identity.ReplicaID, @@ -509,7 +525,19 @@ func decide(st *ReplicaState, r *ApplyResult, trace func(string, string)) { } else if recoveredReplicaWaitingForPostCloseAck(st) { trace("publish_healthy_held", "waiting for post-close durable ack") } else { - r.Commands = append(r.Commands, PublishHealthy{ReplicaID: st.Identity.ReplicaID}) + healthy := PublishHealthy{ReplicaID: st.Identity.ReplicaID} + target := st.Session.FrontierHint + if target == 0 { + target = st.Session.TargetLSN + } + if st.Recovery.RecoveryWindowClosed && st.Recovery.PostCloseDurableAckKnown && + st.Session.Phase == PhaseCompleted && target > 0 && st.Session.AchievedLSN >= target { + healthy.RecoverySessionID = st.Session.SessionID + healthy.Epoch = st.Identity.Epoch + healthy.EndpointVersion = st.Identity.EndpointVersion + healthy.CertifiedPrefix = target + } + r.Commands = append(r.Commands, healthy) } } diff --git a/seaweed-block/core/engine/commands.go b/seaweed-block/core/engine/commands.go index 3d137a7a38..d8bcefcccc 100644 --- a/seaweed-block/core/engine/commands.go +++ b/seaweed-block/core/engine/commands.go @@ -106,6 +106,8 @@ func (FenceAtEpoch) commandKind() string { return "FenceAtEpoch" } // PublishHealthy: declare this replica healthy for external consumption. type PublishHealthy struct { ReplicaID string + // Zero unless this publication follows a successful recovery close at T. + RecoverySessionID, Epoch, EndpointVersion, CertifiedPrefix uint64 } func (PublishHealthy) commandKind() string { return "PublishHealthy" } diff --git a/seaweed-block/core/engine/promotion_ready.go b/seaweed-block/core/engine/promotion_ready.go index 9f8f8f79e6..ef1426ee72 100644 --- a/seaweed-block/core/engine/promotion_ready.go +++ b/seaweed-block/core/engine/promotion_ready.go @@ -2,6 +2,7 @@ package engine const ( PromotionReadyReasonReady = "promotion_ready" + PromotionReadyReasonRecoveryActive = "recovery_active" PromotionReadyReasonNotMember = "not_member" PromotionReadyReasonNotReachable = "not_reachable" PromotionReadyReasonNotCaughtUp = "not_caught_up" @@ -35,6 +36,8 @@ func BuildPromotionReadyFact(st *ReplicaState) PromotionReadyFact { fact.Reason = PromotionReadyReasonNotMember case st.Reachability.Status != ProbeReachable: fact.Reason = PromotionReadyReasonNotReachable + case hasActiveSession(st): + fact.Reason = PromotionReadyReasonRecoveryActive case st.Recovery.Decision != DecisionNone: fact.Reason = PromotionReadyReasonNotCaughtUp case st.Identity.Epoch > st.Reachability.FencedEpoch: diff --git a/seaweed-block/core/engine/recovery_prefix_test.go b/seaweed-block/core/engine/recovery_prefix_test.go new file mode 100644 index 0000000000..d8eeec7077 --- /dev/null +++ b/seaweed-block/core/engine/recovery_prefix_test.go @@ -0,0 +1,42 @@ +package engine + +import "testing" + +func TestHealthyPrefixRequiresCompletedRecoveryAndPostCloseAck(t *testing.T) { + st := helperPrime(t, 1, 1, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 8, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 8}) + result := Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 8, AchievedLSN: 100}) + for _, command := range result.Commands { + if _, ok := command.(PublishHealthy); ok { + t.Fatal("recovery close certified before post-close ack") + } + } + result = Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 120, PrimaryTailLSN: 1, PrimaryHeadLSN: 120}) + for _, command := range result.Commands { + if healthy, ok := command.(PublishHealthy); ok { + if healthy.CertifiedPrefix != 100 || healthy.RecoverySessionID != 8 || healthy.Epoch != 1 || healthy.EndpointVersion != 1 { + t.Fatalf("healthy publication lost exact completed target: %+v", healthy) + } + return + } + } + t.Fatal("post-close ack did not publish certified recovery prefix") +} + +func TestHealthyProbeDoesNotCertifyRecoveryPrefix(t *testing.T) { + st := helperPrime(t, 100, 1, 100) + result := Apply(st, FenceCompleted{ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}) + found := false + for _, command := range result.Commands { + if healthy, ok := command.(PublishHealthy); ok { + found = true + if healthy.CertifiedPrefix != 0 || healthy.RecoverySessionID != 0 { + t.Fatalf("plain healthy probe invented a prefix certificate: %+v", healthy) + } + } + } + if !found { + t.Fatal("control did not reach healthy publication") + } +} diff --git a/seaweed-block/core/engine/recovery_probe_order_test.go b/seaweed-block/core/engine/recovery_probe_order_test.go new file mode 100644 index 0000000000..15908d0687 --- /dev/null +++ b/seaweed-block/core/engine/recovery_probe_order_test.go @@ -0,0 +1,43 @@ +package engine + +import "testing" + +func TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity(t *testing.T) { + st := &ReplicaState{} + assignAndProbe(st) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, TargetLSN: 100}) + Apply(st, SessionStarted{ReplicaID: "r1", SessionID: 1}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + r := Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + assertNoCommand(t, r, "StartCatchUp") + if st.Recovery.R != 100 { + t.Fatalf("old probe lowered completed R: %d", st.Recovery.R) + } + // An unknown probe must not turn the retained R into invented primary + // boundaries or publish healthy. A later valid observation recovers it. + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + if r.Projection.RecoveryDecision != DecisionUnknown { + t.Fatalf("retained R fabricated known boundaries: %+v", r.Projection) + } + r = Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + if r.Projection.RecoveryDecision != DecisionUnknown { + t.Fatal("reachability fabricated missing recovery facts") + } + assertNoCommand(t, r, "PublishHealthy") + r = Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + if r.Projection.RecoveryDecision != DecisionNone || st.Recovery.FactsMissing { + t.Fatalf("valid ack did not restore known facts: %+v", r.Projection) + } + // A higher primary head remains real new work, starting after durable R. + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 150}) + start := findStartCatchUp(t, r.Commands) + if start.FromLSN != 101 || start.EffectiveFrontierHint() != 150 { + t.Fatalf("new work lost or replayed completed prefix: %+v", start) + } + // Replacement identity must not inherit the old replica's progress floor. + Apply(st, AssignmentObserved{VolumeID: "vol1", ReplicaID: "r1", Epoch: 2, EndpointVersion: 2}) + Apply(st, ProbeSucceeded{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2}) + r = Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 2, TransportEpoch: 2, R: 0, S: 10, H: 150}) + assertHasCommand(t, r, "StartRebuild") +} diff --git a/seaweed-block/core/engine/recovery_review_regression_test.go b/seaweed-block/core/engine/recovery_review_regression_test.go new file mode 100644 index 0000000000..627be92efa --- /dev/null +++ b/seaweed-block/core/engine/recovery_review_regression_test.go @@ -0,0 +1,29 @@ +package engine + +import "testing" + +func TestPromotionReadyRefusesDelayedProbeDuringNewRecovery(t *testing.T) { + st := helperPrime(t, 50, 10, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 100, PrimaryTailLSN: 10, PrimaryHeadLSN: 100}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 100, S: 10, H: 150}) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 2, Kind: SessionCatchUp, FrontierHint: 150}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, R: 50, S: 10, H: 100}) + if fact := BuildPromotionReadyFact(st); fact.Ready { + t.Fatalf("active recovery became promotion ready after delayed probe: %+v", fact) + } +} + +func TestMissingProbeAckRestoresNewerDurableProgress(t *testing.T) { + st := helperPrime(t, 50, 10, 100) + Apply(st, SessionPrepared{ReplicaID: "r1", SessionID: 1, Kind: SessionCatchUp, FrontierHint: 100}) + Apply(st, SessionClosedCompleted{ReplicaID: "r1", SessionID: 1, AchievedLSN: 100}) + Apply(st, RecoveryFactsObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1}) + result := Apply(st, DurableAckObserved{ReplicaID: "r1", EndpointVersion: 1, TransportEpoch: 1, DurableLSN: 150, PrimaryTailLSN: 110, PrimaryHeadLSN: 150}) + if st.Recovery.R != 150 || st.Recovery.Decision != DecisionNone { + t.Fatalf("missing-probe ACK retained stale progress: R=%d decision=%s", st.Recovery.R, st.Recovery.Decision) + } + assertNoCommand(t, result, "StartRebuild") + assertNoCommand(t, result, "StartCatchUp") +} diff --git a/seaweed-block/core/engine/state.go b/seaweed-block/core/engine/state.go index bd90e8847a..c92f15734c 100644 --- a/seaweed-block/core/engine/state.go +++ b/seaweed-block/core/engine/state.go @@ -82,6 +82,9 @@ const ( // RecoveryTruth: what recovery is needed. Authority: primary. type RecoveryTruth struct { + // FactsMissing preserves an all-zero probe's unknown confidence even + // while R retains already-confirmed durable progress. + FactsMissing bool R uint64 // replica durable/achieved boundary S uint64 // primary recoverable start boundary (WAL tail) H uint64 // primary target boundary (head) diff --git a/seaweed-block/core/host/master/workspace_paused_grantee_test.go b/seaweed-block/core/host/master/workspace_paused_grantee_test.go new file mode 100644 index 0000000000..69af179701 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -0,0 +1,234 @@ +package master + +import ( + "bytes" + "context" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/host/volume" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// attachWitness records each projection read: the first refused read (not +// healthy) with the HEAD current at that instant, and whether any read was +// healthy. +type attachWitness struct { + base frontend.ProjectionView + head func() authority.WorkspaceHead + + mu sync.Mutex + refusals int + firstAt authority.WorkspaceHead + healthy bool +} + +func (w *attachWitness) Projection() frontend.Projection { + p := w.base.Projection() + var h authority.WorkspaceHead + if !p.Healthy { + h = w.head() + } + w.mu.Lock() + defer w.mu.Unlock() + if p.Healthy { + w.healthy = true + } else if w.refusals++; w.refusals == 1 { + w.firstAt = h + } + return p +} + +func (w *attachWitness) first() (authority.WorkspaceHead, int) { + w.mu.Lock() + defer w.mu.Unlock() + return w.firstAt, w.refusals +} + +func (w *attachWitness) admitted() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.healthy +} + +// A grantee renews its issued lease, then pauses before claiming HEAD. The +// forced move away from it is admitted only after the GRANT's lease expiry +// plus skew (the predecessor's older lease never satisfies it), and is +// granted on the predecessor's unchanged HEAD. The grantee resumes before +// the new owner claims: HEAD's epoch has not moved yet, so the epoch alone +// would let it claim; the authority check at attach (its lease-gated +// projection) refuses it. The new owner then claims at the higher epoch. +func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store, err := authority.NewFileAuthorityStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := store.Close(); err != nil { + t.Error(err) + } + }) + const ttl = 3 * time.Second + start := time.Now() + masterNow, hostNow := start, start + dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} + p := authority.NewPublisher(dir, authority.WithStore(store), authority.WithWorkspaceLeaseConfig(ttl, func() time.Time { return masterNow })) + seedSkewPublisher(t, p, dir) // v bound to r at epoch 1 + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + oldBarrier := time.Unix(0, p.WorkspaceState("v").Lease.ExpiresAtNS) + + remote := storage.NewMemChunkRemote() + readHead := func() authority.WorkspaceHead { + t.Helper() + h, err := remote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + } + open := func(holder string, view frontend.ProjectionView) *durable.DurableProvider { + t.Helper() + prov, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkHolder: holder, ChunkAssignmentTimeout: 2 * time.Second, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, view) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = prov.Close() }) + if _, err := prov.EnsureStorage("v"); err != nil { + t.Fatal(err) + } + if _, err := prov.RecoverVolume(ctx, "v"); err != nil { + t.Fatalf("%s recovery: %v", holder, err) + } + return prov + } + healthy := func(epoch uint64) restoreProjection { + return restoreProjection{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: epoch, EndpointVersion: 1, Healthy: true}} + } + + // The predecessor writes, cuts and detaches; the clean move grants new-node. + oldProv := open("old-node/r", healthy(1)) + b, err := oldProv.Open(ctx, "v") + if err != nil { + t.Fatal(err) + } + if n, err := b.Write(ctx, 0, bytes.Repeat([]byte{0xA5}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + if err := b.Sync(ctx); err != nil { + t.Fatal(err) + } + if _, err := oldProv.CaptureVolume(ctx, "v"); err != nil { + t.Fatal(err) + } + if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + detached, _, err := oldProv.DetachVolume(ctx, "v") + if err != nil || detached.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach: %+v %v", detached.Head, err) + } + if err := p.AckWorkspaceRevocation(ctx, "v", authority.WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: detached.Head.Gen}); err != nil { + t.Fatal(err) + } + // The lease reply's validity is measured on the real clock: keep the + // fake clocks at real time for the move and the grantee's renewal. + masterNow = time.Now() + if min := start.Add(500 * time.Millisecond); masterNow.Before(min) { + masterNow = min + } + hostNow = masterNow + clean, err := p.MoveWorkspace(ctx, authority.WorkspaceMoveRequest{RequestID: "clean", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, + TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"}, readHead()) + if err != nil || clean.NewEpoch != 2 { + t.Fatal("clean move:", clean, err) + } + predecessor := readHead() + + // The grantee renews (its guard is valid), then pauses before its claim. + guard, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 2, EndpointVersion: 1, Healthy: true}}, skewLeaseClient{p}, + &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 2}, func(context.Context) (uint64, error) { return 0, nil }, func() time.Time { return hostNow }) + if err != nil { + t.Fatal(err) + } + if err := guard.Refresh(ctx); err != nil { + t.Fatal("grantee renewal:", err) + } + if !guard.Projection().Healthy { + t.Fatal("grantee not serving after its renewal") + } + lease := p.WorkspaceState("v").Lease + if lease == nil || lease.Epoch != 2 { + t.Fatalf("grantee lease %+v", lease) + } + skew := time.Duration(lease.MaxClockSkewNS) + grantBarrier := time.Unix(0, lease.ExpiresAtNS).Add(skew) + forced := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, + TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} + + // After the predecessor's lease (plus skew) but before the grant's: refused. + masterNow = oldBarrier.Add(skew).Add(grantBarrier.Sub(oldBarrier.Add(skew)) / 2) + if !masterNow.After(oldBarrier.Add(skew)) || !masterNow.Before(grantBarrier) { + t.Fatalf("test clock: %s not between %s and %s", masterNow, oldBarrier.Add(skew), grantBarrier) + } + if _, err := p.MoveWorkspace(ctx, forced, readHead()); err == nil { + t.Fatal("forced move admitted on the predecessor's lease before the grant's lease expired") + } + masterNow = grantBarrier + r, err := p.MoveWorkspace(ctx, forced, readHead()) + if err != nil || r.NewEpoch != 3 || r.HeadGen != predecessor.Gen { + t.Fatal("forced move after the grant's lease expired:", r, err) + } + + // The grantee resumes before the new owner claims. Its attach is refused. + hostNow = masterNow + if guard.Projection().Healthy { + t.Fatal("the paused grantee still serves after the forced move") + } + // The attach decision is witnessed, not waited for: recovery runs the + // first attach attempt synchronously, and every admission read of the + // projection records the HEAD current at that instant. Close then + // settles the deferred attempts, so none can land afterwards. + witness := &attachWitness{base: guard, head: func() authority.WorkspaceHead { + h, err := remote.GetHead(context.Background()) // also read off the test goroutine: no t.Fatal + if err != nil { + return authority.WorkspaceHead{} + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached} + }} + granteeProv := open("new-node/r", witness) + refusedAt, refusals := witness.first() + if refusals == 0 || refusedAt != predecessor { + t.Fatalf("no witnessed refused attach decision while the predecessor HEAD was current (refusals %d, HEAD %+v)", refusals, refusedAt) + } + if witness.admitted() { + t.Fatal("the paused grantee's attach read a healthy projection after the forced move") + } + if h := readHead(); h != predecessor { + t.Fatalf("the paused grantee claimed HEAD after the forced move: %+v, was %+v", h, predecessor) + } + if err := granteeProv.Close(); err != nil { + t.Fatal(err) + } + if h := readHead(); h != predecessor || witness.admitted() { + t.Fatalf("HEAD changed by the paused grantee before its provider settled: %+v", h) + } + + // The new owner claims at the higher epoch. + open("third-node/r", healthy(3)) + if h := readHead(); h.Epoch != 3 || h.Holder != "third-node/r" || h.RemoteLSN != predecessor.RemoteLSN { + t.Fatalf("HEAD after the new owner's claim: %+v", h) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index fabe00514c..4f51bf89d7 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -136,6 +136,16 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) if err := s.workspaceVolume(q.GetVolumeId()); err != nil { return nil, err } + // A forced move reads HEAD only after its lease admission holds: the + // expected holder's lease has then expired, so it starts no new claim or + // cut before this read. A claim it already sent may still land after it + // (WorkspaceForcedMoveAdmitted). The publisher re-checks admission when + // it issues the move. + if q.GetKind() == "forced" { + if err := s.host.Publisher().WorkspaceForcedMoveAdmitted(ctx, q.GetVolumeId(), q.GetRequestId(), q.GetExpectedReplicaId(), q.GetExpectedEpoch()); err != nil { + return nil, workspaceError(err) + } + } // Always bound the configured reader, even when the caller omitted a deadline. readCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() diff --git a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go new file mode 100644 index 0000000000..3a6b4defa4 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go @@ -0,0 +1,190 @@ +package master + +import ( + "context" + "errors" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// seedDetachedHead installs the predecessor's detached final cut. +func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChunkRemote, holder string, epoch, lsn uint64) storage.ChunkHead { + t.Helper() + h := storage.ChunkHead{Epoch: epoch, Holder: holder, RemoteLSN: lsn, State: storage.ChunkHeadDetached, DetachedBy: &storage.ChunkDetachedBy{Holder: holder, Epoch: epoch, Gen: 1}} + gen, err := remote.CASHead(ctx, storage.ChunkHeadVersion{}, h) + if err != nil { + t.Fatal(err) + } + h.Gen = gen + return h +} + +// A clean move grants vol-a to node-b, whose host dies before its first +// renewal and so before it claims HEAD: HEAD still names node-a. A forced +// move to node-c is refused before the lease the issue started has expired +// plus the skew bound, without reading HEAD; after it, it reads HEAD (only +// then) and is granted on the predecessor's unchanged HEAD. A late claim by +// the dead grantee never displaces the new owner's higher epoch. +func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { + // The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s. + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + var reads atomic.Int64 + var lastReadNS atomic.Int64 + reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) { + reads.Add(1) + lastReadNS.Store(time.Now().UnixNano()) + h, err := remote.GetHead(ctx) + if err != nil { + return authority.WorkspaceHead{}, err + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil + } + const skew = 100 * time.Millisecond + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + + for _, server := range []string{"node-a", "node-b", "node-c"} { + if _, err = m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err = lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + dst := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + third := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-c", DataAddr: "127.0.0.1:39200", CtrlAddr: "127.0.0.1:39100"} + for _, b := range []*control.WorkspaceBinding{src, dst, third} { + if _, err = ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err = ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-a", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-a", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch} + if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil { + t.Fatal(err) + } + + // node-a detaches its final cut and ACKs; the clean move grants node-b. + seed := seedDetachedHead(t, ctx, remote, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) + if _, err = ws.RevokeWorkspace(ctx, oldID); err != nil { + t.Fatal(err) + } + if _, err = ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: oldID, HeadGen: seed.Gen}); err != nil { + t.Fatal(err) + } + clean, err := ws.MoveWorkspace(ctx, &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"}) + if err != nil { + t.Fatal("clean move:", err) + } + grantee := clean.GetNewEpoch() + st := m.Publisher().WorkspaceState("vol-a") + if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking { + t.Fatalf("the issued move must start node-b's lease: %+v", st) + } + barrier := time.Unix(0, st.Lease.ExpiresAtNS).Add(skew) + if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee { + t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err) + } + + // node-b dies before renewing or claiming. Before expiry plus skew the + // forced move is refused, and HEAD is not read for it. + forced := &control.WorkspaceMove{RequestId: "forced-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: grantee, TargetReplicaId: "r1", + TargetServerId: "node-c", TargetDataAddr: third.DataAddr, TargetCtrlAddr: third.CtrlAddr, Kind: "forced", Force: true} + before := reads.Load() + if _, err := ws.MoveWorkspace(ctx, forced); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { + t.Fatalf("forced move before the issued lease expired: %v", err) + } + if n := reads.Load() - before; n != 0 { + t.Fatalf("HEAD read %d times for a forced move whose admission had not passed", n) + } + + select { + case <-time.After(time.Until(barrier) + 50*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + grant, err := ws.MoveWorkspace(ctx, forced) + if err != nil { + t.Fatal("forced move after the issued lease expired:", err) + } + if reads.Load() == before || time.Unix(0, lastReadNS.Load()).Before(barrier) { + t.Fatalf("the forced move's HEAD was not read after admission (reads %d, last read %s, barrier %s)", reads.Load()-before, time.Unix(0, lastReadNS.Load()), barrier) + } + line, _ := m.Publisher().VolumeAuthorityLine("vol-a") + if !grant.Issued || grant.NewEpoch != grantee+1 || line.Epoch != grant.NewEpoch || grant.HeadGen != seed.Gen || grant.RemoteLsn != seed.RemoteLSN { + t.Fatalf("forced grant %+v line %+v; want epoch %d on HEAD gen %d lsn %d", grant, line, grantee+1, seed.Gen, seed.RemoteLSN) + } + if _, err := ws.RenewWorkspaceLease(ctx, &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: "r1", Epoch: grantee}); err == nil { + t.Fatal("the dead grantee's epoch renewed after the forced move") + } + + // A late grantee claim. (b) Its CAS lands after the forced move's HEAD + // read but before the new owner claims: the new owner still takes HEAD + // at the higher epoch, and the grantee is fenced afterwards. + granteeCfg := storage.ChunkLayerConfig{Epoch: grantee, Holder: "node-b/r1"} + ownerCfg := storage.ChunkLayerConfig{Epoch: grant.NewEpoch, Holder: "node-c/r1"} + late, err := storage.ClaimChunkHead(ctx, remote, granteeCfg) + if err != nil { + t.Fatal("late grantee claim landing first:", err) + } + owned, err := storage.ClaimChunkHead(ctx, remote, ownerCfg) + if err != nil || owned.Epoch != grant.NewEpoch || owned.Holder != "node-c/r1" || owned.RemoteLSN != seed.RemoteLSN { + t.Fatalf("new owner's claim over the late grantee: %+v %v", owned, err) + } + if _, err := storage.ClaimChunkHead(ctx, remote, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("grantee re-claim after the new owner: %v; want fenced", err) + } + stale := late + stale.State = storage.ChunkHeadActive + if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: late.Gen, Epoch: late.Epoch}, stale); !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("grantee HEAD write after the new owner: %v; want a CAS precondition failure", err) + } + // (a) The new owner claims first; the late grantee claim is fenced. + fresh := storage.NewMemChunkRemote() + seedDetachedHead(t, ctx, fresh, "node-a/"+oldLine.ReplicaID, oldLine.Epoch, 42) + if _, err := storage.ClaimChunkHead(ctx, fresh, ownerCfg); err != nil { + t.Fatal(err) + } + if _, err := storage.ClaimChunkHead(ctx, fresh, granteeCfg); !errors.Is(err, storage.ErrChunkLayerFenced) { + t.Fatalf("late grantee claim after the new owner: %v; want fenced", err) + } + for _, r := range []*storage.MemChunkRemote{remote, fresh} { + if h, err := r.GetHead(ctx); err != nil || h.Epoch != grant.NewEpoch || h.Holder != "node-c/r1" { + t.Fatalf("HEAD after the late claim: %+v %v; want the new owner", h, err) + } + } +} diff --git a/seaweed-block/core/replication/apply_gate.go b/seaweed-block/core/replication/apply_gate.go index 368df4e62c..aa0fa64cd1 100644 --- a/seaweed-block/core/replication/apply_gate.go +++ b/seaweed-block/core/replication/apply_gate.go @@ -52,8 +52,8 @@ import ( // Per-LBA applied LSN source (Option C hybrid, kickoff §2.5 #1): // at session init, query `store.AppliedLSNs()` for substrate- // reported per-LBA latest-applied-LSN seed; substrates returning -// `ErrAppliedLSNsNotTracked` (BlockStore) fall back to session-only -// tracking, seeded from live + recovery applies during the session. +// `ErrAppliedLSNsNotTracked` (BlockStore) fall back to replica-lifetime +// tracking, seeded from live + recovery applies across sessions. // // Pinned invariants (T4d mini-plan §4 #6): // - INV-REPL-NO-PER-LBA-DATA-REGRESSION (goal-level) @@ -65,20 +65,18 @@ import ( type ReplicaApplyGate struct { store storage.LogicalStorage - mu sync.Mutex - sessions map[uint64]*applyGateSession // keyed by lineage.SessionID + mu sync.Mutex + sessions map[uint64]*applyGateSession // keyed by lineage.SessionID + appliedLSN map[uint32]uint64 // replica-wide, shared by every lane and session + floorLSN uint64 // certified contiguous prefix; never inferred from synced maximum R } // applyGateSession is the per-recovery-session state. Per round-44 // 2-map split: liveTouched + recoveryCovered are distinct because // the same physical LBA can appear in both (live lane wrote it AND -// recovery lane saw it during the session). appliedLSN is the -// stale-skip discriminator. +// recovery lane saw it during the session). The stale-skip discriminator +// is replica-wide and survives CloseSession. type applyGateSession struct { - // appliedLSN: highest LSN successfully applied to each LBA - // (across both lanes). The stale-skip discriminator. - appliedLSN map[uint32]uint64 - // liveTouched: LBAs the live lane wrote during this session. // Recovery must yield to these (live-wins via per-LBA LSN check). liveTouched map[uint32]bool @@ -93,13 +91,14 @@ type applyGateSession struct { // // Called by: replica-side wiring code that constructs the // `transport.ReplicaListener` with an `ApplyHook` option. -// Owns: per-session state maps; substrate query at session init. +// Owns: per-session coverage, replica-wide applied LSNs; substrate seed queries. // Borrows: store handle (caller retains; gate calls ApplyEntry + // AppliedLSNs through the interface). func NewReplicaApplyGate(store storage.LogicalStorage) *ReplicaApplyGate { return &ReplicaApplyGate{ - store: store, - sessions: make(map[uint64]*applyGateSession), + store: store, + sessions: make(map[uint64]*applyGateSession), + appliedLSN: make(map[uint32]uint64), } } @@ -167,7 +166,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat g.mu.Lock() defer g.mu.Unlock() - if existing, ok := sess.appliedLSN[lba]; ok && lsn <= existing { + if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing { // Stale: skip data write but ADVANCE recoveryCovered. sess.recoveryCovered[lba] = true return nil @@ -176,7 +175,7 @@ func (g *ReplicaApplyGate) applyRecovery(sess *applyGateSession, lba uint32, dat if err := g.store.ApplyEntry(lba, data, lsn); err != nil { return fmt.Errorf("apply gate: recovery substrate.ApplyEntry lba=%d lsn=%d: %w", lba, lsn, err) } - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = lsn sess.recoveryCovered[lba] = true return nil } @@ -192,7 +191,7 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] g.mu.Lock() defer g.mu.Unlock() - if existing, ok := sess.appliedLSN[lba]; ok && lsn <= existing { + if existing := max(g.appliedLSN[lba], g.floorLSN); lsn <= existing { // Stale: fail-loud. Caller logs + drops conn. return fmt.Errorf("apply gate: live-lane stale entry lba=%d lsn=%d <= applied=%d (INV-REPL-LIVE-LANE-STALE-FAILS-LOUD)", lba, lsn, existing) @@ -202,17 +201,17 @@ func (g *ReplicaApplyGate) applyLive(sess *applyGateSession, lba uint32, data [] if err := g.store.ApplyEntry(lba, data, lsn); err != nil { return fmt.Errorf("apply gate: live substrate.ApplyEntry lba=%d lsn=%d: %w", lba, lsn, err) } - sess.appliedLSN[lba] = lsn + g.appliedLSN[lba] = lsn sess.liveTouched[lba] = true return nil } // initSessionLocked builds a fresh session state. Called with g.mu -// held. Seeds appliedLSN from substrate AppliedLSNs() (Option C -// hybrid); falls back to empty map on `ErrAppliedLSNsNotTracked`. +// held. Merge substrate seeds into the replica-wide map without lowering +// LSNs already applied by another lane or session. Untracked substrates +// retain the gate's replica-lifetime history. func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession { sess := &applyGateSession{ - appliedLSN: make(map[uint32]uint64), liveTouched: make(map[uint32]bool), recoveryCovered: make(map[uint32]bool), } @@ -220,21 +219,23 @@ func (g *ReplicaApplyGate) initSessionLocked(sessionID uint64) *applyGateSession if err != nil { // ErrAppliedLSNsNotTracked is the documented sentinel (Option // C hybrid). Anything else is an unexpected substrate error; - // log and proceed with empty map (gate's session-only - // tracking will fill in via subsequent applies). - log.Printf("apply gate: session %d substrate AppliedLSNs unavailable (%v); falling back to session-only tracking", sessionID, err) + // log and retain the replica-lifetime map; subsequent applies + // extend it only after the physical write succeeds. + log.Printf("apply gate: session %d substrate AppliedLSNs unavailable (%v); retaining replica-lifetime tracking", sessionID, err) return sess } for lba, lsn := range seed { - sess.appliedLSN[lba] = lsn + if lsn > g.floorLSN { + g.appliedLSN[lba] = max(g.appliedLSN[lba], lsn) + } } return sess } // CloseSession clears per-session state. Called by replica-side // wiring on session teardown (lineage advance to a new session, -// peer disconnect, etc.). Optional — leaving stale sessions in the -// map costs memory but doesn't affect correctness for fresh sessions. +// peer disconnect, etc.). Only coverage is released: the replica-wide +// applied-LSN map must survive session teardown. // // Called by: replica-side session-lifecycle hook (post-T4d-2: the // existing acceptMutationLineage advance path is the natural close @@ -246,7 +247,7 @@ func (g *ReplicaApplyGate) CloseSession(sessionID uint64) { g.mu.Unlock() } -// SessionState exposes per-session state for assertion-only +// SessionState exposes replica-wide version count and per-session coverage for assertion-only // inspection in tests + diagnostics. Returns a snapshot; caller- // owned (mutation does not affect gate state). // @@ -258,7 +259,7 @@ func (g *ReplicaApplyGate) SessionState(sessionID uint64) (appliedLSN, liveTouch if !ok { return 0, 0, 0, false } - return len(sess.appliedLSN), len(sess.liveTouched), len(sess.recoveryCovered), true + return len(g.appliedLSN), len(sess.liveTouched), len(sess.recoveryCovered), true } // SessionRecoveryCoverage returns true iff the given LBA was @@ -276,17 +277,52 @@ func (g *ReplicaApplyGate) SessionRecoveryCoverage(sessionID uint64, lba uint32) return sess.recoveryCovered[lba] } -// SessionAppliedLSN returns the gate's tracked applied LSN for an -// LBA in this session. Returns 0 + false if not tracked. +// SessionAppliedLSN returns the replica-wide applied LSN visible to a +// registered session. Returns 0 + false if either is not tracked. // // Called by: tests pinning per-LBA stale-skip discrimination. func (g *ReplicaApplyGate) SessionAppliedLSN(sessionID uint64, lba uint32) (uint64, bool) { g.mu.Lock() defer g.mu.Unlock() - sess, ok := g.sessions[sessionID] + _, ok := g.sessions[sessionID] if !ok { return 0, false } - lsn, present := sess.appliedLSN[lba] + lsn, present := g.appliedLSN[lba] return lsn, present } + +// CertifyRecoveryPrefix accepts an explicit source-coverage certificate emitted +// only after a successful recovery close is published healthy. Sync/Boundaries +// alone cannot certify coverage: a high live LSN can be durable across a hole. +// The transport owns lineage admission. A missing/refused certificate retains +// history conservatively; ordinary live traffic does not advance this floor. +func (g *ReplicaApplyGate) CertifyRecoveryPrefix(lineage transport.RecoveryLineage) error { + prefix := lineage.EffectiveFrontierHint() + g.mu.Lock() + defer g.mu.Unlock() + r, _, _ := g.store.Boundaries() + if prefix == 0 || prefix > r { + return fmt.Errorf("apply gate: certified prefix %d exceeds durable boundary %d or is zero", prefix, r) + } + if prefix <= g.floorLSN { + return nil + } + // Rebuild rather than only deleting: release the old map's bucket capacity. + retained := make(map[uint32]uint64) + for lba, lsn := range g.appliedLSN { + if lsn > prefix { + retained[lba] = lsn + } + } + g.appliedLSN = retained + g.floorLSN = prefix + return nil +} + +// CertifiedPrefix reports the source-certified coverage frontier, not R. +func (g *ReplicaApplyGate) CertifiedPrefix() uint64 { + g.mu.Lock() + defer g.mu.Unlock() + return g.floorLSN +} diff --git a/seaweed-block/core/replication/apply_gate_cross_session_test.go b/seaweed-block/core/replication/apply_gate_cross_session_test.go new file mode 100644 index 0000000000..fdecae23d5 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_cross_session_test.go @@ -0,0 +1,106 @@ +package replication + +import ( + "bytes" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Both sessions are initialized before either writes the contested LBA. +// This fixes the ordering without relying on a probabilistic goroutine race. +func TestApplyGate_OverlappingSessionsNeverRegressBytes(t *testing.T) { + for _, live := range []bool{false, true} { + name := "recovery_then_older_recovery" + if live { + name = "live_then_older_recovery" + } + t.Run(name, func(t *testing.T) { + gate, store := newGate(t) + older, newer := recoveryLineage(10, 120), recoveryLineage(11, 120) + if err := gate.ApplyRecovery(older, 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if err := gate.ApplyRecovery(newer, 1, makeData(2), 2); err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0xBB}, blockSize) + apply := gate.ApplyRecovery + if live { + apply = gate.ApplyLive + } + if err := apply(newer, 5, want, 120); err != nil { + t.Fatal(err) + } + if err := gate.ApplyRecovery(older, 5, bytes.Repeat([]byte{0xAA}, blockSize), 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(5) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("cross-session stale recovery regressed bytes: got %x want %x", got[:8], want[:8]) + } + if !gate.SessionRecoveryCoverage(older.SessionID, 5) { + t.Fatal("stale recovery did not advance its own coverage") + } + }) + } +} + +func TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion(t *testing.T) { + store := &fakeStoreWithSeed{BlockStore: storage.NewBlockStore(64, blockSize), seed: map[uint32]uint64{5: 1}} + gate := NewReplicaApplyGate(store) + want := bytes.Repeat([]byte{0xBB}, blockSize) + if err := gate.ApplyLive(liveLineage(1), 5, want, 120); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if _, _, _, found := gate.SessionState(1); found { + t.Fatal("closed session coverage retained") + } + if err := gate.ApplyRecovery(recoveryLineage(2, 120), 5, makeData(0xAA), 95); err != nil { + t.Fatal(err) + } + if err := gate.ApplyLive(liveLineage(3), 5, makeData(0xCC), 100); err == nil { + t.Fatal("cross-session stale live write was accepted") + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("teardown/reseed regressed replica bytes: err=%v", err) + } + if !gate.SessionRecoveryCoverage(2, 5) || gate.SessionRecoveryCoverage(3, 5) { + t.Fatal("stale skip/fail mixed lane coverage") + } +} + +type failOnceApplyStore struct { + *storage.BlockStore + fail bool +} + +func (s *failOnceApplyStore) ApplyEntry(lba uint32, data []byte, lsn uint64) error { + if s.fail { + s.fail = false + return errSubstrateBoom + } + return s.BlockStore.ApplyEntry(lba, data, lsn) +} + +func TestApplyGate_FailedWriteDoesNotPublishReplicaVersion(t *testing.T) { + store := &failOnceApplyStore{BlockStore: storage.NewBlockStore(64, blockSize), fail: true} + gate := NewReplicaApplyGate(store) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); !errors.Is(err, errSubstrateBoom) { + t.Fatalf("physical error lost: %v", err) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(2, 120), 5, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("failed write falsely blocked recovery: err=%v", err) + } +} diff --git a/seaweed-block/core/replication/apply_gate_floor_test.go b/seaweed-block/core/replication/apply_gate_floor_test.go new file mode 100644 index 0000000000..68f1323176 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_floor_test.go @@ -0,0 +1,141 @@ +package replication + +import ( + "bytes" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// A synced scalar maximum does not establish recovery coverage for other LBAs. +func TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if r, err := store.Sync(); err != nil || r != 120 { + t.Fatalf("sync: R=%d err=%v", r, err) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(2, 100), 6, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("synced maximum swallowed an uncovered recovery LBA: err=%v got=%x", err, got[:8]) + } +} + +// Each batch has a successful recovery close and an explicit prefix certificate. +// Durability alone is insufficient; ordinary healthy traffic remains unbounded. +func TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory(t *testing.T) { + const batch = 32 + store := storage.NewBlockStore(1025, 1) + gate := NewReplicaApplyGate(store) + var lsn uint64 + for round := uint64(0); round < 32; round++ { + session := round + 1 + for j := uint64(0); j < batch; j++ { + lba := uint32(round*batch + j) + lsn++ + if err := gate.ApplyLive(liveLineage(session), lba, []byte{0xBB}, lsn); err != nil { + t.Fatal(err) + } + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(session, lsn)); err != nil { + t.Fatal(err) + } + // A subsequent apply provides a lazy-pruning opportunity. + lsn++ + if err := gate.ApplyLive(liveLineage(session), 1024, []byte{0xCC}, lsn); err != nil { + t.Fatal(err) + } + tracked, _, _, _ := gate.SessionState(session) + if tracked > batch+1 { + t.Fatalf("durable version history grew with historical LBAs: round=%d tracked=%d bound=%d", round, tracked, batch+1) + } + gate.CloseSession(session) + } +} + +func TestApplyGate_PrunedDurableVersionsRemainStale(t *testing.T) { + gate, store := newGate(t) + want := makeData(0xBB) + for lba := uint32(0); lba < 32; lba++ { + if err := gate.ApplyLive(liveLineage(1), lba, want, uint64(lba)+1); err != nil { + t.Fatal(err) + } + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 32)); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if err := gate.ApplyRecovery(recoveryLineage(2, 32), 5, makeData(0xAA), 1); err != nil { + t.Fatal(err) + } + if !gate.SessionRecoveryCoverage(2, 5) { + t.Fatal("pruned stale recovery did not cover its own session") + } + if err := gate.ApplyLive(liveLineage(3), 6, makeData(0xCC), 2); err == nil { + t.Fatal("pruned stale live write was accepted") + } + if gate.SessionRecoveryCoverage(3, 6) { + t.Fatal("stale live write advanced recovery coverage") + } + for _, lba := range []uint32{5, 6} { + got, err := store.Read(lba) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("pruned stale record changed LBA %d: err=%v", lba, err) + } + } + tracked, _, _, _ := gate.SessionState(2) + if tracked != 0 { + t.Fatalf("durable versions were not pruned: tracked=%d want=0", tracked) + } +} + +func TestApplyGate_CertifiedPrefixFreezesAcrossSessions(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil { + t.Fatal(err) + } + gate.CloseSession(1) + if err := gate.ApplyLive(liveLineage(2), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + if got := gate.CertifiedPrefix(); got != 1 { + t.Fatalf("new session or Sync extended certified floor: P=%d", got) + } + want := makeData(0xAA) + if err := gate.ApplyRecovery(recoveryLineage(3, 100), 6, want, 95); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("frozen prefix swallowed missing recovery: err=%v", err) + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 121)); err == nil { + t.Fatal("certificate above durable boundary accepted") + } + if err := gate.CertifyRecoveryPrefix(recoveryLineage(3, 1)); err != nil { + t.Fatal(err) + } + if gate.CertifiedPrefix() != 1 { + t.Fatal("failed/repeated certificate changed prefix") + } +} diff --git a/seaweed-block/core/replication/apply_gate_prefix_wire_test.go b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go new file mode 100644 index 0000000000..83065c3ce1 --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_prefix_wire_test.go @@ -0,0 +1,214 @@ +package replication + +import ( + "bytes" + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type prefixResult struct { + lineage transport.RecoveryLineage + err error +} + +type observedPrefixGate struct { + *ReplicaApplyGate + certified chan prefixResult +} + +func (g *observedPrefixGate) CertifyRecoveryPrefix(l transport.RecoveryLineage) error { + err := g.ReplicaApplyGate.CertifyRecoveryPrefix(l) + g.certified <- prefixResult{l, err} + return err +} + +// Real primary engine/adapter/executor -> role-gated replica -> shared gate. +func TestApplyGate_HealthyRecoveryPublishesWirePrefix(t *testing.T) { + t.Run("catchup_from_certified_base", func(t *testing.T) { runHealthyRecoveryPrefix(t, true) }) + t.Run("full_base", func(t *testing.T) { runHealthyRecoveryPrefix(t, false) }) +} +func runHealthyRecoveryPrefix(t *testing.T, seeded bool) { + primary := storage.NewBlockStore(64, blockSize) + for lba := uint32(0); lba < 32; lba++ { + if _, err := primary.Write(lba, makeData(byte(lba+1))); err != nil { + t.Fatal(err) + } + } + if _, err := primary.Sync(); err != nil { + t.Fatal(err) + } + store := storage.NewBlockStore(64, blockSize) + gate := &observedPrefixGate{ReplicaApplyGate: NewReplicaApplyGate(store), certified: make(chan prefixResult, 8)} + if seeded { + if err := gate.ApplyLive(liveLineage(1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + // This initial BASE is known complete; Sync alone must not establish it. + if err := gate.ReplicaApplyGate.CertifyRecoveryPrefix(recoveryLineage(1, 1)); err != nil { + t.Fatal(err) + } + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + executor := transport.NewBlockExecutor(primary, listener.Addr()) + t.Cleanup(func() { executor.Stop(); listener.StopHard() }) + a := adapter.NewVolumeReplicaAdapter(executor) + a.OnAssignment(adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1, DataAddr: listener.Addr()}) + var certified transport.RecoveryLineage + select { + case result := <-gate.certified: + if result.err != nil { + t.Fatal(result.err) + } + certified = result.lineage + case <-time.After(5 * time.Second): + t.Fatal("healthy recovery did not publish wire prefix certificate") + } + if got := gate.CertifiedPrefix(); got != 32 { + t.Fatalf("wire certified prefix=%d want32", got) + } + tracked, _, _, found := gate.SessionState(certified.SessionID) + if (seeded && !found) || tracked != 0 { + t.Fatalf("wire recovery did not prune: found=%v tracked=%d", found, tracked) + } +} + +func TestApplyGate_WirePrefixCannotIntroduceOrReviveSession(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyRecovery(recoveryLineage(1, 1), 0, makeData(1), 1); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + send := func(l transport.RecoveryLineage, certificate bool) { + t.Helper() + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + defer c.Close() + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + if certificate { + if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(l)); err != nil { + t.Fatal(err) + } + } + if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)); err != nil { + if certificate { + return + } + t.Fatal(err) + } + kind, _, err := transport.ReadMsg(c) + if !certificate && (err != nil || kind != transport.MsgBarrierResp) { + t.Fatalf("setup barrier: kind=%d err=%v", kind, err) + } + } + send(recoveryLineage(1, 1), true) // unseen: rejected, must not introduce lineage + if gate.CertifiedPrefix() != 0 { + t.Fatal("unseen session certified prefix") + } + send(recoveryLineage(2, 1), false) + send(recoveryLineage(1, 1), true) // superseded: cannot certify even with valid R + if gate.CertifiedPrefix() != 0 { + t.Fatal("stale session certified prefix") + } +} + +// A clean recovery close cannot certify a pre-existing hole in its starting R. +func TestApplyGate_WirePrefixRequiresCoveredStartingImage(t *testing.T) { + gate, store := newGate(t) + if err := gate.ApplyLive(liveLineage(1), 5, makeData(0xBB), 120); err != nil { + t.Fatal(err) + } + if _, err := store.Sync(); err != nil { + t.Fatal(err) + } + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + lineage := recoveryLineage(2, 120) + dial := func() net.Conn { + t.Helper() + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + t.Fatal(err) + } + return c + } + barrier := func(c net.Conn) error { + if err := transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(lineage)); err != nil { + return err + } + _, _, err := transport.ReadMsg(c) + return err + } + c := dial() + if err := transport.WriteMsg(c, transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + if err := barrier(c); err != nil { + t.Fatal(err) + } + if err := transport.WriteMsg(c, transport.MsgCertifiedPrefix, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + _ = barrier(c) // certificate refusal closes this connection + if got := gate.CertifiedPrefix(); got != 0 { + t.Fatalf("uncertified starting R advanced P=%d", got) + } + c = dial() + if err := transport.WriteMsg(c, transport.MsgRecoveryLaneStart, transport.EncodeLineage(lineage)); err != nil { + t.Fatal(err) + } + want := makeData(0xAA) + if err := transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: lineage, LBA: 6, LSN: 95, Data: want})); err != nil { + t.Fatal(err) + } + if err := barrier(c); err != nil { + t.Fatal(err) + } + got, err := store.Read(6) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("uncertified starting image swallowed recovery hole: err=%v", err) + } +} diff --git a/seaweed-block/core/replication/apply_gate_retirement_test.go b/seaweed-block/core/replication/apply_gate_retirement_test.go new file mode 100644 index 0000000000..64e506e94b --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_retirement_test.go @@ -0,0 +1,54 @@ +package replication + +import ( + "net" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/transport" +) + +func TestApplyGate_WireSessionTurnoverRetiresSettledCoverage(t *testing.T) { + gate, store := newGate(t) + listener, err := transport.NewReplicaListenerWithFloorAndApplyHook("127.0.0.1:0", store, "v1", "", gate) + if err != nil { + t.Fatal(err) + } + if err := listener.AdmitAsReplica(1); err != nil { + listener.StopHard() + t.Fatal(err) + } + listener.Serve() + t.Cleanup(listener.StopHard) + for session := uint64(1); session <= 128; session++ { + c, err := net.DialTimeout("tcp", listener.Addr(), time.Second) + if err != nil { + t.Fatal(err) + } + if err := c.SetDeadline(time.Now().Add(2 * time.Second)); err != nil { + c.Close() + t.Fatal(err) + } + l := liveLineage(session) + err = transport.WriteMsg(c, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: l, LBA: 5, LSN: session, Data: makeData(byte(session))})) + if err == nil { + err = transport.WriteMsg(c, transport.MsgBarrierReq, transport.EncodeLineage(l)) + } + if err == nil { + _, _, err = transport.ReadMsg(c) + } + c.Close() + if err != nil { + t.Fatal(err) + } + if session > 1 { + if _, _, _, found := gate.SessionState(session - 1); found { + t.Fatalf("settled session coverage survived turnover: session=%d", session-1) + } + } + } + // Retirement must leave the shared suffix version intact. + if err := gate.ApplyLive(liveLineage(129), 5, makeData(0), 127); err == nil { + t.Fatal("coverage retirement erased shared version") + } +} diff --git a/seaweed-block/core/replication/apply_gate_test.go b/seaweed-block/core/replication/apply_gate_test.go index 7179d26bd9..b629eb0b68 100644 --- a/seaweed-block/core/replication/apply_gate_test.go +++ b/seaweed-block/core/replication/apply_gate_test.go @@ -230,18 +230,21 @@ func TestApplyGate_LiveLane_StaleEntry_DoesNotAdvanceRecoveryCovered(t *testing. // --- Lane independence: two sessions, different lanes --- -func TestApplyGate_LiveAndRecovery_DistinctSessions_Independent(t *testing.T) { +func TestApplyGate_LiveAndRecovery_DistinctCoverageSharedVersion(t *testing.T) { gate, _ := newGate(t) live := liveLineage(50) recov := recoveryLineage(7, 100) gate.ApplyLive(live, 5, makeData(0xBB), 100) - gate.ApplyRecovery(recov, 5, makeData(0xAA), 30) // recovery sees its own session + gate.ApplyRecovery(recov, 5, makeData(0xAA), 30) // stale across sessions - // Recovery session sees its own appliedLSN (just set: 30). + // Both sessions see the replica-wide version, with separate coverage. lsn, ok := gate.SessionAppliedLSN(7, 5) - if !ok || lsn != 30 { - t.Errorf("recovery session appliedLSN[5] = (%d, %v), want (30, true)", lsn, ok) + if !ok || lsn != 100 { + t.Errorf("recovery appliedLSN[5] = (%d, %v), want (100, true)", lsn, ok) + } + if !gate.SessionRecoveryCoverage(7, 5) || gate.SessionRecoveryCoverage(50, 5) { + t.Fatal("cross-session version sharing mixed recovery coverage") } // Live session sees its own appliedLSN (set: 100). diff --git a/seaweed-block/core/replication/apply_gate_wire_overlap_test.go b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go new file mode 100644 index 0000000000..f3f41a5e1c --- /dev/null +++ b/seaweed-block/core/replication/apply_gate_wire_overlap_test.go @@ -0,0 +1,117 @@ +package replication + +import ( + "bytes" + "net" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" + "github.com/seaweedfs/seaweed-block/core/transport" +) + +type heldAdmittedRecovery struct { + *ReplicaApplyGate + entered, release chan struct{} + done chan error + closed chan uint64 +} + +func (h *heldAdmittedRecovery) CloseSession(id uint64) { + h.ReplicaApplyGate.CloseSession(id) + if h.closed != nil { + h.closed <- id + } +} + +func (h *heldAdmittedRecovery) ApplyRecovery(l transport.RecoveryLineage, lba uint32, data []byte, lsn uint64) error { + if l.SessionID == 1 && lsn == 95 { + close(h.entered) + <-h.release + err := h.ReplicaApplyGate.ApplyRecovery(l, lba, data, lsn) + h.done <- err + return err + } + return h.ReplicaApplyGate.ApplyRecovery(l, lba, data, lsn) +} + +// An old frame can pass the listener's lineage check before a newer session +// advances that check, then reach the apply gate after the newer write. +func TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes(t *testing.T) { + store := storage.NewBlockStore(64, blockSize) + h := &heldAdmittedRecovery{ReplicaApplyGate: NewReplicaApplyGate(store), entered: make(chan struct{}), release: make(chan struct{}), done: make(chan error, 1), closed: make(chan uint64, 8)} + listener, err := transport.NewReplicaListenerWithApplyHook("127.0.0.1:0", store, h) + if err != nil { + t.Fatal(err) + } + listener.Serve() + var once sync.Once + release := func() { once.Do(func() { close(h.release) }) } + t.Cleanup(func() { release(); listener.Stop() }) + dial := func() net.Conn { + c, err := net.DialTimeout("tcp", listener.Addr(), 2*time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + if err := c.SetDeadline(time.Now().Add(3 * time.Second)); err != nil { + t.Fatal(err) + } + return c + } + send := func(c net.Conn, kind byte, payload []byte) { + if err := transport.WriteMsg(c, kind, payload); err != nil { + t.Fatal(err) + } + } + barrier := func(c net.Conn, l transport.RecoveryLineage) { + send(c, transport.MsgBarrierReq, transport.EncodeLineage(l)) + kind, _, err := transport.ReadMsg(c) + if err != nil || kind != transport.MsgBarrierResp { + t.Fatalf("barrier: kind=%d err=%v", kind, err) + } + } + old, newer := recoveryLineage(1, 120), recoveryLineage(2, 120) + c1, c2 := dial(), dial() + send(c1, transport.MsgRecoveryLaneStart, transport.EncodeLineage(old)) + send(c1, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: old, LBA: 0, Data: makeData(1), LSN: 1})) + barrier(c1, old) // initialize the old session before the competing apply + send(c1, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: old, LBA: 5, Data: makeData(0xAA), LSN: 95})) + select { + case <-h.entered: + case <-time.After(3 * time.Second): + t.Fatal("old frame never reached post-admission hook") + } + send(c2, transport.MsgRecoveryLaneStart, transport.EncodeLineage(newer)) + want := bytes.Repeat([]byte{0xBB}, blockSize) + send(c2, transport.MsgShipEntry, transport.EncodeShipEntry(transport.ShipEntry{Lineage: newer, LBA: 5, Data: want, LSN: 120})) + barrier(c2, newer) + if _, _, _, found := h.SessionState(old.SessionID); !found { + t.Fatal("admitted old frame lost coverage before settlement") + } + release() + select { + case err := <-h.done: + if err != nil { + t.Fatal(err) + } + case <-time.After(3 * time.Second): + t.Fatal("admitted old frame did not settle") + } + select { + case id := <-h.closed: + if id != old.SessionID { + t.Fatalf("retired session=%d want old%d", id, old.SessionID) + } + case <-time.After(3 * time.Second): + t.Fatal("settled admitted old session was not retired") + } + if _, _, _, found := h.SessionState(old.SessionID); found { + t.Fatal("settled old coverage survived retirement") + } + got, err := store.Read(5) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("admitted old wire session regressed bytes: err=%v", err) + } +} diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go new file mode 100644 index 0000000000..c09081897c --- /dev/null +++ b/seaweed-block/core/storage/data_sync.go @@ -0,0 +1,102 @@ +package storage + +import ( + "fmt" + "io" + "log" + "os" +) + +// Data-only sync applies to WAL/extent data on Linux by default. Descriptor slots, +// chunk maps, creation and directory operations retain full fsync. +func configuredDataSyncMode() (string, error) { + mode := os.Getenv("SWBLOCK_SYNC") + if mode == "" { + mode = defaultDataFileSyncMode + } + switch mode { + case "fsync": + return mode, nil + case "fdatasync": + return mode, dataSyncSupported() + default: + return "", fmt.Errorf("storage: invalid SWBLOCK_SYNC %q", mode) + } +} + +func newDataFileSync(f *os.File) (func() error, error) { + mode, err := configuredDataSyncMode() + if err != nil { + return nil, err + } + if mode == "fsync" { + return f.Sync, nil + } + log.Printf("storage: WAL/extent sync=fdatasync file=%s", f.Name()) + return func() error { return fdatasyncFile(f) }, nil +} + +// Configuration errors must not create or initialize a volume file. +func validateNewStorePolicy() error { + if _, err := configuredDataSyncMode(); err != nil { + return err + } + _, err := configuredAllocationMode() + return err +} + +func configuredAllocationMode() (string, error) { + mode := os.Getenv("SWBLOCK_ALLOCATION") + prezero := os.Getenv("SWBLOCK_PREZERO") + if prezero != "" && prezero != "0" && prezero != "1" { + return "", fmt.Errorf("storage: invalid SWBLOCK_PREZERO %q", prezero) + } + if prezero == "1" { + if mode != "" && mode != "prezero" { + return "", fmt.Errorf("storage: SWBLOCK_PREZERO conflicts with SWBLOCK_ALLOCATION %q", mode) + } + mode = "prezero" + } + switch mode { + case "", "sparse": + return "sparse", nil + case "fallocate": + return "", fmt.Errorf("storage: fallocate allocation is disabled; use sparse or explicit prezero") + case "prezero": + return mode, dataSyncSupported() + default: + return "", fmt.Errorf("storage: invalid SWBLOCK_ALLOCATION %q", mode) + } +} + +// Only newly-created files reach this hook; existing bytes are never rewritten. +func prezeroNewStore(f *os.File, size int64) error { + mode, err := configuredAllocationMode() + if err != nil { + return err + } + if mode == "sparse" { + return nil + } + zero := make([]byte, 1<<20) + for off := int64(0); off < size; { + b := zero[:min(int64(len(zero)), size-off)] + n, err := f.WriteAt(b, off) + if err != nil { + return fmt.Errorf("storage: prezero: %w", err) + } + if n != len(b) { + return io.ErrShortWrite + } + off += int64(n) + } + // Allocation/size/extent metadata must be fully durable before the check. + if err := f.Sync(); err != nil { + return err + } + if err := verifyInitializedFile(f); err != nil { + return fmt.Errorf("storage: prezero verification: %w", err) + } + log.Printf("storage: prezero FIEMAP verified initialized file=%s bytes=%d", f.Name(), size) + return nil +} diff --git a/seaweed-block/core/storage/data_sync_linux.go b/seaweed-block/core/storage/data_sync_linux.go new file mode 100644 index 0000000000..23273f33f4 --- /dev/null +++ b/seaweed-block/core/storage/data_sync_linux.go @@ -0,0 +1,63 @@ +//go:build linux + +package storage + +import ( + "fmt" + "golang.org/x/sys/unix" + "os" + "unsafe" +) + +// FIEMAP with SYNC resolves delayed allocation before inspecting the mapping. +// Reject holes, unknown/delayed mappings and unwritten extents; fallocate alone +// does not satisfy the initialized-file experiment's precondition. +const defaultDataFileSyncMode = "fdatasync" + +func verifyInitializedFile(f *os.File) error { return verifyAllocatedFile(f, true) } + +func verifyAllocatedFile(f *os.File, written bool) error { + info, err := f.Stat() + if err != nil { + return err + } + type extent struct { + Logical, Physical, Length uint64 + Reserved [2]uint64 + Flags uint32 + Reserved2 [3]uint32 + } + type mapping struct { + Start, Length uint64 + Flags, Mapped, Count, Reserved uint32 + Extents [128]extent + } + end := uint64(info.Size()) + var covered uint64 + for covered < end { + m := mapping{Start: covered, Length: end - covered, Flags: 1, Count: 128} + _, _, errno := unix.Syscall(unix.SYS_IOCTL, f.Fd(), 0xc020660b, uintptr(unsafe.Pointer(&m))) + if errno != 0 { + return fmt.Errorf("storage: FIEMAP: %w", errno) + } + if m.Mapped == 0 || m.Mapped > m.Count { + return fmt.Errorf("storage: uninitialized file at %d", covered) + } + for _, e := range m.Extents[:m.Mapped] { + if e.Logical > covered || e.Length == 0 || e.Logical+e.Length < e.Logical || e.Flags&(2|4) != 0 || (written && e.Flags&0x800 != 0) { + return fmt.Errorf("storage: hole or unwritten extent at %d (logical=%d flags=%#x)", covered, e.Logical, e.Flags) + } + next := e.Logical + e.Length + if next <= covered { + return fmt.Errorf("storage: FIEMAP made no progress") + } + covered = next + } + } + return nil +} + +func dataSyncSupported() error { return nil } +func fdatasyncFile(f *os.File) error { return unix.Fdatasync(int(f.Fd())) } + +func fallocateFile(f *os.File, size int64) error { return unix.Fallocate(int(f.Fd()), 0, 0, size) } diff --git a/seaweed-block/core/storage/data_sync_linux_test.go b/seaweed-block/core/storage/data_sync_linux_test.go new file mode 100644 index 0000000000..e91897834f --- /dev/null +++ b/seaweed-block/core/storage/data_sync_linux_test.go @@ -0,0 +1,303 @@ +//go:build linux + +package storage + +import ( + "bufio" + "bytes" + "context" + "fmt" + "golang.org/x/sys/unix" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +func TestPrezeroCreatesInitializedVolume(t *testing.T) { + t.Setenv("SWBLOCK_ALLOCATION", "") + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", "1") + path := filepath.Join(t.TempDir(), "volume") + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + defer s.Close() + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = verifyInitializedFile(f); e != nil { + t.Fatalf("prezero must eliminate holes and unwritten extents: %v", e) + } + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(31) + if e != nil || !bytes.Equal(b, make([]byte, 4096)) { + t.Fatalf("new extent bytes: %v", e) + } +} + +func TestInitializedFileRejectsSparseAndUnwritten(t *testing.T) { + f, e := os.CreateTemp(t.TempDir(), "volume") + if e != nil { + t.Fatal(e) + } + defer f.Close() + if e = f.Truncate(1 << 20); e != nil { + t.Fatal(e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("sparse file accepted") + } + if e = unix.Fallocate(int(f.Fd()), 0, 0, 1<<20); e != nil { + t.Fatal(e) + } + if e = verifyInitializedFile(f); e == nil { + t.Fatal("unwritten extents accepted") + } +} + +func TestFdatasyncAcknowledgedWritesSurviveSIGKILL(t *testing.T) { + if path := os.Getenv("SWBLOCK_TEST_SYNC_CRASH"); path != "" { + if os.Getenv("SWBLOCK_TEST_SYNC_CHILD_FAILURE") == "1" { + _ = os.Stdout.Close() + time.Sleep(30 * time.Millisecond) + fmt.Fprintln(os.Stderr, "SYNC_CHILD_FAILURE_SETTLED") + os.Exit(7) + } + opts := WALStoreOptions{} + if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { + opts.WMode = WModeStrict + } + s, e := CreateWALStoreWithOptions(path, 32, 4096, opts) + if e != nil { + panic(e) + } + if os.Getenv("SWBLOCK_PREZERO") == "0" && verifyInitializedFile(s.fd) == nil { + panic("sparse crash arm was silently prezeroed") + } + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + panic(e) + } + for _, lba := range []uint32{0, 13, 31} { + if _, e = s.Write(lba, bytes.Repeat([]byte{byte(lba + 17)}, 4096)); e != nil { + panic(e) + } + } + if n, e := s.Sync(); e != nil || n < 3 { + panic(fmt.Sprintf("Sync=%d %v", n, e)) + } + if os.Getenv("SWBLOCK_TEST_EXTENT") == "1" { + if e = s.flusher.flushOnce(); e != nil { + panic(e) + } + } + fmt.Println("SYNC_ACKNOWLEDGED") + for { + time.Sleep(time.Hour) + } + } + for _, strict := range []string{"0", "1"} { + for _, prezero := range []string{"0", "1"} { + for _, extent := range []string{"0", "1"} { + t.Run("strict"+strict+"/prezero"+prezero+"/extent"+extent, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "volume") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_ALLOCATION=", "SWBLOCK_SYNC=fdatasync", "SWBLOCK_PREZERO="+prezero, "SWBLOCK_TEST_SYNC_CRASH="+path, "SWBLOCK_TEST_EXTENT="+extent, "SWBLOCK_TEST_STRICT="+strict) + out, e := cmd.StdoutPipe() + if e != nil { + t.Fatal(e) + } + var stderr bytes.Buffer + cmd.Stderr = &stderr + if e = cmd.Start(); e != nil { + t.Fatal(e) + } + var waitOnce sync.Once + var waitErr error + wait := func() { waitOnce.Do(func() { waitErr = cmd.Wait() }) } + defer func() { _ = cmd.Process.Kill(); wait() }() + scan := bufio.NewScanner(out) + ready := false + for scan.Scan() { + if scan.Text() == "SYNC_ACKNOWLEDGED" { + ready = true + break + } + } + if !ready { + wait() + t.Fatalf("no sync ACK: scan=%v wait=%v %s", scan.Err(), waitErr, stderr.String()) + } + if e = cmd.Process.Kill(); e != nil { + t.Fatal(e) + } + wait() + exit, ok := waitErr.(*exec.ExitError) + if !ok { + t.Fatalf("not killed: %v", waitErr) + } + status, ok := exit.Sys().(syscall.WaitStatus) + if !ok || status.Signal() != syscall.SIGKILL { + t.Fatalf("wrong exit: %v", waitErr) + } + t.Setenv("SWBLOCK_ALLOCATION", "") + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_PREZERO", prezero) + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + for _, lba := range []uint32{0, 13, 31} { + b, e := s.Read(lba) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{byte(lba + 17)}, 4096)) { + t.Fatalf("acknowledged block%d differs: %v", lba, e) + } + } + }) + } + } + + } +} + +// Run under strace with the sync environment unset/set to verify the +// syscall boundary independently of the selected function's Go identity. +func TestDataSyncSyscallProbe(t *testing.T) { + opts := WALStoreOptions{} + if os.Getenv("SWBLOCK_TEST_STRICT") == "1" { + opts.WMode = WModeStrict + } + s, e := CreateWALStoreWithOptions(filepath.Join(t.TempDir(), "volume"), 32, 4096, opts) + if e != nil { + t.Fatal(e) + } + defer s.Close() + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + if _, e = s.Write(7, bytes.Repeat([]byte{0x6d}, 4096)); e != nil { + t.Fatal(e) + } + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + if e = s.flusher.flushOnce(); e != nil { + t.Fatal(e) + } + b, e := s.Read(7) + if e != nil || !bytes.Equal(b, bytes.Repeat([]byte{0x6d}, 4096)) { + t.Fatalf("readback: %v", e) + } +} + +func TestFallocateAllocationIsRefused(t *testing.T) { + t.Setenv("SWBLOCK_PREZERO", "0") + t.Setenv("SWBLOCK_ALLOCATION", "fallocate") + s, err := CreateWALStore(filepath.Join(t.TempDir(), "volume"), 32, 4096) + if err == nil { + s.Close() + t.Fatal("fallocate allocation must be refused") + } +} + +func TestDefaultCreatedVolumeStaysSparse(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", "") + t.Setenv("SWBLOCK_PREZERO", "") + t.Setenv("SWBLOCK_ALLOCATION", "") + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStore(path, 262144, 4096) + if err != nil { + t.Fatal(err) + } + defer s.Close() + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + stat := info.Sys().(*syscall.Stat_t) + if allocated := stat.Blocks * 512; allocated >= info.Size()/4 { + t.Fatalf("default volume lost sparse allocation: allocated=%d size=%d", allocated, info.Size()) + } +} + +func TestInvalidCreatePolicyLeavesNoFileAndAllowsRetry(t *testing.T) { + for _, tc := range []struct{ name, sync, allocation, prezero string }{ + {"sync-before-prezero", "bad", "prezero", "1"}, + {"allocation", "fdatasync", "bad", "0"}, + {"fallocate", "fdatasync", "fallocate", "0"}, + {"prezero", "fdatasync", "", "bad"}, + {"conflict", "fdatasync", "sparse", "1"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("SWBLOCK_SYNC", tc.sync) + t.Setenv("SWBLOCK_ALLOCATION", tc.allocation) + t.Setenv("SWBLOCK_PREZERO", tc.prezero) + path := filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStore(path, 32, 4096) + if err == nil { + s.Close() + t.Fatal("invalid policy accepted") + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("invalid policy touched volume before refusal: %v", err) + } + t.Setenv("SWBLOCK_SYNC", "fdatasync") + t.Setenv("SWBLOCK_ALLOCATION", "sparse") + t.Setenv("SWBLOCK_PREZERO", "0") + s, err = CreateWALStore(path, 32, 4096) + if err != nil { + t.Fatalf("corrected retry failed: %v", err) + } + s.Close() + }) + } +} + +func TestSyncCrashFailureDiagnosticsWaitForStderr(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestFdatasyncAcknowledgedWritesSurviveSIGKILL$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=1", "SWBLOCK_ALLOCATION=", "SWBLOCK_PREZERO=0") + out, err := cmd.CombinedOutput() + if err == nil || ctx.Err() != nil { + t.Fatalf("wrong failed-child outcome: %v %v", err, ctx.Err()) + } + if !strings.Contains(string(out), "SYNC_CHILD_FAILURE_SETTLED") || strings.Contains(string(out), "WARNING: DATA RACE") { + t.Fatalf("failure diagnostics read before child settlement: %s", out) + } +} + +func TestSyncControlsIgnoreAmbientAllocation(t *testing.T) { + for _, tc := range []struct{ name, test, allocation string }{ + {"prezero", "TestPrezeroCreatesInitializedVolume", "sparse"}, + {"crash-matrix", "TestFdatasyncAcknowledgedWritesSurviveSIGKILL", "prezero"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+tc.test+"$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_SYNC_CRASH=", "SWBLOCK_TEST_SYNC_CHILD_FAILURE=", "SWBLOCK_ALLOCATION="+tc.allocation, "SWBLOCK_PREZERO=0") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("ambient allocation contaminated control: %v: %s", err, out) + } + }) + } +} diff --git a/seaweed-block/core/storage/data_sync_other.go b/seaweed-block/core/storage/data_sync_other.go new file mode 100644 index 0000000000..7018474354 --- /dev/null +++ b/seaweed-block/core/storage/data_sync_other.go @@ -0,0 +1,19 @@ +//go:build !linux + +package storage + +import ( + "errors" + "os" +) + +const defaultDataFileSyncMode = "fsync" + +func dataSyncSupported() error { + return errors.New("storage: fdatasync/prezero experiment requires Linux") +} +func fdatasyncFile(*os.File) error { return dataSyncSupported() } +func verifyInitializedFile(*os.File) error { return dataSyncSupported() } + +func fallocateFile(*os.File, int64) error { return dataSyncSupported() } +func verifyAllocatedFile(*os.File, bool) error { return dataSyncSupported() } diff --git a/seaweed-block/core/storage/data_sync_replay_linux_test.go b/seaweed-block/core/storage/data_sync_replay_linux_test.go new file mode 100644 index 0000000000..758c95ffe8 --- /dev/null +++ b/seaweed-block/core/storage/data_sync_replay_linux_test.go @@ -0,0 +1,148 @@ +//go:build linux + +package storage + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "testing" +) + +// External dm-log-writes harness calls prepare/write, replays only through +// the post-sync ACK mark onto a fresh device, then calls verify. Without that +// block-layer harness this helper is not a power-loss test. +func TestDataSyncPowerLossReplayHelper(t *testing.T) { + root := os.Getenv("SWBLOCK_REPLAY_ROOT") + if root == "" { + t.Skip("requires isolated dm-log-writes replay harness") + } + phase, kind := os.Getenv("SWBLOCK_REPLAY_PHASE"), os.Getenv("SWBLOCK_REPLAY_CASE") + path := filepath.Join(root, "probe") + payload := bytes.Repeat([]byte{0x7d}, 4096) + if kind == "wal" { + switch phase { + case "prepare": + s, e := CreateWALStore(path, 32, 4096) + if e != nil { + t.Fatal(e) + } + if e = s.Close(); e != nil { + t.Fatal(e) + } + case "write": + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + s.DisableAutoFlushForRecoveryTest() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + if _, e = s.Write(13, payload); e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") != "1" { + if _, e = s.Sync(); e != nil { + t.Fatal(e) + } + } + // Deliberately no Close: only the explicit Sync precedes the ACK mark. + case "verify": + s, e := OpenWALStore(path) + if e != nil { + t.Fatal(e) + } + defer s.Close() + if _, e = s.Recover(); e != nil { + t.Fatal(e) + } + b, e := s.Read(13) + if e != nil || !bytes.Equal(b, payload) { + t.Fatalf("REPLAY_BYTES_MISMATCH WAL: %v", e) + } + default: + t.Fatalf("unknown replay phase %q", phase) + } + } else { + switch phase { + case "prepare": + f, e := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) + if e != nil { + t.Fatal(e) + } + defer f.Close() + switch kind { + case "written": + if _, e = f.WriteAt(make([]byte, 1<<20), 0); e != nil { + t.Fatal(e) + } + case "unwritten": + if e = fallocateFile(f, 1<<20); e != nil { + t.Fatal(e) + } + case "hole": + if e = f.Truncate(1 << 20); e != nil { + t.Fatal(e) + } + case "growth": + if _, e = f.WriteAt(make([]byte, 4096), 0); e != nil { + t.Fatal(e) + } + default: + t.Fatalf("unknown replay case %q", kind) + } + if e = f.Sync(); e != nil { + t.Fatal(e) + } + case "write": + f, e := os.OpenFile(path, os.O_RDWR, 0) + if e != nil { + t.Fatal(e) + } + defer f.Close() + if _, e = f.WriteAt(payload, 128<<10); e != nil { + t.Fatal(e) + } + if os.Getenv("SWBLOCK_REPLAY_DROP_SYNC") != "1" { + if kind == "growth" { + e = f.Sync() + } else { + var sync func() error + sync, e = newDataFileSync(f) + if e == nil { + e = sync() + } + } + if e != nil { + t.Fatal(e) + } + } + case "verify": + f, e := os.Open(path) + if e != nil { + t.Fatal(e) + } + defer f.Close() + b := make([]byte, 4096) + n, e := f.ReadAt(b, 128<<10) + if e != nil || n != len(b) || !bytes.Equal(b, payload) { + t.Fatalf("REPLAY_BYTES_MISMATCH %s: n=%d err=%v", kind, n, e) + } + default: + t.Fatalf("unknown replay phase %q", phase) + } + } + if phase == "prepare" { + d, e := os.Open(root) + if e != nil { + t.Fatal(e) + } + defer d.Close() + if e = d.Sync(); e != nil { + t.Fatal(e) + } + } + fmt.Printf("REPLAY_%s_OK %s\n", phase, kind) +} diff --git a/seaweed-block/core/storage/wal_writer.go b/seaweed-block/core/storage/wal_writer.go index 1b6bf33638..558eb8b064 100644 --- a/seaweed-block/core/storage/wal_writer.go +++ b/seaweed-block/core/storage/wal_writer.go @@ -479,7 +479,13 @@ func (w *walWriter) logicalTailValue() uint64 { } // fsync forces buffered data to durable storage. -func (w *walWriter) fsync() error { return w.fd.Sync() } +func (w *walWriter) fsync() error { + sync, err := newDataFileSync(w.fd) + if err != nil { + return err + } + return sync() +} // usedFraction returns the fraction of the WAL region currently in // use, in the range [0, 1]. Used by the admission controller to diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 754caec8d4..29104f42fb 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -209,6 +209,9 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt // Frozen constructor for legacy-format regression fixtures; public Create // never reaches it after activation. Removed from production in row 14a. func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opts WALStoreOptions) (*WALStore, error) { + if err := validateNewStorePolicy(); err != nil { + return nil, err + } if blockSize == 0 { blockSize = DefaultBlockSize } @@ -254,7 +257,11 @@ func createLegacyWALStoreWithOptions(path string, numBlocks uint32, blockSize in _ = f.Close() return nil, fmt.Errorf("storage: fsync after create: %w", err) } - return openInitializedWithMetadata(path, f, &sb, metadata) + s, err := openInitializedWithMetadata(path, f, &sb, metadata) + if err != nil { + _ = f.Close() + } + return s, err } // OpenWALStore opens an existing store file WITHOUT recovering it. @@ -309,6 +316,10 @@ func openInitializedWithMetadata(path string, f *os.File, sb *superblock, metada // init hook that runs before the committer and flusher goroutines start // (the v3 store attaches its state there). func openInitializedInternal(path string, f *os.File, sb *superblock, metadata BlockMetadata, init func(*WALStore) error) (*WALStore, error) { + dataSync, err := newDataFileSync(f) + if err != nil { + return nil, err + } dm := newDirtyMap(64) // 64 shards is plenty for Phase 07 demo workloads s := &WALStore{ @@ -333,9 +344,9 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B s.walMutation.Store(1) s.syncWALFile = func() error { s.walSyncCalls.Add(1) - return f.Sync() + return dataSync() } - s.syncExtentFile = f.Sync + s.syncExtentFile = dataSync if init != nil { if err := init(s); err != nil { return nil, err diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 99d911141e..9c61731325 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -231,6 +231,9 @@ func createWALStoreV3MapAtCursorForTest(path string, numBlocks, blockSize uint32 } func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSize uint64, mode WMode, cursor, chunkBlocks uint64, opts WALStoreOptions) (*WALStore, error) { + if err := validateNewStorePolicy(); err != nil { + return nil, err + } d := descriptorV3{ ImplKind: ImplKindWALStore, ImplVersion: walStoreImplVersion3, VolumeSize: uint64(numBlocks) * uint64(blockSize), ExtentSize: 64 * 1024, BlockSize: blockSize, @@ -269,6 +272,9 @@ func createWALStoreV3Configured(path string, numBlocks, blockSize uint32, walSiz return nil, err } err = fd.Truncate(totalSize) + if err == nil { + err = prezeroNewStore(fd, totalSize) + } if err == nil && chunkBlocks != 0 { var m *chunkLSNMapV3 m, err = createChunkLSNMapV3(path+".chunkmap", d, chunkBlocks) diff --git a/seaweed-block/core/transport/executor.go b/seaweed-block/core/transport/executor.go index e8eb0f44b7..26bd2f0419 100644 --- a/seaweed-block/core/transport/executor.go +++ b/seaweed-block/core/transport/executor.go @@ -1315,3 +1315,32 @@ func (e *BlockExecutor) recordSessionRunning(replicaID string, sessionID uint64) SessionID: sessionID, } } + +// PublishRecoveryPrefix forwards a completed-recovery certificate supplied by +// the engine's healthy publication. Failure conservatively retains the map. +// It does not certify subsequent live traffic or infer coverage from R. +func (e *BlockExecutor) PublishRecoveryPrefix(replicaID string, sessionID, epoch, endpointVersion, prefix uint64) { + if err := e.beginAsyncOperation(); err != nil { + return + } + go func() { + defer e.asyncWG.Done() + lineage := RecoveryLineage{SessionID: sessionID, Epoch: epoch, EndpointVersion: endpointVersion, FrontierHint: prefix} + conn, err := net.DialTimeout("tcp", e.replicaAddr, 2*time.Second) + if err != nil { + log.Printf("executor: prefix certificate %s: %v", replicaID, err) + return + } + defer conn.Close() + if err := e.trackTransientConn(conn); err != nil { + return + } + defer e.untrackTransientConn(conn) + if err := conn.SetDeadline(time.Now().Add(recoveryConnTimeout)); err != nil { + return + } + if err := WriteMsg(conn, MsgCertifiedPrefix, EncodeLineage(lineage)); err != nil { + log.Printf("executor: prefix certificate %s: %v", replicaID, err) + } + }() +} diff --git a/seaweed-block/core/transport/protocol.go b/seaweed-block/core/transport/protocol.go index c15344cfce..188974eed9 100644 --- a/seaweed-block/core/transport/protocol.go +++ b/seaweed-block/core/transport/protocol.go @@ -46,6 +46,10 @@ const ( // recovery-lane before any MsgShipEntry frames arrive. It replaces // payload-derived lane guessing from RecoveryLineage.TargetLSN. MsgRecoveryLaneStart byte = 0x08 + // MsgCertifiedPrefix carries a full lineage whose frontier is an explicit + // completed-recovery coverage certificate, never a scalar Sync maximum. + // No acknowledgement/old-peer fallback is needed: refusal retains history. + MsgCertifiedPrefix byte = 0x09 ) // RecoveryLineage binds a mutating recovery stream to one accepted recovery diff --git a/seaweed-block/core/transport/replica.go b/seaweed-block/core/transport/replica.go index 204709474a..b413222c7e 100644 --- a/seaweed-block/core/transport/replica.go +++ b/seaweed-block/core/transport/replica.go @@ -38,6 +38,17 @@ const ( // Returning a non-nil error → caller (handler) logs + closes conn. // Per INV-REPL-LIVE-LANE-STALE-FAILS-LOUD: live-lane stale entries // surface here as errors. +// RecoveryPrefixHook accepts explicit completed-prefix certificates. It does +// not derive source coverage from Sync. Admission is checked at the effect. +type SessionRetirer interface{ CloseSession(sessionID uint64) } + +// RecoveryPrefixHook accepts explicit completed-prefix certificates. It does +// not derive source coverage from Sync. Admission is checked at the effect. +type RecoveryPrefixHook interface { + CertifyRecoveryPrefix(lineage RecoveryLineage) error + CertifiedPrefix() uint64 +} + type ApplyHook interface { // ApplyRecovery routes the entry through the recovery-lane apply // path. Stale entries (LSN <= per-LBA applied) skip data + advance @@ -58,8 +69,11 @@ type ReplicaListener struct { wg sync.WaitGroup applyHook ApplyHook // optional gate plug-in; nil = direct apply - mu sync.Mutex - activeLineage RecoveryLineage + mu sync.Mutex + activeLineage RecoveryLineage + prefixEligible RecoveryLineage // one active source-covered recovery certificate + sessionFrames map[uint64]int + retiringSessions map[uint64]bool // 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 @@ -104,6 +118,12 @@ func NewReplicaListener(addr string, store storage.LogicalStorage) (*ReplicaList // it takes effect; a missing or invalid record refuses construction. An // empty floorPath (non-durable memback) keeps the floor in memory. func NewReplicaListenerWithFloor(addr string, store storage.LogicalStorage, volumeID, floorPath string) (*ReplicaListener, error) { + return NewReplicaListenerWithFloorAndApplyHook(addr, store, volumeID, floorPath, nil) +} + +// NewReplicaListenerWithFloorAndApplyHook preserves role and durable-floor +// admission while using the volume's shared apply ordering gate. +func NewReplicaListenerWithFloorAndApplyHook(addr string, store storage.LogicalStorage, volumeID, floorPath string, hook ApplyHook) (*ReplicaListener, error) { var floor uint64 if floorPath != "" { var err error @@ -111,7 +131,7 @@ func NewReplicaListenerWithFloor(addr string, store storage.LogicalStorage, volu return nil, err } } - r, err := NewReplicaListenerWithApplyHook(addr, store, nil) + r, err := NewReplicaListenerWithApplyHook(addr, store, hook) if err != nil { return nil, err } @@ -149,21 +169,31 @@ func (r *ReplicaListener) raiseFloor(epoch uint64) error { func (r *ReplicaListener) admitMutation(l RecoveryLineage) bool { r.mu.Lock() prev := r.activeLineage - r.mu.Unlock() - if !r.acceptMutationLineage(l) { + if !r.acceptMutationLineageLocked(l) { + r.mu.Unlock() return false } + if r.sessionFrames == nil { + r.sessionFrames = make(map[uint64]int) + } + r.sessionFrames[l.SessionID]++ // register before another lineage can retire it + r.mu.Unlock() if err := r.raiseFloor(l.Epoch); err != nil { - // Nothing changes on a refused frame: undo the lineage advance, - // unless another frame has moved it on since. r.mu.Lock() if r.activeLineage == l { r.activeLineage = prev } + r.markSessionRetiringLocked(l.SessionID) r.mu.Unlock() + r.endSessionFrame(l.SessionID) log.Printf("replica: refuse mutation at epoch %d: %v", l.Epoch, err) return false } + r.mu.Lock() + if prev.SessionID != l.SessionID { + r.markSessionRetiringLocked(prev.SessionID) + } + r.mu.Unlock() return true } @@ -231,6 +261,7 @@ func (r *ReplicaListener) Stop() { close(r.stopCh) r.listener.Close() r.wg.Wait() + r.closeSettledSessions() } // StopHard is like Stop but also forcibly closes all active handler @@ -266,6 +297,7 @@ func (r *ReplicaListener) StopHard() { _ = c.Close() } r.wg.Wait() + r.closeSettledSessions() } func (r *ReplicaListener) acceptLoop() { @@ -356,6 +388,14 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { // the fence waits for storage effects only, never for the network. var replyType byte var reply []byte + var admittedSession uint64 + admit := func(l RecoveryLineage) bool { + if !r.admitMutation(l) { + return false + } + admittedSession = l.SessionID + return true + } stop := func() bool { switch msgType { case MsgRecoveryLaneStart: @@ -364,12 +404,13 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode recovery lane start: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(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 + r.markPrefixEligibility(lineage, false) case MsgShipEntry: entry, err := DecodeShipEntry(payload) @@ -377,7 +418,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode ship entry: %v", err) return true } - if !r.admitMutation(entry.Lineage) { + if !admit(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 @@ -451,7 +492,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode rebuild block: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale rebuild block session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -474,7 +515,7 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: decode rebuild done: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale rebuild done session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -497,6 +538,8 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { log.Printf("replica: sync after rebuild done: %v", err) return true } + // A completed full BASE supplies the covered starting image. + r.markPrefixEligibility(lineage, true) // Echo the request's full lineage in the rebuild-done ack // so primary-side validators can consume it. resp := EncodeBarrierResp(BarrierResponse{ @@ -506,13 +549,19 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { replyType, reply = MsgBarrierResp, resp return true + case MsgCertifiedPrefix: + lineage, err := DecodeLineage(payload) + if err != nil || r.certifyRecoveryPrefix(lineage) != nil { + return true + } + case MsgBarrierReq: lineage, err := DecodeLineage(payload) if err != nil { log.Printf("replica: decode barrier req: %v", err) return true } - if !r.admitMutation(lineage) { + if !admit(lineage) { log.Printf("replica: reject stale barrier session=%d epoch=%d endpointVersion=%d", lineage.SessionID, lineage.Epoch, lineage.EndpointVersion) return true @@ -534,6 +583,9 @@ func (r *ReplicaListener) handleConn(conn net.Conn) { } return false }() + if admittedSession != 0 { + r.endSessionFrame(admittedSession) + } if mutating { r.endMutationFrame() } @@ -654,7 +706,7 @@ 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: + case MsgRecoveryLaneStart, MsgShipEntry, MsgRebuildBlock, MsgRebuildDone, MsgBarrierReq, MsgCertifiedPrefix: return true } return false @@ -726,6 +778,10 @@ func (r *ReplicaListener) AdmitAsReplica(epoch uint64) error { func (r *ReplicaListener) acceptMutationLineage(incoming RecoveryLineage) bool { r.mu.Lock() defer r.mu.Unlock() + return r.acceptMutationLineageLocked(incoming) +} + +func (r *ReplicaListener) acceptMutationLineageLocked(incoming RecoveryLineage) bool { if incoming.SessionID == 0 || incoming.Epoch == 0 || incoming.EndpointVersion == 0 { return false @@ -776,3 +832,84 @@ func compareLineage(a, b RecoveryLineage) int { return 0 } } + +// A certificate cannot introduce an unseen session or survive a later one. +// Lock order: listener.mu -> gate.mu -> store boundary read. There is no wire +// or physical I/O here; fencing/session admission cannot cross the effect. +func (r *ReplicaListener) certifyRecoveryPrefix(lineage RecoveryLineage) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.primary || (r.requireRole && !r.assigned) || lineage.Epoch < r.epochFloor || + lineage.SessionID == 0 || lineage.EffectiveFrontierHint() == 0 || !r.activeLineage.Equivalent(lineage) || !r.prefixEligible.Equivalent(lineage) { + return fmt.Errorf("replica: uncertified/stale recovery lineage") + } + hook, ok := r.applyHook.(RecoveryPrefixHook) + if !ok { + return fmt.Errorf("replica: no recovery prefix hook") + } + return hook.CertifyRecoveryPrefix(lineage) +} + +// A successful scan can extend only an already-covered starting prefix. The +// engine starts catch-up at probed R+1; R is monotone, so observing local R<=P +// at the lane marker is a conservative bound on that starting R. A completed +// full BASE instead supplies its own prefix. A refusal only retains history. +func (r *ReplicaListener) markPrefixEligibility(lineage RecoveryLineage, fullBase bool) { + r.mu.Lock() + defer r.mu.Unlock() + if !r.activeLineage.Equivalent(lineage) || r.primary || (r.requireRole && !r.assigned) { + return + } + r.prefixEligible = RecoveryLineage{} + hook, ok := r.applyHook.(RecoveryPrefixHook) + if !ok { + return + } + synced, _, _ := r.store.Boundaries() + if fullBase || synced <= hook.CertifiedPrefix() { + r.prefixEligible = lineage + } +} + +// Retirement tracks logical-session frames, not socket lifetimes. A newer +// session may run while an admitted older frame is parked before the hook. +// Lock order remains listener.mu -> gate.mu; versions and P are not released. +func (r *ReplicaListener) markSessionRetiringLocked(id uint64) { + if id == 0 { + return + } + if r.retiringSessions == nil { + r.retiringSessions = make(map[uint64]bool) + } + r.retiringSessions[id] = true + r.retireSessionIfSettledLocked(id) +} +func (r *ReplicaListener) retireSessionIfSettledLocked(id uint64) { + if !r.retiringSessions[id] || id == r.activeLineage.SessionID || r.sessionFrames[id] != 0 { + return + } + if hook, ok := r.applyHook.(SessionRetirer); ok { + hook.CloseSession(id) + } + delete(r.retiringSessions, id) +} +func (r *ReplicaListener) endSessionFrame(id uint64) { + r.mu.Lock() + defer r.mu.Unlock() + r.sessionFrames[id]-- + if r.sessionFrames[id] == 0 { + delete(r.sessionFrames, id) + } + r.retireSessionIfSettledLocked(id) +} +func (r *ReplicaListener) closeSettledSessions() { + r.mu.Lock() + defer r.mu.Unlock() + if hook, ok := r.applyHook.(SessionRetirer); ok { + hook.CloseSession(r.activeLineage.SessionID) + for id := range r.retiringSessions { + hook.CloseSession(id) + } + } + r.retiringSessions = nil +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 8b1152d2cd..d4d621ecd1 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -245,6 +245,8 @@ The attempt path is never removed, so a late create can never land after a delet **FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. +**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's expiry and deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim. + **Takeover** (`core/storage/chunk_restore.go` `ClaimChunkHead`, called before the chunk layer attaches in `core/frontend/durable/provider_chunk.go`): read HEAD; fence if HEAD has a higher epoch or another holder at the same epoch; seed the local LSN frontier from HEAD (`PrepareRestore`); CAS HEAD to the new epoch and holder with `State = active`; on an unknown outcome, succeed only if a re-read shows the exact proposal. I/O opens afterwards; blocks load lazily on first read. ```mermaid @@ -266,7 +268,14 @@ sequenceDiagram A->>A: self-fence when ValidForNs runs out M->>M: wait for expiry, restart deadline and skew bound, then mint epoch e+1 end + M->>M: the issue write also starts B's lease (horizon issue+1.5·TTL, deadline issue+TTL) M->>B: assignment at epoch e+1 and a lease + opt B dies before renewing or claiming (HEAD still at epoch e) + M->>M: wait for B's lease expiry, deadline and skew bound + M->>F: GetHead (only after that admission) + M->>M: HEAD epoch is older than e+1, so mint epoch e+2 for host C, lost range from that HEAD's RemoteLSN + Note over B,F: a claim B already sent may still land at e+1, C's claim at e+2 supersedes it, and a returning B is refused at attach (expired lease) and by the higher HEAD epoch + end B->>F: GetHead B->>B: refuse if HEAD epoch is higher, else seed the local frontier from HEAD B->>F: CASHead expected {current gen, e}, next {epoch e+1, holder B, active} @@ -284,13 +293,14 @@ Lease states: ```mermaid stateDiagram-v2 state "Lease (blockmaster)" as L { - [*] --> Granted: Renew + [*] --> Granted: first Renew after bind + [*] --> Granted: move issue starts the new holder's lease Granted --> Granted: Renew before horizon and deadline (from memory) Granted --> Revoking: BeginWorkspaceRevocation Revoking --> Acked: host acks detached HEAD gen while the lease is valid Acked --> Moved: CLEAN move Granted --> Expired: horizon or deadline passes - Expired --> Moved: FORCED move after expiry + skew bound + Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) } ``` diff --git a/seaweed-block/docs/design/block-design.md b/seaweed-block/docs/design/block-design.md index dae9c48a72..f3f35d38e8 100644 --- a/seaweed-block/docs/design/block-design.md +++ b/seaweed-block/docs/design/block-design.md @@ -297,6 +297,10 @@ stateDiagram-v2 Unknown --> Healthy: probe and barrier succeed Healthy --> Degraded: barrier or ship failure Degraded --> CatchingUp: gap within the primary's WAL + CatchingUp --> CatchingUp: identical recovery facts retain the prepared session + CatchingUp --> CatchingUp: active session refuses promotion readiness + Healthy --> Healthy: delayed probe retains completed durable R + Healthy --> Healthy: completed recovery certifies P, prune version suffix CatchingUp --> Healthy: caught up to the target CatchingUp --> Degraded: catch-up fails Degraded --> Healthy: recovers diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 112f6e2df3..6a0caa5c86 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -88,15 +88,15 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL (an epoch issued by a move already has its lease) | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding; each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001` | ### M3 Replica role and peer state @@ -114,6 +114,13 @@ stateDiagram-v2 Excluded --> Supporting: later fact lists self as a peer ``` +The apply gate retains versions only above its certified contiguous prefix P. +Completed recovery plus post-close healthy publication sends an explicit full-lineage +certificate; current listener admission and the durable boundary guard it. A catch-up certificate also requires a covered starting image (local R at its lane marker no greater than P); a completed full BASE supplies its own image. A missing certificate retains history. Sync R, +ordinary live traffic and session changes do not advance P. This implementation +prunes at successful recovery certification only; healthy-run growth remains an +RF2 qualification limitation until ordered-live certification is wired (#297). Settled superseded logical sessions release coverage after their admitted frames finish; shared versions and P survive. Seed enumeration and healthy-run growth remain RF2 qualification limits. + **Host role and listener admission.** | From | To | Event and guard | Enforced in | Protects | @@ -125,14 +132,16 @@ stateDiagram-v2 | Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | | any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | | (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | -| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | +| Supporting | promotion candidate | no active recovery session; member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | + +**Recovery observation and apply ordering.** A probe publishes its fresh boundaries before reachability, and each emitted recovery is prepared under the adapter mutex before the next event. Same-identity delayed probes retain completed durable R; missing probe boundaries remain unknown until a valid observation arrives. Every lane and session shares one replica-wide per-LBA applied-LSN map under the apply mutex; session close releases coverage only. Recovery skips stale data while advancing its own coverage; stale live data fails without advancing recovery coverage. **Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). | From | To | Event and guard | Enforced in | Protects | |---|---|---|---|---| | `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | | `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | | any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | | `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | @@ -329,7 +338,7 @@ snapshot lifetime; local persistence does not bypass it. ## Part B. Invariant ledger -81 rows: 70 ACTIVE, 11 STUB; 15 kept from the internal ledger, 66 new. +117 rows: 98 ACTIVE, 19 STUB; 15 kept from the internal ledger, 102 new. The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger. @@ -401,10 +410,10 @@ Notes: |---|---|---|---|---|---|---| | `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | | `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceIssuePublishNeverLowersARenewedDeadline` (`core/authority/workspace_issue_publish_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that replaces the lease with the new holder's is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | @@ -419,13 +428,16 @@ Notes: | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | |---|---|---|---|---|---|---| +| `INV-REPL-SESSION-COVERAGE-RETIRE-001` | Superseded logical-session coverage is released only after every already-admitted frame for that session settles; newer sessions do not delay that release. Shared version history and P survive. | M3 replica admission / session retirement | `transport/replica.go` `admitMutation`, `endSessionFrame`; `ReplicaApplyGate.CloseSession` | `TestApplyGate_WireSessionTurnoverRetiresSettledCoverage`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes` | `ReplicaReviewGuards` NoEarlyRetirement/NoSettledHistory | ACTIVE | +| `INV-REPL-RECOVERY-SESSION-UNIQUE-001` | Each runtime observation selects at most one recovery session; delayed same-identity facts cannot restart a completed prefix, while a higher primary head or replacement identity still permits new work. | M3 recovery observation / preparation | `core/adapter/adapter.go`, `normalize.go`; `core/engine/apply.go` | `TestAdapter_OneRecoveryFromPostCloseStalledAck`, `TestAdapter_OneRecoveryPreparedWithinProbeBatch`, `TestAdapter_ConcurrentOldProbesNeverRestartHealthyRecovery`, `TestAdapter_ProbeUsesFreshBoundsBeforePreparingRecovery`, `TestRecoveryProbeKeepsCompletedRButAllowsNewWorkAndIdentity`, `TestMissingProbeAckRestoresNewerDurableProgress`, `TestC5_OrderStableAcrossRuns` | `ReplicaApplyOrder` NoDuplicateRecovery; `ReplicaReviewGuards` AckRestoresProgress | ACTIVE | +| `INV-REPL-NO-PER-LBA-DATA-REGRESSION` | Successful applies share a replica-wide per-LBA version across all sessions and lanes. Stale recovery advances only its own coverage; stale live entries fail. Closing a session or merging a lower seed cannot erase the applied version; failed physical writes do not publish it. Only an explicit completed-recovery prefix certificate advances P and prunes entries at/below P; the floor still rejects/skips old records. Synced R is not a certificate. Restart safety still requires substrate seeds. | M3 replica apply / session release | `core/replication/apply_gate.go`; blockvolume `replicationIngress` | `TestReplicationIngressSharesApplyVersionsAcrossSessions`, `TestApplyGate_OverlappingSessionsNeverRegressBytes`, `TestApplyGate_AlreadyAdmittedWireSessionNeverRegressesBytes`, `TestApplyGate_CloseAndLowerSeedNeverEraseReplicaVersion`, `TestApplyGate_FailedWriteDoesNotPublishReplicaVersion`, `TestApplyGate_CertifiedRecoveryClosesBoundVersionHistory`, `TestApplyGate_PrunedDurableVersionsRemainStale`, `TestApplyGate_CertifiedPrefixFreezesAcrossSessions`, `TestApplyGate_SyncedLiveMaximumDoesNotCoverRecoveryHole`, `TestApplyGate_HealthyRecoveryPublishesWirePrefix`, `TestApplyGate_WirePrefixCannotIntroduceOrReviveSession` | `ReplicaApplyOrder` NoRegression; `ReplicaPrefixFloor` NoRegression/CertifiedCoverage/OnlySuffix | ACTIVE | | `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | | `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | | `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | | `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | | `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | | `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. An active recovery session always refuses readiness, even if delayed bounds select DecisionNone. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`), `TestPromotionReadyRefusesDelayedProbeDuringNewRecovery` | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive`; `ReplicaReviewGuards` ReadyRequiresIdle | ACTIVE | | `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | | `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | | `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | @@ -446,17 +458,17 @@ Notes: | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | | `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | +| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound, of the current holder's lease (a move issue starts it; a predecessor's never admits); the lease reported to the host is the grant, never the horizon, and excludes half of the bound. HEAD is read only after that admission; it must be the expected holder's at the expected epoch or be at an older epoch, and the lost range starts at the remote LSN of that HEAD. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact`, `MoveWorkspace` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE | Notes: - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). -- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. +- `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. - `INV-WS-STOP-PENDING-001`: `WorkspaceTakeover` has no renewal cadence (a host may renew at any step), so StopPending adds no state to the model and no configuration is re-run; `INV-WS-LEASE-001` and `INV-WS-REVOKE-ACK-001` hold in StopPending unchanged. ### B.5 Workspace: the cut pipeline @@ -553,6 +565,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### Experimental data-file synchronization + +| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status | +|---|---|---|---|---|---|---| +| `INV-WAL-DATA-SYNC-001` | Linux WAL/extent sync defaults to fdatasync; `SWBLOCK_SYNC=fsync` explicitly restores full data-file sync (other platforms retain fsync). Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `data_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE | + ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 98c2c668f4..7b0862480e 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -317,3 +317,20 @@ end-to-end wall-clock latency guarantee. Keep long model runs off tp04. `HostBudget.tla` abstracts cooperating process slots, COW reservation and joined release. Config `HostBudget.cfg` checks three owners/two slots; `HostBudget_early_release.cfg` must violate HeldUntilJoined. It excludes degraded static fallback and does not prove filesystem locks, rates or physical-I/O deadlines. Native subprocess tests cover lock lifetime. HostBudget also models guarded configuration initialization: staged bytes are invisible until atomic publication; an initializer crash permits a successor. `HostBudget_partial_config.cfg` must violate NoPartialConfig. The syscall-level crash boundary is covered by TestKilledInitializerDoesNotPublishPartialConfiguration. +## Replica apply ordering + +`ReplicaApplyOrder.tla` models two admitted sessions on one LBA with three versions, plus the two events of one probe and a delayed post-completion probe. `R292_safe` checks `NoRegression`, `NoDuplicateRecovery` and `NoFalseKnown`; the four `R292_red_*` configurations remove one guard each. It abstracts successful physical applies only: it does not establish restart persistence, authority, byte-level framing, or I/O deadlines. + +`ReplicaPrefixFloor.tla` checks two LBAs/three source versions with explicit +covered-prefix certification, suffix pruning and stale checks against the floor. +`R293_prefix_safe` checks `NoRegression`, `CertifiedCoverage`, and `OnlySuffix`; +its two negative controls infer a prefix from the synced maximum or omit the +floor after pruning. It does not establish the wire certificate's provenance, +restart persistence, live-prefix extension, or a fixed memory cap without closes. + +`ReplicaReviewGuards.tla` checks two logical sessions with one admitted frame +per session, settled-coverage retirement, active-recovery readiness refusal and +one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; +four negative controls separately remove retirement, the frame join, the +readiness guard or ACK progress restoration. This abstracts successful admitted +frames and does not prove physical-I/O, authority rollback or timing behavior. diff --git a/seaweed-block/docs/spec/ReplicaApplyOrder.tla b/seaweed-block/docs/spec/ReplicaApplyOrder.tla new file mode 100644 index 0000000000..3ff2348cff --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaApplyOrder.tla @@ -0,0 +1,54 @@ +------------------------- MODULE ReplicaApplyOrder ------------------------- +EXTENDS Integers, TLC + +\* Two admitted sessions, one LBA, three versions. Bytes are represented by +\* their LSN. Storage faults, restart persistence and authority are external +\* obligations; this model checks successful apply ordering and probe dedupe. +CONSTANTS SharedVersions, PrepareEachEvent, MonotoneFacts, PreserveUnknownConfidence +VARIABLES applied, local, bytes, seen, stage, active, starts, replicaR, factsKnown, knownDecision +vars == <> +Max(a,b) == IF a > b THEN a ELSE b +Init == /\ applied = 0 /\ local = [s \in 1..2 |-> 0] + /\ bytes = 0 /\ seen = 0 /\ stage = 0 + /\ active = FALSE /\ starts = 0 /\ replicaR = 0 + /\ factsKnown = TRUE /\ knownDecision = TRUE + +\* One shared mutex covers stale check, physical apply and version publication. +Apply(s,n) == LET floor == IF SharedVersions THEN applied ELSE local[s] + IN /\ bytes' = IF n > floor THEN n ELSE bytes + /\ applied' = Max(applied,n) + /\ local' = [local EXCEPT ![s] = Max(@,n)] + /\ seen' = Max(seen,n) + /\ UNCHANGED <> + +\* A probe's two semantic events must observe the same reserved session. +FirstEvent == /\ stage = 0 /\ stage' = 1 /\ starts' = 1 + /\ active' = PrepareEachEvent + /\ UNCHANGED <> +SecondEvent == /\ stage = 1 /\ stage' = 2 + /\ starts' = IF active THEN starts ELSE starts + 1 + /\ active' = TRUE + /\ UNCHANGED <> +Complete == /\ stage = 2 /\ stage' = 3 /\ replicaR' = 3 + /\ active' = FALSE + /\ UNCHANGED <> +DelayedProbe == /\ stage = 3 /\ stage' = 4 + /\ replicaR' = IF MonotoneFacts THEN replicaR ELSE 1 + /\ starts' = IF replicaR' < 3 THEN starts + 1 ELSE starts + /\ active' = (replicaR' < 3) + /\ UNCHANGED <> +\* Retaining durable R does not give an all-zero probe known confidence. +MissingProbe == /\ stage = 3 /\ stage' = 5 + /\ factsKnown' = FALSE + /\ knownDecision' = ~PreserveUnknownConfidence + /\ UNCHANGED <> +FreshAck == /\ stage = 5 /\ stage' = 3 + /\ factsKnown' = TRUE /\ knownDecision' = TRUE + /\ UNCHANGED <> +Next == (\E s \in 1..2, n \in 1..3 : Apply(s,n)) + \/ FirstEvent \/ SecondEvent \/ Complete \/ DelayedProbe \/ MissingProbe \/ FreshAck +Spec == Init /\ [][Next]_vars +NoRegression == bytes = seen +NoDuplicateRecovery == starts <= 1 +NoFalseKnown == ~factsKnown => ~knownDecision +============================================================================= diff --git a/seaweed-block/docs/spec/ReplicaPrefixFloor.tla b/seaweed-block/docs/spec/ReplicaPrefixFloor.tla new file mode 100644 index 0000000000..70e419d693 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaPrefixFloor.tla @@ -0,0 +1,31 @@ +----------------------- MODULE ReplicaPrefixFloor ----------------------- +EXTENDS Integers, TLC +CONSTANTS UseFloor, CertifiedOnly +VARIABLES data, seen, versions, durable, prefix +vars == <> +Addr(n) == IF n = 2 THEN 2 ELSE 1 +Max(a,b) == IF a > b THEN a ELSE b +Covered(p) == \A n \in 1..p : data[Addr(n)] >= n +Init == /\ data = [i \in 1..2 |-> 0] /\ seen = data /\ versions = data + /\ durable = 0 /\ prefix = 0 +Apply(n) == LET i == Addr(n) + threshold == Max(versions[i], IF UseFloor THEN prefix ELSE 0) + IN /\ data' = IF n > threshold THEN [data EXCEPT ![i] = n] ELSE data + /\ seen' = [seen EXCEPT ![i] = Max(@,n)] + /\ versions' = IF n > threshold THEN [versions EXCEPT ![i] = n] ELSE versions + /\ UNCHANGED <> +Sync == /\ durable' = Max(durable, Max(data[1],data[2])) + /\ UNCHANGED <> +Certify(p) == /\ p > prefix /\ p <= durable + /\ (~CertifiedOnly \/ Covered(p)) + /\ prefix' = p + /\ versions' = [i \in 1..2 |-> IF versions[i] <= p THEN 0 ELSE versions[i]] + /\ UNCHANGED <> +\* Session changes, ordinary live writes, disconnects and Sync do not certify. +RestartSession == UNCHANGED vars +Next == (\E n \in 1..3 : Apply(n)) \/ Sync \/ (\E p \in 1..3 : Certify(p)) \/ RestartSession +Spec == Init /\ [][Next]_vars +NoRegression == data = seen +CertifiedCoverage == Covered(prefix) +OnlySuffix == \A i \in 1..2 : versions[i] = 0 \/ versions[i] > prefix +============================================================================= \ No newline at end of file diff --git a/seaweed-block/docs/spec/ReplicaReviewGuards.tla b/seaweed-block/docs/spec/ReplicaReviewGuards.tla new file mode 100644 index 0000000000..82e179c078 --- /dev/null +++ b/seaweed-block/docs/spec/ReplicaReviewGuards.tla @@ -0,0 +1,32 @@ +---------------------- MODULE ReplicaReviewGuards ---------------------- +EXTENDS Integers, TLC +CONSTANTS RetireSettled, WaitForFrames, GuardActive, RestoreAck +VARIABLES current, refs, coverage, active, ready, missing, observedR +vars == <> +Init == /\ current = 1 /\ refs = [s \in 1..2 |-> 0] /\ coverage = {1} + /\ active = FALSE /\ ready = FALSE /\ missing = TRUE /\ observedR = 100 +Admit(s) == /\ s >= current /\ refs[s] = 0 + /\ current' = s /\ refs' = [refs EXCEPT ![s] = 1] + /\ coverage' = (coverage \cup {s}) \ ( + IF RetireSettled /\ s # current /\ (refs[current] = 0 \/ ~WaitForFrames) + THEN {current} ELSE {}) + /\ UNCHANGED <> +Release(s) == /\ refs[s] = 1 /\ refs' = [refs EXCEPT ![s] = 0] + /\ coverage' = IF RetireSettled /\ s # current THEN coverage \ {s} ELSE coverage + /\ UNCHANGED <> +Prepare == /\ ~active /\ active' = TRUE /\ ready' = FALSE + /\ UNCHANGED <> +DelayedProbe == /\ active /\ ready' = ~GuardActive + /\ UNCHANGED <> +Finish == /\ active /\ active' = FALSE /\ ready' = TRUE + /\ UNCHANGED <> +Ack == /\ missing /\ missing' = FALSE + /\ observedR' = IF RestoreAck THEN 150 ELSE 100 + /\ UNCHANGED <> +Next == (\E s \in 1..2 : Admit(s) \/ Release(s)) \/ Prepare \/ DelayedProbe \/ Finish \/ Ack +Spec == Init /\ [][Next]_vars +NoEarlyRetirement == \A s \in 1..2 : refs[s] = 1 => s \in coverage +NoSettledHistory == \A s \in coverage : s = current \/ refs[s] = 1 +ReadyRequiresIdle == ready => ~active +AckRestoresProgress == ~missing => observedR = 150 +============================================================================= \ No newline at end of file diff --git a/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg new file mode 100644 index 0000000000..c2893f1af0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_delayed_prepare.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = FALSE + MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE +INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg new file mode 100644 index 0000000000..662b75c378 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_probe_rollback.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = FALSE + PreserveUnknownConfidence = TRUE +INVARIANT NoDuplicateRecovery diff --git a/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg new file mode 100644 index 0000000000..e457c7f536 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_session_versions.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = FALSE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE +INVARIANT NoRegression diff --git a/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg b/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg new file mode 100644 index 0000000000..762579b7e0 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_red_unknown_confidence.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE + PreserveUnknownConfidence = FALSE +INVARIANT NoFalseKnown diff --git a/seaweed-block/docs/spec/cfg/R292_safe.cfg b/seaweed-block/docs/spec/cfg/R292_safe.cfg new file mode 100644 index 0000000000..47c0f9fd2f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R292_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS SharedVersions = TRUE + PrepareEachEvent = TRUE + MonotoneFacts = TRUE + PreserveUnknownConfidence = TRUE +INVARIANTS NoRegression NoDuplicateRecovery NoFalseKnown diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg new file mode 100644 index 0000000000..c877180acc --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_forgot_floor.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = FALSE + CertifiedOnly = TRUE +INVARIANTS NoRegression diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg new file mode 100644 index 0000000000..2e7b34a866 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_red_synced_max.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = TRUE + CertifiedOnly = FALSE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg b/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg new file mode 100644 index 0000000000..8fc29bed97 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_prefix_safe.cfg @@ -0,0 +1,4 @@ +SPECIFICATION Spec +CONSTANTS UseFloor = TRUE + CertifiedOnly = TRUE +INVARIANTS NoRegression CertifiedCoverage OnlySuffix diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg new file mode 100644 index 0000000000..8ff050bb89 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_ack.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = FALSE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg new file mode 100644 index 0000000000..c9ebaae853 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_early_close.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = FALSE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg new file mode 100644 index 0000000000..2ea4b4a0da --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_readiness.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = FALSE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg b/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg new file mode 100644 index 0000000000..d67850d71a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_red_retention.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = FALSE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/cfg/R293_review_safe.cfg b/seaweed-block/docs/spec/cfg/R293_review_safe.cfg new file mode 100644 index 0000000000..ba56fd7d5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/R293_review_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS RetireSettled = TRUE + WaitForFrames = TRUE + GuardActive = TRUE + RestoreAck = TRUE +INVARIANTS NoEarlyRetirement NoSettledHistory ReadyRequiresIdle AckRestoresProgress diff --git a/seaweed-block/docs/spec/run.sh b/seaweed-block/docs/spec/run.sh index 05391d8a5e..06c7e844f3 100755 --- a/seaweed-block/docs/spec/run.sh +++ b/seaweed-block/docs/spec/run.sh @@ -25,6 +25,9 @@ case $cfg in S4_*) spec=CutCapture ;; S5_*) spec=ControlPlane ;; S6_*) spec=ReplicationFailover ;; + R293_review_*) spec=ReplicaReviewGuards ;; + R293_prefix_*) spec=ReplicaPrefixFloor ;; + R292_*) spec=ReplicaApplyOrder ;; S9b_*) spec=RetentionGCMulti ;; S9_*) spec=RetentionGCTiming ;; *) echo "run.sh: no spec for config '$cfg'" >&2; exit 2 ;;