From c24f9913b7fb2469f712ec45c83012ca00cef5bd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:02:51 -0800 Subject: [PATCH 01/29] test(master): a creating volume runs no fencing round on the supported gate (red) Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creation_phase_test.go | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 seaweed-block/core/host/master/creation_phase_test.go diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go new file mode 100644 index 0000000000..74266e4dfa --- /dev/null +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -0,0 +1,92 @@ +package master + +import ( + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// supportedCreatingTick ingests r1 (as given) and two ready replicas, checks +// the volume takes the SUPPORTED gate, and runs one product tick. +func supportedCreatingTick(t *testing.T, h *Host, r1 rf3Slot) { + t.Helper() + ingestRF3Incarnations(t, h, r1, readySlot("r2-a"), readySlot("r3-a")) + topo, ok := acceptedTopologyFromPlacementIntents(h.Lifecycle().Placements.ListPlacements()) + if !ok { + t.Fatal("no accepted topology from placements") + } + build := authority.BuildSnapshot(h.obs.Store().Snapshot(), topo, h.Publisher()) + if _, unsupported := build.Report.Unsupported["vol-rf3"]; unsupported { + t.Fatalf("vol-rf3 is unsupported (%+v); this test needs the supported gate", build.Report.Unsupported["vol-rf3"]) + } + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatalf("product tick: %v", err) + } +} + +// Creation is its own phase: a volume whose first line has not reached +// Healthy is never subject to a replacement decision, so no fencing round +// runs and no heal moves the line, however ready the replicas are. The +// schedule from the NET fence-heal run on the SUPPORTED gate: an empty new +// volume, r1 awaiting the replica stores (reachable, not primary-ready), +// r2 and r3 turned ready first. +func TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate(t *testing.T) { + for _, c := range []struct { + name string + setup func(t *testing.T, h *Host) + }{ + {"the master still awaits the stores", func(*testing.T, *Host) {}}, + {"the master's wait is over, the primary has not got the stores yet", func(t *testing.T, h *Host) { attestAllStores(t, h) }}, + } { + t.Run(c.name, func(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) + defer closeTestMaster(t, h) + c.setup(t, h) + p := awaitingProbe(t, h, true) + p.mu.Lock() + p.empty = true // a new volume: every end is zero + p.mu.Unlock() + time.Sleep(250 * time.Millisecond) // past the boot grace + awaiting := rf3Slot{incarnation: "r1-a", reachable: true, eligible: true} + supportedCreatingTick(t, h, awaiting) + supportedCreatingTick(t, h, awaiting) + p.mu.Lock() + fences := p.fenceCalls + p.mu.Unlock() + if fences != 0 { + t.Fatalf("%d fencing rounds against a creating volume", fences) + } + expectLineStaysR1(t, h, "a creating volume with ready replicas") + }) + } +} + +// While the master's record still awaits the stores, the volume is creating +// whatever the primary answers: a creating primary that stops answering is +// not replaced either (the volume waits, visibly). +func TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) + defer closeTestMaster(t, h) + if !inCreationWait(h) { + t.Fatal("fixture: the volume is not creating") + } + p := probeOf(t, h) + p.mu.Lock() + p.empty, p.currentUnknown = true, true + p.mu.Unlock() + time.Sleep(250 * time.Millisecond) + for i := 0; i < 2; i++ { + ingestRF3Incarnations(t, h, silent, readySlot("r2-a"), readySlot("r3-a")) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + } + p.mu.Lock() + fences := p.fenceCalls + p.mu.Unlock() + if fences != 0 { + t.Fatalf("%d fencing rounds against a creating volume with a silent primary", fences) + } + expectLineStaysR1(t, h, "a creating volume whose primary is silent") +} From 1f13ab3bb0c0760d30cbffdbc48ca3f52d9f8b5e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:04:20 -0800 Subject: [PATCH 02/29] fix(master): creation is its own phase: no replacement decision for a creating volume A volume whose first line has not reached Healthy is never subject to a replacement decision: no reassign, no fencing round, no heal at a higher epoch. One predicate, checked first in both gates and in the operator's move: the master's record still awaits a replica store, or the current primary's own answer says its assignment at this line's epoch awaits them. The creation-wait excuse that judged such a primary ready (and so let the supported gate fence its replicas at e+1 and heal the primary at e+1 before epoch 1 was ever healthy) collapses into it. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/planned_move.go | 11 +++ .../core/host/master/product_loop.go | 80 +++++++++++++++---- 2 files changed, 76 insertions(+), 15 deletions(-) diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index 88469beda2..b171f1c6b8 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -43,6 +43,11 @@ func plannedMoveAllowed(ackProfile string, replicas int) error { return fmt.Errorf("planned move: unknown ack profile %q", ackProfile) } +// ErrMoveWhileCreating: the volume is still creating (its replica stores +// are not all attested, or its primary still awaits them); no primary +// change is decided before its first line is healthy. +var ErrMoveWhileCreating = errors.New("move: the volume is still creating (replica stores not yet attested); no primary change until its first line is healthy") + // ackProfiled is a promotion evidence provider that knows the ack profile. type ackProfiled interface{ AckProfile() string } @@ -52,6 +57,9 @@ func (p *roundEvidenceProvider) AckProfile() string { return p.ackProfile } // planned move to target: the guard, then a probe round of the target, which // must answer ready; its evidence goes on the line (kind PROMOTION). func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvidence, error) { + if h.creatingByRecord(volumeID) { + return adapter.PrimaryEvidence{}, ErrMoveWhileCreating + } h.promotionMu.RLock() prober := h.promotionProber h.promotionMu.RUnlock() @@ -136,6 +144,9 @@ func (h *Host) fencedMoveEvidence(volumeID, target, profile string, slots []life if err != nil { return adapter.PrimaryEvidence{}, fmt.Errorf("fenced move: probe round: %w", err) } + if creatingByAnswer(plain, current) { + return adapter.PrimaryEvidence{}, ErrMoveWhileCreating + } if plain.AckProfile == "" { plain.AckProfile = profile } diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index e82a8ae67b..14a4b9fc14 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -25,14 +25,14 @@ type LifecycleProductTickResult struct { } type PromotionCandidateEvidence struct { - ReplicaID string - Ready bool + ReplicaID string + Ready bool // AwaitingReplicaStoresEpoch: the primary answered not ready only because // its assignment at this epoch still awaits replica stores (its own // report); 0: not awaiting. AwaitingReplicaStoresEpoch uint64 - DurableLSN uint64 - ProbeAddr string + DurableLSN uint64 + ProbeAddr string // LastDataEpoch and LastDataFirstLSN are the candidate's epoch-table row // at DurableLSN (zero: no table, or no row): the promotion line carries // them, and the target adopts only if its own row at that LSN is the same. @@ -252,6 +252,13 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, if currentIdx < 0 { continue } + // Creation is its own phase: no replacement decision of any kind + // (no reassign, no fencing round, no heal at a higher epoch) for a + // volume whose master record still awaits its replica stores. + if h.creatingByRecord(vol.VolumeID) { + h.holdCreating(vol, "the master's record awaits replica stores") + continue + } currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex) // A fencing round fenced survivors above this line and nothing was // published: they refuse the primary at its epoch (and may no longer @@ -277,6 +284,13 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, } probeCount++ result, ok := h.probePromotionCandidatesCurrent(vol.VolumeID, vol.Authority, candidates) + // The same phase by the primary's own answer: its assignment at + // this line's epoch still awaits the stores (the master's wait may + // be over while the re-sent assignment has not arrived). + if ok && creatingByAnswer(result, vol.Authority) { + h.holdCreating(vol, "the primary's answer awaits replica stores") + continue + } allowed := promotionAllowedReplicas(result, ok, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates)) // Replacing the primary (it is not acceptable, or answered not // ready): the decision is read from a fencing round, never from the @@ -529,6 +543,10 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac // and every start counts toward flap history (#128). The // promotion rules below are unchanged. h.recordCurrentBootFact(placement.VolumeID) + if h.creatingByRecord(placement.VolumeID) { + h.recordVolumeWaitingEvent(placement.VolumeID, ops.ReasonAwaitingReplicaAttestations, "creating: no replacement decision until the replica stores are attested") + continue + } // A fencing round fenced survivors above this line and nothing was // published (e.g. the operator's refused failover): continue the // line's own primary at e+1 when it is back and answers ready, @@ -563,6 +581,10 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac } probeCount++ result, probeOK := h.probePromotionCandidatesCurrent(vol.VolumeID, current, candidates) + if probeOK && creatingByAnswer(result, current) { + h.recordVolumeWaitingEvent(vol.VolumeID, ops.ReasonAwaitingReplicaAttestations, "creating: the primary's answer awaits replica stores; no replacement decision") + continue + } allowed := promotionAllowedReplicas(result, probeOK, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates)) if probeOK { h.log.Printf("blockmaster: promotion gate unsupported volume=%s current=%s reasons=%v current_known=%t current_ready=%t ack_profile=%s required_lsn=%d candidates=%v allowed=%v", @@ -820,17 +842,10 @@ func (h *Host) probePromotionCandidatesCurrent(volumeID string, current authorit return result, ok } after, afterOK := h.freshCurrentSlot(volumeID, current.ReplicaID) - // A new volume's primary serves nothing until its assignment carries - // every replica's store (the creation wait), and it says so in its - // answer. That not-ready answer is the wait, not a failure: the primary - // is judged ready for this decision, but only while its own fresh slot is - // acceptable. One that is unreachable, ineligible (an unhealthy - // heartbeat) or withdrawn is replaced as for an established volume. The - // primary owns this fact; the master keeps no state for it. - if result.CurrentKnown && current.Epoch != 0 && result.Current.AwaitingReplicaStoresEpoch == current.Epoch && - afterOK && after.Reachable && after.Eligible && !after.Withdrawn { - h.log.Printf("blockmaster: promotion gate volume=%s current=%s not ready, awaiting replica stores (its own answer); judged ready", volumeID, current.ReplicaID) - result.Current.Ready = true + // A primary that answers it awaits replica stores is in the creation + // phase: the gates hold the volume on that answer (creatingByAnswer), + // so it is returned as it is. + if result.CurrentKnown && current.Epoch != 0 && result.Current.AwaitingReplicaStoresEpoch == current.Epoch { return result, ok } if !afterOK || !after.ReadyForPrimary || !after.Reachable || !after.Eligible || after.Withdrawn { @@ -1082,3 +1097,38 @@ func (h *Host) freshCurrentSlot(volumeID, replicaID string) (authority.ReplicaCa } return h.obs.Store().Snapshot().FreshSlotCandidate(volumeID, replicaID) } + +// creatingByRecord: the master's own durable record of the volume still +// awaits a replica store (the creation phase), whatever its primary +// answers or whether it answers at all. +func (h *Host) creatingByRecord(volumeID string) bool { + if h.attest == nil { + return false + } + waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) + return waiting > 0 +} + +// creatingByAnswer: the current primary answered that its assignment at this +// line's epoch still awaits the replica stores (the master's wait may be +// over while the re-sent assignment has not arrived). +func creatingByAnswer(result PromotionProbeResult, current authority.AuthorityBasis) bool { + return result.CurrentKnown && current.Epoch != 0 && result.Current.AwaitingReplicaStoresEpoch == current.Epoch +} + +// holdCreating keeps a creating volume out of every replacement decision: +// no candidate is enabled (the controller reassigns only to an enabled +// slot), and the wait is visible. +func (h *Host) holdCreating(vol *authority.VolumeTopologySnapshot, why string) { + for si := range vol.Slots { + slot := &vol.Slots[si] + if slot.ReplicaID == vol.Authority.ReplicaID { + continue + } + slot.ReadyForPrimary = false + slot.PromotionEvidence = adapter.PrimaryEvidence{} + slot.PlannedMoveAllowed = false + } + h.log.Printf("blockmaster: promotion gate volume=%s current=%s creating (%s): no replacement decision", vol.VolumeID, vol.Authority.ReplicaID, why) + h.recordVolumeWaitingEvent(vol.VolumeID, ops.ReasonAwaitingReplicaAttestations, "creating: "+why+"; no replacement decision") +} From 291bc47b530c489a384ccfcfc90ad0197bce9ce1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:17:06 -0800 Subject: [PATCH 03/29] test(master): fixtures of established volumes record their replica stores Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creation_phase_test.go | 27 +++++++++++++++++++ .../core/host/master/event_ring_test.go | 1 + .../core/host/master/failback_runtime_test.go | 1 + .../host/master/manual_failover_fence_test.go | 2 ++ .../core/host/master/product_loop_test.go | 12 +++++++++ .../promotion_frontier_coverage_test.go | 2 ++ ...motion_missing_frontier_regression_test.go | 1 + .../master/recovery_watchdog_master_test.go | 1 + .../host/master/workspace_restore_test.go | 1 + 9 files changed, 48 insertions(+) diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index 74266e4dfa..748547be22 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/storage" ) // supportedCreatingTick ingests r1 (as given) and two ready replicas, checks @@ -90,3 +91,29 @@ func TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent(t *testing.T) { } expectLineStaysR1(t, h, "a creating volume whose primary is silent") } + +// establishVolume records the current primary's attestation of every +// replica's store, as a primary's first heartbeat after its bind does, so +// the volume has left the creation phase (an established volume). Fixtures +// that exercise promotion on an established volume call it after the first +// line is published. +func establishVolume(t *testing.T, h *Host, volumeID string) { + t.Helper() + line := waitAuthorityLine(t, h.Publisher(), volumeID) + p, ok := h.Lifecycle().Placements.GetPlacement(volumeID) + if !ok { + t.Fatalf("establish %s: no placement", volumeID) + } + stores := map[string]storage.StoreID{} + for _, s := range p.Slots { + stores[s.ReplicaID] = storeOf(s.ReplicaID) + } + published, _ := h.Publisher().PublishedAuthorityLine(volumeID) + server := h.workspaceLineOwner(published, volumeID, line.ReplicaID, line.Epoch) + if err := h.ingestStoreAttestation(server, attestation(volumeID, line.ReplicaID, line.Epoch, stores)); err != nil { + t.Fatalf("establish %s: %v", volumeID, err) + } + if h.creatingByRecord(volumeID) { + t.Fatalf("establish %s: still creating after the attestation (line %+v, server %q)", volumeID, line, server) + } +} diff --git a/seaweed-block/core/host/master/event_ring_test.go b/seaweed-block/core/host/master/event_ring_test.go index 81fc0454db..2e81b8bbc1 100644 --- a/seaweed-block/core/host/master/event_ring_test.go +++ b/seaweed-block/core/host/master/event_ring_test.go @@ -48,6 +48,7 @@ func TestMasterTimeline_RecordsPromotionCandidateEvaluation(t *testing.T) { t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "pvc-a") + establishVolume(t, h, "pvc-a") h.SetPromotionEvidenceProvider(staticPromotionProbe{ result: PromotionProbeResult{ AckProfile: "sync-quorum", diff --git a/seaweed-block/core/host/master/failback_runtime_test.go b/seaweed-block/core/host/master/failback_runtime_test.go index 6197c4f3c6..9ffed42ef4 100644 --- a/seaweed-block/core/host/master/failback_runtime_test.go +++ b/seaweed-block/core/host/master/failback_runtime_test.go @@ -25,6 +25,7 @@ func TestHostFailbackAuthorityRuntimeUsesLivePublisher(t *testing.T) { t.Fatalf("product tick: %v", err) } current := waitAuthorityLine(t, h.Publisher(), "vol-a") + establishVolume(t, h, "vol-a") if current.ReplicaID != "r2" { t.Fatalf("current line=%+v want r2", current) } diff --git a/seaweed-block/core/host/master/manual_failover_fence_test.go b/seaweed-block/core/host/master/manual_failover_fence_test.go index fe68846297..03047dd9b8 100644 --- a/seaweed-block/core/host/master/manual_failover_fence_test.go +++ b/seaweed-block/core/host/master/manual_failover_fence_test.go @@ -43,6 +43,7 @@ func rf3LineOnR1With(t *testing.T, h *Host) (*Host, authority.AuthorityBasis) { if line.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", line) } + establishVolume(t, h, "vol-rf3") return h, line } @@ -182,6 +183,7 @@ func rf2LineOnR1(t *testing.T, profile string) (*Host, authority.AuthorityBasis) if line.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", line) } + establishVolume(t, h, "vol-rf2") return h, line } diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index 61e12135e9..e020e2060b 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -117,6 +117,7 @@ func TestMountedFailover_ProductLoopRF2UsesAuthorityControllerForFailover(t *tes t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2") + establishVolume(t, h, "vol-rf2") if initial.ReplicaID != "r1" || initial.Epoch != 1 || initial.EndpointVersion != 1 { t.Fatalf("initial line=%+v want r1@1/1", initial) } @@ -194,6 +195,7 @@ func TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe( t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -239,6 +241,7 @@ func TestMountedFailover_ProductLoopRF3BlocksHealthyCurrentRebalanceWithoutProbe } } initialA := waitAuthorityLine(t, h.Publisher(), "vol-rf3-a") + establishVolume(t, h, "vol-rf3-a") initialB := waitAuthorityLine(t, h.Publisher(), "vol-rf3-b") if initialA.ReplicaID != "r1" || initialB.ReplicaID != "r1" { t.Fatalf("initial lines=%+v %+v want both r1", initialA, initialB) @@ -288,6 +291,7 @@ func TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe(t * t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -328,6 +332,7 @@ func TestMountedFailover_ProductLoopRF3PrefersHighestDurableLSNAboveRequired(t * t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -367,6 +372,7 @@ func TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurab t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -406,6 +412,7 @@ func TestMountedFailover_ProductLoopRF3BestEffortUnknownRequiredLSNCanSelectHigh t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -493,6 +500,7 @@ func TestMountedFailover_ProductLoopRF3DoesNotPromoteWhenCurrentProbeIsReady(t * t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") ingestRF3Observation(t, h, true, true, true) result, err := h.RunLifecycleProductTick() if err != nil { @@ -534,6 +542,7 @@ func TestMountedFailover_ProductLoopRF3ProbeCanAuthorizeStaleHeartbeatReadiness( t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -576,6 +585,7 @@ func TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing(t * t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } @@ -621,6 +631,7 @@ func TestMountedFailover_ProductLoopRF3RejectsBestEffortProbeForHA(t *testing.T) t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") ingestRF3Observation(t, h, false, true, true) result, err := h.RunLifecycleProductTick() @@ -661,6 +672,7 @@ func TestMountedFailover_ProductLoopRF3UnknownProbeCandidateCountsBlocked(t *tes t.Fatalf("initial product tick: %v", err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") ingestRF3Observation(t, h, false, true, true) result, err := h.RunLifecycleProductTick() diff --git a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go index c2acaa4341..727bd9545d 100644 --- a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go +++ b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go @@ -198,6 +198,7 @@ func TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused(t *te if initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3"); initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } + establishVolume(t, h, "vol-rf3") // Previous tick: both survivors probed ready, current primary ready. probe.set(PromotionProbeResult{ @@ -281,6 +282,7 @@ func TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate(t *testing.T) { return } failover := waitAuthorityReplica(t, h.Publisher(), "vol-rf2", "r2") + establishVolume(t, h, "vol-rf2") if failover.Epoch != 2 { t.Fatalf("failover line=%+v want r2@2", failover) } diff --git a/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go b/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go index 2ae248a535..1e9419869d 100644 --- a/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go +++ b/seaweed-block/core/host/master/promotion_missing_frontier_regression_test.go @@ -36,6 +36,7 @@ func TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion(t *testing.T) { t.Fatal(err) } initial := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") if initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v", initial) } diff --git a/seaweed-block/core/host/master/recovery_watchdog_master_test.go b/seaweed-block/core/host/master/recovery_watchdog_master_test.go index 95d15246dc..d0964a72ac 100644 --- a/seaweed-block/core/host/master/recovery_watchdog_master_test.go +++ b/seaweed-block/core/host/master/recovery_watchdog_master_test.go @@ -68,6 +68,7 @@ func watchdogMaster(t *testing.T) (*Host, *services) { if line := waitAuthorityLine(t, h.Publisher(), "vol-rf3"); line.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", line) } + establishVolume(t, h, "vol-rf3") return h, svc } diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go index 09cacad702..23ec4b0f5d 100644 --- a/seaweed-block/core/host/master/workspace_restore_test.go +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -50,6 +50,7 @@ func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { t.Fatal(err) } oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + establishVolume(t, m, "vol-a") fixture := testutil.NewLayoutFixture(t, "vol-a", 64, 4) var gets atomic.Uint64 readHead := func() layout.Head { From 3d6b0031acbda4f501f1ba0d66300af44208f56e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:23:38 -0800 Subject: [PATCH 04/29] test(master): creation-wait tests follow the creation phase; remaining fixtures record their stores A creating volume is no longer replaced when its primary is not ready for another reason, answers a stale epoch, or has an unacceptable slot: no promotion decision is even probed (the owner's ruling and its model). Co-Authored-By: Claude Opus 5.5 --- .../host/master/creating_primary_gate_test.go | 79 +++++++++++-------- .../core/host/master/failback_runtime_test.go | 3 + .../core/host/master/product_loop_test.go | 1 + .../promotion_frontier_coverage_test.go | 1 + .../master/workspace_binding_review_test.go | 1 + 5 files changed, 54 insertions(+), 31 deletions(-) diff --git a/seaweed-block/core/host/master/creating_primary_gate_test.go b/seaweed-block/core/host/master/creating_primary_gate_test.go index cdadc48984..9697a23dd6 100644 --- a/seaweed-block/core/host/master/creating_primary_gate_test.go +++ b/seaweed-block/core/host/master/creating_primary_gate_test.go @@ -41,9 +41,9 @@ func TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady(t *testing.T) { defer closeTestMaster(t, h) awaitingProbe(t, h, true) time.Sleep(250 * time.Millisecond) // past the boot grace - unsupportedTick(t, h, readySlot("r1-a")) + creatingTick(t, h, readySlot("r1-a")) expectLineStaysR1(t, h, "a primary awaiting replica stores answered not ready") - unsupportedTick(t, h, readySlot("r1-a")) + creatingTick(t, h, readySlot("r1-a")) expectLineStaysR1(t, h, "still awaiting on the next tick") } @@ -78,9 +78,11 @@ func TestMasterRestartInTheGapDoesNotReassign(t *testing.T) { expectLineStaysR1(t, h2, "restarted master, primary still awaiting the re-sent stores") } -// A primary that is not ready for another reason (it does not say it awaits -// replica stores) is replaced as before, also on a new volume. -func TestPrimaryNotReadyForAnotherReasonIsReplaced(t *testing.T) { +// Creation is its own phase (decided on the master's record): a creating +// volume's primary is not replaced even when it is not ready for another +// reason (it does not say it awaits replica stores). No decision is made at +// all: the gate does not even probe. +func TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced(t *testing.T) { h := newBootGraceMasterCreating(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) defer closeTestMaster(t, h) awaitingProbe(t, h, false) @@ -88,14 +90,13 @@ func TestPrimaryNotReadyForAnotherReasonIsReplaced(t *testing.T) { t.Fatal("fixture: the new volume is not in its creation wait") } time.Sleep(250 * time.Millisecond) // past the boot grace - unsupportedTick(t, h, readySlot("r1-a")) - expectFailoverToR2(t, h, "a primary not ready without awaiting replica stores") + creatingTick(t, h, readySlot("r1-a")) + expectLineStaysR1(t, h, "a primary not ready without awaiting replica stores") } -// The answer names its line: one that says it awaits replica stores for -// another epoch (a stale answer) excuses nothing, and the primary is -// replaced as one not ready for another reason. -func TestAwaitingAnswerForAnotherLineExcusesNothing(t *testing.T) { +// The phase is the master's record, not the answer: a stale awaiting answer +// (naming another epoch) changes nothing while the record still awaits. +func TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced(t *testing.T) { h := newBootGraceMasterCreating(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) defer closeTestMaster(t, h) p := probeOf(t, h) @@ -103,21 +104,22 @@ func TestAwaitingAnswerForAnotherLineExcusesNothing(t *testing.T) { p.awaitingEpoch = waitAuthorityLine(t, h.Publisher(), "vol-rf3").Epoch + 1 p.mu.Unlock() time.Sleep(250 * time.Millisecond) // past the boot grace - unsupportedTick(t, h, readySlot("r1-a")) - expectFailoverToR2(t, h, "an awaiting answer naming another line") + creatingTick(t, h, readySlot("r1-a")) + expectLineStaysR1(t, h, "an awaiting answer naming another line") } -// The answer never shelters a failed primary: one whose own fresh slot is -// not acceptable (an unhealthy heartbeat makes it ineligible) is replaced -// through the fencing round, as for an established volume. -func TestPrimaryAwaitingReplicaStoresIsReplacedWhenItsSlotIsNotAcceptable(t *testing.T) { +// A creating primary whose own slot is not acceptable (ineligible) is not +// replaced either: a creating volume that is really broken stays in its +// visible wait, and the operator deletes and recreates it (it served +// nothing). +func TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced(t *testing.T) { h := newBootGraceMasterCreating(t, Config{}) defer closeTestMaster(t, h) awaitingProbe(t, h, true) ineligible := restarting ineligible.eligible = false - unsupportedTick(t, h, ineligible) - expectFailoverToR2(t, h, "an ineligible primary awaiting replica stores") + creatingTick(t, h, ineligible) + expectLineStaysR1(t, h, "an ineligible primary awaiting replica stores") } // attestSomeStores records r1 and r2 but not r3: the volume is still in its @@ -133,27 +135,26 @@ func attestSomeStores(t *testing.T, h *Host) { } } -// Partial attestation (still creating), the primary answering that it awaits -// replica stores: a primary whose own slot is not acceptable is replaced; -// one that does not answer the probe is unknown and never replaced. +// Partial attestation (still creating): whatever the primary's state +// (ineligible, expired, unanswered), no replacement decision is made. func TestCreationWaitPartialAttestationControls(t *testing.T) { - t.Run("unhealthy primary (ineligible) is replaced", func(t *testing.T) { + t.Run("unhealthy primary (ineligible) is not replaced", func(t *testing.T) { h := newBootGraceMasterCreating(t, Config{}) defer closeTestMaster(t, h) attestSomeStores(t, h) awaitingProbe(t, h, true) ineligible := restarting ineligible.eligible = false - unsupportedTick(t, h, ineligible) - expectFailoverToR2(t, h, "an unhealthy primary inside the creation wait") + creatingTick(t, h, ineligible) + expectLineStaysR1(t, h, "an unhealthy primary inside the creation wait") }) - t.Run("expired primary (no fresh slot) is replaced", func(t *testing.T) { + t.Run("expired primary (no fresh slot) is not replaced", func(t *testing.T) { h := newBootGraceMasterCreating(t, Config{}) defer closeTestMaster(t, h) attestSomeStores(t, h) awaitingProbe(t, h, true) - unsupportedTick(t, h, silent) - expectFailoverToR2(t, h, "an expired primary inside the creation wait") + creatingTick(t, h, silent) + expectLineStaysR1(t, h, "an expired primary inside the creation wait") }) t.Run("unanswered primary is never replaced", func(t *testing.T) { h := newBootGraceMasterCreating(t, Config{}) @@ -163,7 +164,7 @@ func TestCreationWaitPartialAttestationControls(t *testing.T) { p.mu.Lock() p.currentUnknown = true p.mu.Unlock() - unsupportedTick(t, h, readySlot("r1-a")) + creatingTick(t, h, readySlot("r1-a")) expectLineStaysR1(t, h, "an unanswered primary inside the creation wait") }) } @@ -199,9 +200,9 @@ func TestCreationWaitEmptyVolumeOutcomes(t *testing.T) { p.mu.Lock() p.empty, p.currentUnknown = true, c.unknown p.mu.Unlock() - unsupportedTick(t, h, c.r1) + creatingTick(t, h, c.r1) if c.promoted { - expectFailoverToR2(t, h, c.name) + expectLineStaysR1(t, h, c.name) return } expectLineStaysR1(t, h, c.name) @@ -211,3 +212,19 @@ func TestCreationWaitEmptyVolumeOutcomes(t *testing.T) { }) } } + +// creatingTick ingests fresh r1/r2 facts (node-c silent), runs one product +// tick on the unsupported-volume path, and requires that no promotion +// decision was even probed: a creating volume is outside every replacement +// decision. +func creatingTick(t *testing.T, h *Host, r1 rf3Slot) { + t.Helper() + ingestRF3Incarnations(t, h, r1, readySlot("r2-a"), silent) + res, err := h.RunLifecycleProductTick() + if err != nil { + t.Fatalf("product tick: %v", err) + } + if res.PromotionProbes != 0 { + t.Fatalf("product tick %+v: a creating volume was probed for a promotion decision", res) + } +} diff --git a/seaweed-block/core/host/master/failback_runtime_test.go b/seaweed-block/core/host/master/failback_runtime_test.go index 9ffed42ef4..2fdd03dabd 100644 --- a/seaweed-block/core/host/master/failback_runtime_test.go +++ b/seaweed-block/core/host/master/failback_runtime_test.go @@ -74,6 +74,7 @@ func TestHostFrontendPublicationRuntimeHTTPConfirmsPostFailbackAuthorityLine(t * t.Fatalf("product tick: %v", err) } current := waitAuthorityLine(t, h.Publisher(), "vol-a") + establishVolume(t, h, "vol-a") if _, err := h.FailbackAuthorityRuntime().ExecuteFailback(context.Background(), authority.FailbackRuntimeRequest{ VolumeID: "vol-a", ReplicaID: "r1", @@ -205,6 +206,7 @@ func TestFailbackServiceEnabledUsesHostRuntime(t *testing.T) { t.Fatalf("product tick: %v", err) } current := waitAuthorityLine(t, h.Publisher(), "vol-a") + establishVolume(t, h, "vol-a") resp, err := newServices(h).ExecuteFailback(context.Background(), &control.FailbackRequest{ VolumeId: "vol-a", @@ -248,6 +250,7 @@ func TestFailbackExecutorGRPCRuntimeUsesRealMasterService(t *testing.T) { t.Fatalf("product tick: %v", err) } current := waitAuthorityLine(t, h.Publisher(), "vol-a") + establishVolume(t, h, "vol-a") if current.ReplicaID != "r2" { t.Fatalf("current line=%+v want r2", current) } diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index e020e2060b..d811603c93 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -243,6 +243,7 @@ func TestMountedFailover_ProductLoopRF3BlocksHealthyCurrentRebalanceWithoutProbe initialA := waitAuthorityLine(t, h.Publisher(), "vol-rf3-a") establishVolume(t, h, "vol-rf3-a") initialB := waitAuthorityLine(t, h.Publisher(), "vol-rf3-b") + establishVolume(t, h, "vol-rf3-b") if initialA.ReplicaID != "r1" || initialB.ReplicaID != "r1" { t.Fatalf("initial lines=%+v %+v want both r1", initialA, initialB) } diff --git a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go index 727bd9545d..e4e2050a1b 100644 --- a/seaweed-block/core/host/master/promotion_frontier_coverage_test.go +++ b/seaweed-block/core/host/master/promotion_frontier_coverage_test.go @@ -266,6 +266,7 @@ func TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate(t *testing.T) { if initial := waitAuthorityLine(t, h.Publisher(), "vol-rf2"); initial.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", initial) } + establishVolume(t, h, "vol-rf2") ingestRF2Observation(t, h, false, true) result, err := h.RunLifecycleProductTick() if err != nil { diff --git a/seaweed-block/core/host/master/workspace_binding_review_test.go b/seaweed-block/core/host/master/workspace_binding_review_test.go index 1bcb1e5c53..8bcdb786e6 100644 --- a/seaweed-block/core/host/master/workspace_binding_review_test.go +++ b/seaweed-block/core/host/master/workspace_binding_review_test.go @@ -314,6 +314,7 @@ func TestWorkspaceBindingRemoteReadDoesNotBlockAck(t *testing.T) { t.Fatal(e) } waitAuthorityLine(t, h.Publisher(), "vol-rf3") + establishVolume(t, h, "vol-rf3") ingestRF3Observation(t, h, false, true, true) h.SetPromotionEvidenceProvider(reviewHeldPromotion{arrived, release}) launch(func() error { _, e := h.RunLifecycleProductTick(); return e }) From 3a36ddcf5b7645fb261820a1170d959475766a07 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:29:12 -0800 Subject: [PATCH 05/29] docs: INV-PROMOTE-CREATION-WAIT-001 is the creation phase, decided on the master's record Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 95f0b0894f..91d378d031 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -955,7 +955,7 @@ Notes: | `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-CREATION-WAIT-001` | A primary that answers the promotion probe not ready is excused from replacement only by its own answer that its assignment at the current line's epoch awaits replica stores (read before its readiness), and only while its own fresh slot is acceptable; the master keeps no state for it. | GUARD (the promotion models have no bring-up) | `core/host/master/product_loop.go` `probePromotionCandidatesCurrent`; `core/host/master/probe_round.go`; `core/host/volume/probe_round.go` `probeAnswer`; `core/host/volume/workspace_startup.go` `awaitingStoresEpoch` | `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestPrimaryNotReadyForAnotherReasonIsReplaced`, `TestAwaitingAnswerForAnotherLineExcusesNothing` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | +| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase: while the master's durable record awaits a replica store, or the primary answers that its assignment at the line's epoch awaits them, no replacement decision is made (reassign, fencing round, higher-epoch heal, operator or planned move, rebalance); checked first. | CreatePromo model (VolumeCreate x Promotion) | `core/host/master/product_loop.go` `creatingByRecord`, `creatingByAnswer`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (no fresh, reachable heartbeat; any replica count); a reachable RF3 `sync_quorum` primary's move stays refused (it needs a seal) and `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`, `TestManualFailoverRF3ReachablePrimaryIsRefused`, `TestManualFailoverAndThePromotionLoopPublishOneLine`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | From aa66ad56a22d40841cc2c6a3a50f1d6d7e9a172a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:30:41 -0800 Subject: [PATCH 06/29] test(master): creation phase: operator entry, master restart, delete of a stuck volume Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creation_phase_test.go | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index 748547be22..f1dc023c32 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -117,3 +118,92 @@ func establishVolume(t *testing.T, h *Host, volumeID string) { t.Fatalf("establish %s: still creating after the attestation (line %+v, server %q)", volumeID, line, server) } } + +// The operator's entries read the same phase (model row +// mut_today_operator_entry): a failover or planned move of a creating volume +// is refused before any probe or fencing round, whatever the answers say. +func TestCreatingVolumeRefusesTheOperatorsMove(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{}) + defer closeTestMaster(t, h) + p := probeOf(t, h) + p.mu.Lock() + p.currentReady = true // a perfect answer: ready, nothing awaited + p.mu.Unlock() + if !inCreationWait(h) { + t.Fatal("fixture: the volume is not creating") + } + if _, err := h.plannedMoveEvidence("vol-rf3", "r2"); err != ErrMoveWhileCreating { + t.Fatalf("err=%v; want ErrMoveWhileCreating", err) + } + p.mu.Lock() + fences := p.fenceCalls + p.mu.Unlock() + if fences != 0 { + t.Fatalf("%d fencing rounds for a refused move of a creating volume", fences) + } +} + +// The phase is the master's durable record, not memory (model row +// mut_mark_in_memory): a master restarted while a volume creates still +// treats it as creating, and one restarted after the stores were attested +// still fails a dead primary over (the mark is never lost). +func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { + for _, established := range []bool{false, true} { + t.Run(map[bool]string{false: "still creating", true: "established"}[established], func(t *testing.T) { + cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), + ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}} + h := newBootGraceMasterCreating(t, cfg) + if established { + attestAllStores(t, h) + } + closeTestMaster(t, h) + + cfg.Listen = "127.0.0.1:0" + cfg.ControllerConfig.ExpectedSlotsPerVolume = 3 + cfg.Freshness.FreshnessWindow = testFreshness + cfg.Freshness.PendingGrace = time.Millisecond + h2, err := New(cfg) + if err != nil { + t.Fatalf("master restart: %v", err) + } + h2.Start() + defer closeTestMaster(t, h2) + p := &switchProbe{} // r1 not ready (not awaiting), r2 ready with evidence + h2.SetPromotionEvidenceProvider(p) + if got := inCreationWait(h2); got == established { + t.Fatalf("after the restart creating=%t; want %t", got, !established) + } + time.Sleep(250 * time.Millisecond) // past the boot grace + ineligible := restarting + ineligible.eligible = false + if established { + unsupportedTick(t, h2, ineligible) + expectFailoverToR2(t, h2, "an established volume's unhealthy primary after a master restart") + return + } + creatingTick(t, h2, ineligible) + expectLineStaysR1(t, h2, "a creating volume after a master restart") + }) + } +} + +// A creating volume that is really broken stays in its wait by rule; the +// documented way out is to delete it and create it again, so its delete is +// admitted. +func TestAStuckCreatingVolumeCanBeDeleted(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{}) + defer closeTestMaster(t, h) + if !inCreationWait(h) { + t.Fatal("fixture: the volume is not creating") + } + ineligible := restarting + ineligible.eligible = false + time.Sleep(250 * time.Millisecond) + creatingTick(t, h, ineligible) // stuck: no decision + if _, err := newServices(h).DeleteVolume(t.Context(), &control.DeleteVolumeRequest{VolumeId: "vol-rf3"}); err != nil { + t.Fatalf("delete of a stuck creating volume: %v", err) + } + if _, placed := h.Lifecycle().Placements.GetPlacement("vol-rf3"); placed { + t.Fatal("the deleted volume keeps its placement") + } +} From 5364850447a751af13e61b50d919e6321c321b36 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:31:15 -0800 Subject: [PATCH 07/29] test(master): drop the delete-of-a-stuck-creating-volume test pending a ruling (the delete is refused today) Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creation_phase_test.go | 22 ------------------- 1 file changed, 22 deletions(-) diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index f1dc023c32..8a1adf18a0 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -5,7 +5,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/authority" - "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -186,24 +185,3 @@ func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { }) } } - -// A creating volume that is really broken stays in its wait by rule; the -// documented way out is to delete it and create it again, so its delete is -// admitted. -func TestAStuckCreatingVolumeCanBeDeleted(t *testing.T) { - h := newBootGraceMasterCreating(t, Config{}) - defer closeTestMaster(t, h) - if !inCreationWait(h) { - t.Fatal("fixture: the volume is not creating") - } - ineligible := restarting - ineligible.eligible = false - time.Sleep(250 * time.Millisecond) - creatingTick(t, h, ineligible) // stuck: no decision - if _, err := newServices(h).DeleteVolume(t.Context(), &control.DeleteVolumeRequest{VolumeId: "vol-rf3"}); err != nil { - t.Fatalf("delete of a stuck creating volume: %v", err) - } - if _, placed := h.Lifecycle().Placements.GetPlacement("vol-rf3"); placed { - t.Fatal("the deleted volume keeps its placement") - } -} From 9b1c5c89a1ca73e5de7c7233255180e373ea6c28 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 20:39:38 -0800 Subject: [PATCH 08/29] refactor(master): one inCreationPhase decision every replacement entry calls first Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creation_phase_test.go | 2 +- .../core/host/master/planned_move.go | 4 +- .../core/host/master/product_loop.go | 69 ++++++++++++------- seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 48 insertions(+), 29 deletions(-) diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index 8a1adf18a0..30e96492ed 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -113,7 +113,7 @@ func establishVolume(t *testing.T, h *Host, volumeID string) { if err := h.ingestStoreAttestation(server, attestation(volumeID, line.ReplicaID, line.Epoch, stores)); err != nil { t.Fatalf("establish %s: %v", volumeID, err) } - if h.creatingByRecord(volumeID) { + if line, _ := h.Publisher().VolumeAuthorityLine(volumeID); h.inCreationPhase(volumeID, line, nil) != "" { t.Fatalf("establish %s: still creating after the attestation (line %+v, server %q)", volumeID, line, server) } } diff --git a/seaweed-block/core/host/master/planned_move.go b/seaweed-block/core/host/master/planned_move.go index b171f1c6b8..24244b27f9 100644 --- a/seaweed-block/core/host/master/planned_move.go +++ b/seaweed-block/core/host/master/planned_move.go @@ -57,7 +57,7 @@ func (p *roundEvidenceProvider) AckProfile() string { return p.ackProfile } // planned move to target: the guard, then a probe round of the target, which // must answer ready; its evidence goes on the line (kind PROMOTION). func (h *Host) plannedMoveEvidence(volumeID, target string) (adapter.PrimaryEvidence, error) { - if h.creatingByRecord(volumeID) { + if line, ok := h.Publisher().VolumeAuthorityLine(volumeID); ok && h.inCreationPhase(volumeID, line, nil) != "" { return adapter.PrimaryEvidence{}, ErrMoveWhileCreating } h.promotionMu.RLock() @@ -144,7 +144,7 @@ func (h *Host) fencedMoveEvidence(volumeID, target, profile string, slots []life if err != nil { return adapter.PrimaryEvidence{}, fmt.Errorf("fenced move: probe round: %w", err) } - if creatingByAnswer(plain, current) { + if h.inCreationPhase(volumeID, current, &plain) != "" { return adapter.PrimaryEvidence{}, ErrMoveWhileCreating } if plain.AckProfile == "" { diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 14a4b9fc14..9b1203e5b7 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -255,8 +255,8 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, // Creation is its own phase: no replacement decision of any kind // (no reassign, no fencing round, no heal at a higher epoch) for a // volume whose master record still awaits its replica stores. - if h.creatingByRecord(vol.VolumeID) { - h.holdCreating(vol, "the master's record awaits replica stores") + if why := h.inCreationPhase(vol.VolumeID, vol.Authority, nil); why != "" { + h.holdCreating(vol, why) continue } currentAcceptable := candidateAcceptableForPromotionGate(vol.Slots[currentIdx], serverIndex) @@ -287,8 +287,8 @@ func (h *Host) applyPromotionEvidenceGate(snap *authority.ClusterSnapshot) (int, // The same phase by the primary's own answer: its assignment at // this line's epoch still awaits the stores (the master's wait may // be over while the re-sent assignment has not arrived). - if ok && creatingByAnswer(result, vol.Authority) { - h.holdCreating(vol, "the primary's answer awaits replica stores") + if why := h.inCreationPhase(vol.VolumeID, vol.Authority, answerOf(result, ok)); why != "" { + h.holdCreating(vol, why) continue } allowed := promotionAllowedReplicas(result, ok, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates)) @@ -543,9 +543,11 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac // and every start counts toward flap history (#128). The // promotion rules below are unchanged. h.recordCurrentBootFact(placement.VolumeID) - if h.creatingByRecord(placement.VolumeID) { - h.recordVolumeWaitingEvent(placement.VolumeID, ops.ReasonAwaitingReplicaAttestations, "creating: no replacement decision until the replica stores are attested") - continue + if line, ok := h.Publisher().VolumeAuthorityLine(placement.VolumeID); ok { + if why := h.inCreationPhase(placement.VolumeID, line, nil); why != "" { + h.noteCreating(placement.VolumeID, line.ReplicaID, why) + continue + } } // A fencing round fenced survivors above this line and nothing was // published (e.g. the operator's refused failover): continue the @@ -581,8 +583,8 @@ func (h *Host) applyUnsupportedPromotionEvidenceGate(placements []lifecycle.Plac } probeCount++ result, probeOK := h.probePromotionCandidatesCurrent(vol.VolumeID, current, candidates) - if probeOK && creatingByAnswer(result, current) { - h.recordVolumeWaitingEvent(vol.VolumeID, ops.ReasonAwaitingReplicaAttestations, "creating: the primary's answer awaits replica stores; no replacement decision") + if why := h.inCreationPhase(vol.VolumeID, current, answerOf(result, probeOK)); why != "" { + h.noteCreating(vol.VolumeID, current.ReplicaID, why) continue } allowed := promotionAllowedReplicas(result, probeOK, len(candidates), h.freshPromotionPeers(vol.VolumeID, candidates)) @@ -843,7 +845,7 @@ func (h *Host) probePromotionCandidatesCurrent(volumeID string, current authorit } after, afterOK := h.freshCurrentSlot(volumeID, current.ReplicaID) // A primary that answers it awaits replica stores is in the creation - // phase: the gates hold the volume on that answer (creatingByAnswer), + // phase: the gates hold the volume on that answer (inCreationPhase), // so it is returned as it is. if result.CurrentKnown && current.Epoch != 0 && result.Current.AwaitingReplicaStoresEpoch == current.Epoch { return result, ok @@ -1098,22 +1100,34 @@ func (h *Host) freshCurrentSlot(volumeID, replicaID string) (authority.ReplicaCa return h.obs.Store().Snapshot().FreshSlotCandidate(volumeID, replicaID) } -// creatingByRecord: the master's own durable record of the volume still -// awaits a replica store (the creation phase), whatever its primary -// answers or whether it answers at all. -func (h *Host) creatingByRecord(volumeID string) bool { - if h.attest == nil { - return false +// inCreationPhase is the one decision of the creation phase, which every +// replacement entry (both promotion gates, the operator's move and planned +// move, the rebalance through the gate) calls first: it returns why the +// volume is creating, or "" once it is not. Two sources, in order: +// - the master's own durable record still awaits a replica store (every +// initial store attested clears it, durably; no other state); +// - the current primary's own answer, when one was read, says its +// assignment at this line's epoch still awaits the stores (the master's +// wait may be over before the re-sent assignment arrives). The answer +// can only hold a volume, never release one. +func (h *Host) inCreationPhase(volumeID string, current authority.AuthorityBasis, answer *PromotionProbeResult) string { + if h.attest != nil { + if waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)); waiting > 0 { + return "the master's record awaits replica stores" + } } - waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) - return waiting > 0 + if answer != nil && answer.CurrentKnown && current.Epoch != 0 && answer.Current.AwaitingReplicaStoresEpoch == current.Epoch { + return "the primary's answer awaits replica stores" + } + return "" } -// creatingByAnswer: the current primary answered that its assignment at this -// line's epoch still awaits the replica stores (the master's wait may be -// over while the re-sent assignment has not arrived). -func creatingByAnswer(result PromotionProbeResult, current authority.AuthorityBasis) bool { - return result.CurrentKnown && current.Epoch != 0 && result.Current.AwaitingReplicaStoresEpoch == current.Epoch +// answerOf is the probe's answer, or nil when the probe gave none. +func answerOf(result PromotionProbeResult, ok bool) *PromotionProbeResult { + if !ok { + return nil + } + return &result } // holdCreating keeps a creating volume out of every replacement decision: @@ -1129,6 +1143,11 @@ func (h *Host) holdCreating(vol *authority.VolumeTopologySnapshot, why string) { slot.PromotionEvidence = adapter.PrimaryEvidence{} slot.PlannedMoveAllowed = false } - h.log.Printf("blockmaster: promotion gate volume=%s current=%s creating (%s): no replacement decision", vol.VolumeID, vol.Authority.ReplicaID, why) - h.recordVolumeWaitingEvent(vol.VolumeID, ops.ReasonAwaitingReplicaAttestations, "creating: "+why+"; no replacement decision") + h.noteCreating(vol.VolumeID, vol.Authority.ReplicaID, why) +} + +// noteCreating makes the hold of a creating volume visible. +func (h *Host) noteCreating(volumeID, current, why string) { + h.log.Printf("blockmaster: promotion gate volume=%s current=%s creating (%s): no replacement decision", volumeID, current, why) + h.recordVolumeWaitingEvent(volumeID, ops.ReasonAwaitingReplicaAttestations, "creating: "+why+"; no replacement decision") } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 91d378d031..39e6a49e7f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -955,7 +955,7 @@ Notes: | `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase: while the master's durable record awaits a replica store, or the primary answers that its assignment at the line's epoch awaits them, no replacement decision is made (reassign, fencing round, higher-epoch heal, operator or planned move, rebalance); checked first. | CreatePromo model (VolumeCreate x Promotion) | `core/host/master/product_loop.go` `creatingByRecord`, `creatingByAnswer`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | +| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase: while the master's durable record awaits a replica store, or the primary answers that its assignment at the line's epoch awaits them, no replacement decision is made (reassign, fencing round, higher-epoch heal, operator or planned move, rebalance); checked first. | CreatePromo model (VolumeCreate x Promotion) | `core/host/master/product_loop.go` `inCreationPhase`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (no fresh, reachable heartbeat; any replica count); a reachable RF3 `sync_quorum` primary's move stays refused (it needs a seal) and `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`, `TestManualFailoverRF3ReachablePrimaryIsRefused`, `TestManualFailoverAndThePromotionLoopPublishOneLine`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | From 2eb5fbfcab702f8f7f22563e0aae21aa64cb3fcf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:28:41 -0800 Subject: [PATCH 09/29] fix(master): creation ends at the primary's first ready answer at its first line Not at the last store attestation: a primary restarted after the last attestation, before it adopts the complete assignment, was no longer creating by the record and could be replaced. The record now sets awaiting_first_ready in the same write that clears its initial set, and clears it, durably and for good, at the line's primary's first ready answer; until then the volume is creating. A record written before the field existed carries none, so an established volume is never reopened. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creation_phase_test.go | 56 ++++++++++++++++++- .../core/host/master/product_loop.go | 39 ++++++++++++- .../core/host/master/store_attestation.go | 44 ++++++++++++++- 3 files changed, 134 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index 30e96492ed..974f667404 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -113,6 +113,10 @@ func establishVolume(t *testing.T, h *Host, volumeID string) { if err := h.ingestStoreAttestation(server, attestation(volumeID, line.ReplicaID, line.Epoch, stores)); err != nil { t.Fatalf("establish %s: %v", volumeID, err) } + h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) // the wait closes + if err := h.attest.noteFirstReady(volumeID); err != nil { // the primary's first ready answer + t.Fatalf("establish %s: %v", volumeID, err) + } if line, _ := h.Publisher().VolumeAuthorityLine(volumeID); h.inCreationPhase(volumeID, line, nil) != "" { t.Fatalf("establish %s: still creating after the attestation (line %+v, server %q)", volumeID, line, server) } @@ -154,6 +158,10 @@ func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { h := newBootGraceMasterCreating(t, cfg) if established { attestAllStores(t, h) + h.attest.awaited("vol-rf3", h.replicaSlotsFor("vol-rf3")) + if err := h.attest.noteFirstReady("vol-rf3"); err != nil { + t.Fatal(err) + } } closeTestMaster(t, h) @@ -169,7 +177,7 @@ func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { defer closeTestMaster(t, h2) p := &switchProbe{} // r1 not ready (not awaiting), r2 ready with evidence h2.SetPromotionEvidenceProvider(p) - if got := inCreationWait(h2); got == established { + if got := h2.inCreationPhase("vol-rf3", waitAuthorityLine(t, h2.Publisher(), "vol-rf3"), nil) != ""; got == established { t.Fatalf("after the restart creating=%t; want %t", got, !established) } time.Sleep(250 * time.Millisecond) // past the boot grace @@ -185,3 +193,49 @@ func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { }) } } + +// Creation ends at the primary's first ready answer at its first line, not +// at the last store attestation: a primary restarted after the last +// attestation, before it adopts the complete assignment (it answers not +// ready, and no longer says it awaits the stores), is still creating: no +// fencing round, no reassign. Its first ready answer ends creation, durably, +// and from then on the normal rules apply. +func TestCreationEndsAtThePrimarysFirstReadyAnswer(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) + defer closeTestMaster(t, h) + attestAllStores(t, h) // every store recorded: the master's wait is over + p := probeOf(t, h) + p.mu.Lock() + p.empty = true // r1 answers not ready (restarted), awaiting nothing + p.mu.Unlock() + time.Sleep(250 * time.Millisecond) // past the boot grace + restarted := rf3Slot{incarnation: "r1-b", reachable: true, eligible: true} + supportedCreatingTick(t, h, restarted) + supportedCreatingTick(t, h, restarted) + p.mu.Lock() + fences := p.fenceCalls + p.mu.Unlock() + if fences != 0 { + t.Fatalf("%d fencing rounds before the primary's first ready answer", fences) + } + expectLineStaysR1(t, h, "a restarted primary before its first ready answer") + line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if h.inCreationPhase("vol-rf3", line, nil) == "" { + t.Fatal("creation ended before the primary's first ready answer") + } + p.mu.Lock() + p.currentReady = true // the first ready answer + p.mu.Unlock() + if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { + t.Fatalf("after the first ready answer: still creating (%s)", why) + } + if h.attest.awaitingFirstReady("vol-rf3") { + t.Fatal("the first ready answer was not recorded") + } + p.mu.Lock() + p.currentReady = false // a later not-ready answer reopens nothing + p.mu.Unlock() + if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { + t.Fatalf("creation reopened after it ended (%s)", why) + } +} diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 9b1203e5b7..7699250c2e 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -1104,8 +1104,10 @@ func (h *Host) freshCurrentSlot(volumeID, replicaID string) (authority.ReplicaCa // replacement entry (both promotion gates, the operator's move and planned // move, the rebalance through the gate) calls first: it returns why the // volume is creating, or "" once it is not. Two sources, in order: -// - the master's own durable record still awaits a replica store (every -// initial store attested clears it, durably; no other state); +// - the master's own durable record: it still awaits a replica store, or +// every store is attested but the primary has not yet answered ready at +// its first line (its first ready answer ends creation, recorded durably +// and for good; no other state); // - the current primary's own answer, when one was read, says its // assignment at this line's epoch still awaits the stores (the master's // wait may be over before the re-sent assignment arrives). The answer @@ -1115,6 +1117,15 @@ func (h *Host) inCreationPhase(volumeID string, current authority.AuthorityBasis if waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)); waiting > 0 { return "the master's record awaits replica stores" } + if h.attest.awaitingFirstReady(volumeID) { + if !h.firstReadyNow(volumeID, current, answer) { + return "the primary has not yet answered ready at its first line" + } + if err := h.attest.noteFirstReady(volumeID); err != nil { + return "the first ready answer could not be recorded: " + err.Error() + } + h.log.Printf("blockmaster: volume=%s creation complete: primary %s answered ready at epoch %d", volumeID, current.ReplicaID, current.Epoch) + } } if answer != nil && answer.CurrentKnown && current.Epoch != 0 && answer.Current.AwaitingReplicaStoresEpoch == current.Epoch { return "the primary's answer awaits replica stores" @@ -1122,6 +1133,30 @@ func (h *Host) inCreationPhase(volumeID string, current authority.AuthorityBasis return "" } +// firstReadyNow: the line's own primary answers ready now (from the answer +// given, or a round of the primary alone). A primary that awaits the stores, +// or one that does not answer, is not ready. +func (h *Host) firstReadyNow(volumeID string, current authority.AuthorityBasis, answer *PromotionProbeResult) bool { + if !current.Assigned || current.ReplicaID == "" { + return false + } + res := answer + if res == nil { + h.promotionMu.RLock() + prober := h.promotionProber + h.promotionMu.RUnlock() + if prober == nil { + return false + } + r, err := prober.ProbePromotionCandidates(volumeID, current, nil) + if err != nil { + return false + } + res = &r + } + return res.CurrentKnown && res.Current.ReplicaID == current.ReplicaID && res.Current.Ready && res.Current.AwaitingReplicaStoresEpoch == 0 +} + // answerOf is the probe's answer, or nil when the probe gave none. func answerOf(result PromotionProbeResult, ok bool) *PromotionProbeResult { if !ok { diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 2a93bdf4e7..819b441f60 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -31,6 +31,12 @@ type attestedStores struct { // meanwhile is not waited for); it is cleared, for good, the first time // every current replica has a recorded store. Initial []string `json:"initial,omitempty"` + // AwaitingFirstReady: every initial store is attested, but the volume's + // primary has not yet answered ready at its first line (first Healthy). + // Set in the same write that clears Initial, cleared for good by the + // first ready answer: creation ends there. A record written before this + // field existed has none, so an established volume is never reopened. + AwaitingFirstReady bool `json:"awaiting_first_ready,omitempty"` } // storeAttestations is the master's record of which store each replica @@ -157,6 +163,7 @@ func (s *storeAttestations) awaited(volumeID string, current []string) (waiting, vols[k] = x } v.Initial = nil + v.AwaitingFirstReady = true // creation ends at the primary's first ready answer vols[volumeID] = v if err := s.persist(vols); err != nil { // Not cleared: the volume keeps answering from its stores (nothing @@ -168,6 +175,38 @@ func (s *storeAttestations) awaited(volumeID string, current []string) (waiting, return 0, len(current) } +// awaitingFirstReady: the volume's stores are all attested and its primary +// has not yet answered ready at its first line. +func (s *storeAttestations) awaitingFirstReady(volumeID string) bool { + s.mu.Lock() + defer s.mu.Unlock() + v, had := s.vols[volumeID] + return had && v.AwaitingFirstReady +} + +// noteFirstReady records, durably and for good, that the volume's primary +// answered ready at its first line: its creation is complete. +func (s *storeAttestations) noteFirstReady(volumeID string) error { + s.mu.Lock() + defer s.mu.Unlock() + v, had := s.vols[volumeID] + if !had || !v.AwaitingFirstReady { + return nil + } + vols := make(map[string]attestedStores, len(s.vols)) + for k, x := range s.vols { + vols[k] = x + } + v.AwaitingFirstReady = false + vols[volumeID] = v + if err := s.persist(vols); err != nil { + return err + } + s.vols = vols + s.notifyLocked(volumeID) + return nil +} + // record merges att into the volume's record, in one write: each replica it // names gets that store as its reference; a replica it does not name keeps // its last one. An attestation from a lower epoch than the recorded one is @@ -200,7 +239,8 @@ func (s *storeAttestations) record(att *control.StoreAttestation) error { next.Stores[id] = sid } } - next.Initial = cur.Initial // cleared only by awaited + next.Initial = cur.Initial // cleared only by awaited + next.AwaitingFirstReady = cur.AwaitingFirstReady // cleared only by noteFirstReady if had && sameAttestation(cur, next) { return nil } @@ -218,7 +258,7 @@ func (s *storeAttestations) record(att *control.StoreAttestation) error { } func sameAttestation(a, b attestedStores) bool { - if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) || len(a.Initial) != len(b.Initial) { + if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) || len(a.Initial) != len(b.Initial) || a.AwaitingFirstReady != b.AwaitingFirstReady { return false } for k, v := range a.Stores { From 5e520aa7621a8b5b3cd6df66847a9b874bf26724 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:34:44 -0800 Subject: [PATCH 10/29] test(master): the boot-grace fixture is an established volume (first ready answer recorded) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/creation_phase_test.go | 2 +- seaweed-block/core/host/master/primary_boot_grace_gate_test.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index 974f667404..a929e4101b 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -113,7 +113,7 @@ func establishVolume(t *testing.T, h *Host, volumeID string) { if err := h.ingestStoreAttestation(server, attestation(volumeID, line.ReplicaID, line.Epoch, stores)); err != nil { t.Fatalf("establish %s: %v", volumeID, err) } - h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) // the wait closes + h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) // the wait closes if err := h.attest.noteFirstReady(volumeID); err != nil { // the primary's first ready answer t.Fatalf("establish %s: %v", volumeID, err) } diff --git a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go index 4b07787b9d..675077bf65 100644 --- a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go +++ b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go @@ -167,6 +167,7 @@ func newBootGraceMaster(t *testing.T, cfg Config) *Host { t.Helper() h := newBootGraceMasterCreating(t, cfg) attestAllStores(t, h) + establishVolume(t, h, "vol-rf3") // and the primary's first ready answer: an established volume return h } From b201bbb74dd7cc28f858429091c2555269f4d3bc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:40:26 -0800 Subject: [PATCH 11/29] test(master): fixtures record the first ready answer where the primary served; the restart gap is still creating Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/creating_primary_gate_test.go | 7 ++++--- seaweed-block/core/host/master/creation_phase_test.go | 11 +++++++++++ seaweed-block/core/host/master/product_loop_test.go | 1 + .../host/master/promotion_adoption_regression_test.go | 1 + .../core/host/master/store_attestation_test.go | 1 + 5 files changed, 18 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/host/master/creating_primary_gate_test.go b/seaweed-block/core/host/master/creating_primary_gate_test.go index 9697a23dd6..b3379fdf40 100644 --- a/seaweed-block/core/host/master/creating_primary_gate_test.go +++ b/seaweed-block/core/host/master/creating_primary_gate_test.go @@ -50,8 +50,9 @@ func TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady(t *testing.T) { // The real-path schedule: the master has recorded every store (its wait is // over) but the primary has not received the re-sent assignment yet, so it // still answers "awaiting replica stores"; the master restarts in that gap. -// The excuse is the primary's own answer, so nothing the master forgets on a -// restart reopens the gap: the line stays. +// Creation ends only at the primary's first ready answer, recorded durably, +// so the restarted master still holds the volume: no decision, the line +// stays. func TestMasterRestartInTheGapDoesNotReassign(t *testing.T) { cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}} @@ -74,7 +75,7 @@ func TestMasterRestartInTheGapDoesNotReassign(t *testing.T) { t.Fatal("fixture: the restarted master still waits for stores") } time.Sleep(250 * time.Millisecond) // past the boot grace - unsupportedTick(t, h2, readySlot("r1-a")) + creatingTick(t, h2, readySlot("r1-a")) expectLineStaysR1(t, h2, "restarted master, primary still awaiting the re-sent stores") } diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index a929e4101b..91d5a263e4 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -239,3 +239,14 @@ func TestCreationEndsAtThePrimarysFirstReadyAnswer(t *testing.T) { t.Fatalf("creation reopened after it ended (%s)", why) } } + +// recordFirstReady records that the volume's primary answered ready at its +// first line (after its stores were attested): fixtures whose primary was +// healthy before the scenario's failure. +func recordFirstReady(t *testing.T, h *Host, volumeID string) { + t.Helper() + h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) + if err := h.attest.noteFirstReady(volumeID); err != nil { + t.Fatal(err) + } +} diff --git a/seaweed-block/core/host/master/product_loop_test.go b/seaweed-block/core/host/master/product_loop_test.go index d811603c93..7a4218ca18 100644 --- a/seaweed-block/core/host/master/product_loop_test.go +++ b/seaweed-block/core/host/master/product_loop_test.go @@ -460,6 +460,7 @@ func TestMountedFailover_ProductLoopRF3PromotesWhenCurrentProbeIsDownDespiteStal t.Fatalf("initial line=%+v want r1", initial) } attestAllStores(t, h) // an established volume, out of its creation wait + recordFirstReady(t, h, "vol-rf3") // Heartbeat state still says r1 is acceptable. The on-demand // current-primary probe is the fresher failure signal and must diff --git a/seaweed-block/core/host/master/promotion_adoption_regression_test.go b/seaweed-block/core/host/master/promotion_adoption_regression_test.go index f9b38531a9..a4a3b22283 100644 --- a/seaweed-block/core/host/master/promotion_adoption_regression_test.go +++ b/seaweed-block/core/host/master/promotion_adoption_regression_test.go @@ -77,6 +77,7 @@ func TestPromotionRefusesReplicaMissingAcknowledgedWrite(t *testing.T) { if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", initial.Epoch, attested)); err != nil { t.Fatal(err) } + recordFirstReady(t, h, "vol-rf3") // the primary served before it failed if err := cluster.Primary().RepVol.Close(); err != nil { t.Fatal(err) } diff --git a/seaweed-block/core/host/master/store_attestation_test.go b/seaweed-block/core/host/master/store_attestation_test.go index ba127ef571..671af17a96 100644 --- a/seaweed-block/core/host/master/store_attestation_test.go +++ b/seaweed-block/core/host/master/store_attestation_test.go @@ -139,6 +139,7 @@ func TestPromotionRefusesAReplacedStoreThePrimaryNeverAttested(t *testing.T) { if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": storeID(1), "r2": s1, "r3": t1})); err != nil { t.Fatal(err) } + recordFirstReady(t, h, "vol-rf3") // the primary served before it failed // r2's node reports its new store: never the reference. if err := h.ingestStoreAttestation("node-b", attestation("vol-rf3", "r2", line.Epoch, map[string]storage.StoreID{"r2": s2})); err != nil { t.Fatal(err) From 8c0a4f712386f9da94fb006a5537d0edd09a62a6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:45:41 -0800 Subject: [PATCH 12/29] docs: creation ends at the primary's first ready answer (INV-PROMOTE-CREATION-WAIT-001) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 39e6a49e7f..3ec3122d34 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -955,7 +955,7 @@ Notes: | `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase: while the master's durable record awaits a replica store, or the primary answers that its assignment at the line's epoch awaits them, no replacement decision is made (reassign, fencing round, higher-epoch heal, operator or planned move, rebalance); checked first. | CreatePromo model (VolumeCreate x Promotion) | `core/host/master/product_loop.go` `inCreationPhase`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | +| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase, ending at the line's primary's first ready answer (recorded durably, for good): before it, or while the primary answers that it awaits replica stores, no replacement decision is made (reassign, fencing round, heal, operator move, rebalance); checked first. | CreatePromo model (VolumeCreate x Promotion) | `core/host/master/product_loop.go` `inCreationPhase`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent`, `TestCreationEndsAtThePrimarysFirstReadyAnswer`, `TestCreatingVolumeRefusesTheOperatorsMove`, `TestCreationPhaseSurvivesAMasterRestart` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (no fresh, reachable heartbeat; any replica count); a reachable RF3 `sync_quorum` primary's move stays refused (it needs a seal) and `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`, `TestManualFailoverRF3ReachablePrimaryIsRefused`, `TestManualFailoverAndThePromotionLoopPublishOneLine`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | From 8d2c0dafd55b2a88dd343580576e28e7dd1ca225 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:10:07 -0800 Subject: [PATCH 13/29] test(master): a never-created volume is deleted without its holder; an established one is not (red) Co-Authored-By: Claude Opus 5.5 --- .../workspace_delete_never_created_test.go | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 seaweed-block/core/host/master/workspace_delete_never_created_test.go diff --git a/seaweed-block/core/host/master/workspace_delete_never_created_test.go b/seaweed-block/core/host/master/workspace_delete_never_created_test.go new file mode 100644 index 0000000000..6d01a1d599 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_delete_never_created_test.go @@ -0,0 +1,77 @@ +package master + +import ( + "context" + "testing" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// neverCreatedVolume builds a layout volume the production way (create, +// binding, placement, heartbeat, a product tick binds its line) whose +// primary holds a live lease, and, when established, records its stores. +func neverCreatedVolume(t *testing.T, established bool) (*Host, control.LifecycleServiceClient, control.WorkspaceServiceClient, *control.WorkspaceIdentity) { + t.Helper() + h, conn, ctx := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{Gen: 2}, authority.ErrWorkspaceHeadUnclaimed + }, nil) + reviewCreate(t, conn, ctx, "v") + ws := control.NewWorkspaceServiceClient(conn) + b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} + if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + line := waitAuthorityLine(t, h.Publisher(), "v") + if established { + establishVolume(t, h, "v") + } + id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: line.Epoch, ServerId: "node-a"} + if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil { + t.Fatalf("the primary's lease: %v", err) + } + if creating := h.inCreationPhase("v", line, nil) != ""; creating == established { + t.Fatalf("fixture: creating=%t, want %t", creating, !established) + } + return h, control.NewLifecycleServiceClient(conn), ws, id +} + +// A volume that never completed creation is deleted without its holder's +// cooperation: the reservation is admitted although the creating primary +// still holds a live lease (it served nothing and acknowledged nothing). +// From the reservation on the master grants that primary no lease, so a +// zombie that wakes cannot serve, and the delete's HEAD update still waits +// until no lease is live (the horizon), after which HEAD is marked deleting +// and no claim or commit applies to it. +func TestANeverCreatedVolumeIsDeletedWithoutItsHolder(t *testing.T) { + _, lc, ws, id := neverCreatedVolume(t, false) + req := &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-created"} + if _, err := lc.ReserveVolumeDeletion(t.Context(), req); err != nil { + t.Fatalf("delete reservation of a never-created volume with a live lease: %v", err) + } + if _, err := ws.RenewWorkspaceLease(t.Context(), id); err == nil { + t.Fatal("the creating primary renewed its lease after the delete reservation: a zombie could keep serving") + } + if _, err := lc.CheckVolumeNoLiveLease(t.Context(), req); err == nil { + t.Fatal("the delete's HEAD update was admitted while the last lease may still be live") + } +} + +// A volume that completed creation keeps the rule: its delete is refused +// while its holder's lease is live (the holder must be revoked first). +func TestAnEstablishedVolumeIsNotDeletedUnderALiveLease(t *testing.T) { + _, lc, _, _ := neverCreatedVolume(t, true) + _, err := lc.ReserveVolumeDeletion(t.Context(), &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-established"}) + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("delete of an established volume under a live lease: %v; want FailedPrecondition", err) + } +} From 353163e23cacdef7928aead32f3ede4d68a2366c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:11:05 -0800 Subject: [PATCH 14/29] fix: a volume that never completed creation is deleted without its holder The layout delete's reservation was refused while any lease was live, and a creating primary that is stuck (a replica store never attested) keeps renewing, so the only exit from the creation phase, delete and recreate, was closed. A volume whose master record never left the creation phase (it served nothing, acknowledged nothing) is now reserved for delete under a live lease: the reservation stops every grant at once, the delete's HEAD update still waits until no lease is live, and HEAD deleting then admits no claim or commit. A volume that ever completed creation keeps the live-lease refusal. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_delete_reservation.go | 16 +++++++++++- .../workspace_delete_reservation_test.go | 25 +++++++++++++++++++ .../host/master/volume_delete_authority.go | 13 ++++++++-- 3 files changed, 51 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/authority/workspace_delete_reservation.go b/seaweed-block/core/authority/workspace_delete_reservation.go index 5f8220e872..7f97368dd6 100644 --- a/seaweed-block/core/authority/workspace_delete_reservation.go +++ b/seaweed-block/core/authority/workspace_delete_reservation.go @@ -24,6 +24,20 @@ func (p *Publisher) beforeWorkspaceGrantLock(site string) { // not reenter Publisher. A replay does no I/O. On startup, call this for every // reloaded committed reservation before serving requests (persist is then nil). func (p *Publisher) ReserveWorkspaceDeletion(ctx context.Context, volume string, persist func() error) error { + return p.reserveWorkspaceDeletion(ctx, volume, true, persist) +} + +// ReserveNeverCreatedWorkspaceDeletion is the delete reservation of a volume +// whose creation never completed (the master's record of it never left the +// creation phase): it served nothing and acknowledged nothing, and its +// creating holder may be broken, so a lease still live now does not refuse +// it. The reservation stops every grant for the volume from then on, and the +// delete's HEAD update still waits until no lease is live (NoLiveWorkspaceLease). +func (p *Publisher) ReserveNeverCreatedWorkspaceDeletion(ctx context.Context, volume string, persist func() error) error { + return p.reserveWorkspaceDeletion(ctx, volume, false, persist) +} + +func (p *Publisher) reserveWorkspaceDeletion(ctx context.Context, volume string, refuseLive bool, persist func() error) error { p.mu.Lock() defer p.mu.Unlock() if err := ctx.Err(); err != nil { @@ -39,7 +53,7 @@ func (p *Publisher) ReserveWorkspaceDeletion(ctx context.Context, volume string, // irreversible step: nothing is persisted while a lease is live now. // This decides nothing for safety (the closed grant writers and the // check at the delete's HEAD update do); it stops an outage by mistake. - if persist != nil { + if persist != nil && refuseLive { if err := p.liveLeaseLocked(volume); err != nil { return fmt.Errorf("%w: %w", ErrWorkspaceDeleteRefused, err) } diff --git a/seaweed-block/core/authority/workspace_delete_reservation_test.go b/seaweed-block/core/authority/workspace_delete_reservation_test.go index 0ca5fad970..38a30ae11f 100644 --- a/seaweed-block/core/authority/workspace_delete_reservation_test.go +++ b/seaweed-block/core/authority/workspace_delete_reservation_test.go @@ -270,3 +270,28 @@ func TestDeleteReservationContextAndPersistenceFailuresStayUnknown(t *testing.T) }) } } + +// A volume whose creation never completed is reserved for delete although +// its holder's lease is live now (it served nothing; its holder may be +// broken): the reservation stops the holder's renewals, and the HEAD update +// still waits until the lease has lapsed. +func TestNeverCreatedDeleteIsReservedUnderALiveLease(t *testing.T) { + ctx := context.Background() + c := newTestClock() + p := newLeasePublisher(t, &deleteGrantStore{}, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") + persisted := false + if err := p.ReserveNeverCreatedWorkspaceDeletion(ctx, "v", func() error { persisted = true; return nil }); err != nil || !persisted { + t.Fatalf("reserve of a never-created volume under a live lease: %v (persisted %t)", err, persisted) + } + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { + t.Fatal("the never-created volume's holder renewed after the reservation") + } + if err := p.NoLiveWorkspaceLease(ctx, "v"); err == nil { + t.Fatal("the HEAD update was admitted while the lease may still be live") + } + c.at(1000) + if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil { + t.Fatalf("after the lease lapsed: %v", err) + } +} diff --git a/seaweed-block/core/host/master/volume_delete_authority.go b/seaweed-block/core/host/master/volume_delete_authority.go index 6c8240f13b..2da9c4e363 100644 --- a/seaweed-block/core/host/master/volume_delete_authority.go +++ b/seaweed-block/core/host/master/volume_delete_authority.go @@ -29,13 +29,22 @@ func (a *volumeDeleteAuthority) Reserve(ctx context.Context) error { if h.lifecycle == nil { return errors.New("workspace delete: lifecycle store unavailable") } - return h.Publisher().ReserveWorkspaceDeletion(ctx, a.volume, func() error { + persist := func() error { if _, err := h.lifecycle.Deletions.Admit(a.volume, a.token); err != nil { return err } _, err := h.lifecycle.Deletions.Commit(a.volume, a.token) return err - }) + } + // A volume whose creation never completed (the master's durable record + // still awaits a replica store) is deleted without its holder: a live + // lease does not refuse the reservation, which stops every grant; the + // HEAD update still waits for no live lease. A volume that ever completed + // creation keeps the live-lease refusal. + if h.inCreationPhase(a.volume, authority.AuthorityBasis{}, nil) != "" { + return h.Publisher().ReserveNeverCreatedWorkspaceDeletion(ctx, a.volume, persist) + } + return h.Publisher().ReserveWorkspaceDeletion(ctx, a.volume, persist) } func (a *volumeDeleteAuthority) NoLiveLease(ctx context.Context) error { From f5641b362f3a8a5cbf490d03ee008356299691fd Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:17:19 -0800 Subject: [PATCH 15/29] test: the reservation guard lives in reserveWorkspaceDeletion; the live-lease delete fixture is an established volume Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/workspace_delete_guard_test.go | 2 +- seaweed-block/core/host/master/volume_delete_authority_test.go | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/authority/workspace_delete_guard_test.go b/seaweed-block/core/authority/workspace_delete_guard_test.go index 264c056091..6d88fbfa13 100644 --- a/seaweed-block/core/authority/workspace_delete_guard_test.go +++ b/seaweed-block/core/authority/workspace_delete_guard_test.go @@ -13,7 +13,7 @@ import ( func TestDeletionReservationGuardSites(t *testing.T) { // A new field access or grant-bound writer must join the causal controls. flagSites := map[string]bool{ - "ReserveWorkspaceDeletion": true, "NoLiveWorkspaceLease": true, + "reserveWorkspaceDeletion": true, "NoLiveWorkspaceLease": true, "applyWithWorkspaceMove": true, "MoveWorkspace": true, "RenewWorkspaceLease": true, "firstWorkspaceGrant": true, "regrantWorkspaceLease": true, "extendWorkspaceLease": true, diff --git a/seaweed-block/core/host/master/volume_delete_authority_test.go b/seaweed-block/core/host/master/volume_delete_authority_test.go index 1e6c55cfb3..39c64ae58d 100644 --- a/seaweed-block/core/host/master/volume_delete_authority_test.go +++ b/seaweed-block/core/host/master/volume_delete_authority_test.go @@ -125,6 +125,7 @@ func TestVolumeDeleteAuthorityRPCFailureIsUnknown(t *testing.T) { func TestReserveVolumeDeletionLiveLeaseIsDefiniteAndKeepsRenewing(t *testing.T) { h, conn, ctx := reviewBindingHost(t) reviewLegacyBind(t, h, conn, ctx, "live-delete") + establishVolume(t, h, "live-delete") // a volume past creation keeps the live-lease refusal if _, err := h.Publisher().RenewWorkspaceLease(ctx, "live-delete", "r1", 1); err != nil { t.Fatal(err) } From 3615b1d7e8de8fcbe4f6a273428d4a712a448ed0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:25:37 -0800 Subject: [PATCH 16/29] test(master): the never-created delete finishes past the lease horizon Co-Authored-By: Claude Opus 5.5 --- .../workspace_delete_never_created_test.go | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/seaweed-block/core/host/master/workspace_delete_never_created_test.go b/seaweed-block/core/host/master/workspace_delete_never_created_test.go index 6d01a1d599..b6410aa522 100644 --- a/seaweed-block/core/host/master/workspace_delete_never_created_test.go +++ b/seaweed-block/core/host/master/workspace_delete_never_created_test.go @@ -2,7 +2,9 @@ package master import ( "context" + "sync/atomic" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/rpc/control" @@ -13,11 +15,17 @@ import ( // neverCreatedVolume builds a layout volume the production way (create, // binding, placement, heartbeat, a product tick binds its line) whose // primary holds a live lease, and, when established, records its stores. -func neverCreatedVolume(t *testing.T, established bool) (*Host, control.LifecycleServiceClient, control.WorkspaceServiceClient, *control.WorkspaceIdentity) { +func neverCreatedVolume(t *testing.T, established bool) (*Host, control.LifecycleServiceClient, control.WorkspaceServiceClient, *control.WorkspaceIdentity, *atomic.Int64) { t.Helper() + // The lease clock is the master's (server configuration): the test + // moves it past the lease horizon. + nowNS := &atomic.Int64{} + nowNS.Store(time.Now().UnixNano()) h, conn, ctx := reviewBindingHostBeforeStart(t, func(context.Context, string) (authority.WorkspaceHead, error) { return authority.WorkspaceHead{Gen: 2}, authority.ErrWorkspaceHeadUnclaimed - }, nil) + }, func(h *Host) { + authority.WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })(h.Publisher()) + }) reviewCreate(t, conn, ctx, "v") ws := control.NewWorkspaceServiceClient(conn) b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"} @@ -42,7 +50,7 @@ func neverCreatedVolume(t *testing.T, established bool) (*Host, control.Lifecycl if creating := h.inCreationPhase("v", line, nil) != ""; creating == established { t.Fatalf("fixture: creating=%t, want %t", creating, !established) } - return h, control.NewLifecycleServiceClient(conn), ws, id + return h, control.NewLifecycleServiceClient(conn), ws, id, nowNS } // A volume that never completed creation is deleted without its holder's @@ -53,7 +61,7 @@ func neverCreatedVolume(t *testing.T, established bool) (*Host, control.Lifecycl // until no lease is live (the horizon), after which HEAD is marked deleting // and no claim or commit applies to it. func TestANeverCreatedVolumeIsDeletedWithoutItsHolder(t *testing.T) { - _, lc, ws, id := neverCreatedVolume(t, false) + _, lc, ws, id, nowNS := neverCreatedVolume(t, false) req := &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-never-created"} if _, err := lc.ReserveVolumeDeletion(t.Context(), req); err != nil { t.Fatalf("delete reservation of a never-created volume with a live lease: %v", err) @@ -64,12 +72,21 @@ func TestANeverCreatedVolumeIsDeletedWithoutItsHolder(t *testing.T) { if _, err := lc.CheckVolumeNoLiveLease(t.Context(), req); err == nil { t.Fatal("the delete's HEAD update was admitted while the last lease may still be live") } + // Past the lease horizon (the 30 s lease plus the clock-skew margin) the + // HEAD update is admitted: the delete finishes without the holder. + nowNS.Add(int64(2 * time.Minute)) + if _, err := lc.CheckVolumeNoLiveLease(t.Context(), req); err != nil { + t.Fatalf("past the lease horizon the delete's HEAD update is still refused: %v", err) + } + if _, err := ws.RenewWorkspaceLease(t.Context(), id); err == nil { + t.Fatal("the creating primary renewed its lease past the horizon") + } } // A volume that completed creation keeps the rule: its delete is refused // while its holder's lease is live (the holder must be revoked first). func TestAnEstablishedVolumeIsNotDeletedUnderALiveLease(t *testing.T) { - _, lc, _, _ := neverCreatedVolume(t, true) + _, lc, _, _, _ := neverCreatedVolume(t, true) _, err := lc.ReserveVolumeDeletion(t.Context(), &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-established"}) if status.Code(err) != codes.FailedPrecondition { t.Fatalf("delete of an established volume under a live lease: %v; want FailedPrecondition", err) From 2e2a425ecaa1672fa75e3a13d843d87462e4d1df Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 21:47:00 -0800 Subject: [PATCH 17/29] fix(master): the delete reads the creation phase with the volume's line Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/volume_delete_authority.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/volume_delete_authority.go b/seaweed-block/core/host/master/volume_delete_authority.go index 2da9c4e363..34e0729a13 100644 --- a/seaweed-block/core/host/master/volume_delete_authority.go +++ b/seaweed-block/core/host/master/volume_delete_authority.go @@ -41,7 +41,10 @@ func (a *volumeDeleteAuthority) Reserve(ctx context.Context) error { // lease does not refuse the reservation, which stops every grant; the // HEAD update still waits for no live lease. A volume that ever completed // creation keeps the live-lease refusal. - if h.inCreationPhase(a.volume, authority.AuthorityBasis{}, nil) != "" { + // The line, so a primary that has just answered ready is recorded + // (creation complete) before the delete is decided. + line, _ := h.Publisher().VolumeAuthorityLine(a.volume) + if h.inCreationPhase(a.volume, line, nil) != "" { return h.Publisher().ReserveNeverCreatedWorkspaceDeletion(ctx, a.volume, persist) } return h.Publisher().ReserveWorkspaceDeletion(ctx, a.volume, persist) From cbd0f12d0c7e7a018b3e804933082866df855f41 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 22:07:41 -0800 Subject: [PATCH 18/29] test(master): the endpoint fixture is an established volume Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/master/failback_endpoint_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/seaweed-block/core/host/master/failback_endpoint_test.go b/seaweed-block/core/host/master/failback_endpoint_test.go index 264f2620e8..329843ffe3 100644 --- a/seaweed-block/core/host/master/failback_endpoint_test.go +++ b/seaweed-block/core/host/master/failback_endpoint_test.go @@ -27,6 +27,7 @@ func TestFailbackPublishesOnlyTheMastersRecordedTargetAddresses(t *testing.T) { if line.ReplicaID != "r1" { t.Fatalf("initial line=%+v want r1", line) } + establishVolume(t, h, "vol-rf2") // an established volume: the move is past creation req := func(data, ctrl string) authority.FailbackRuntimeRequest { return authority.FailbackRuntimeRequest{VolumeID: "vol-rf2", ReplicaID: "r2", TargetDataAddr: data, TargetCtrlAddr: ctrl, ExpectedCurrentReplicaID: line.ReplicaID, ExpectedCurrentEpoch: line.Epoch, From 3bc43a68795047d749e6e6aa4a7a0185c83103ae Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 23:36:53 -0800 Subject: [PATCH 19/29] docs: restore as v1 ships it; fork removed Restore is created with --master and fills on access (no restore driver, no background copy); its source snapshot stays a dependent for the target's life. Fork and template retirement are not in this release. The documented show, snapshots and snapshot-delete commands get the required --master. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/README.md | 22 +++--- seaweed-block/docs/operator-guide.md | 10 +-- seaweed-block/docs/standalone-deployment.md | 78 ++++++--------------- seaweed-block/docs/user-capabilities.md | 2 +- seaweed-block/docs/volume-lifecycle.md | 12 ++-- 5 files changed, 42 insertions(+), 82 deletions(-) diff --git a/seaweed-block/README.md b/seaweed-block/README.md index 38101ef947..57d55419b7 100644 --- a/seaweed-block/README.md +++ b/seaweed-block/README.md @@ -46,7 +46,8 @@ their invariants, the tests behind them and the known issues. - **Incremental snapshots.** A cut uploads only the changed 4 MiB chunks. Chunks are immutable; the volume's state is a HEAD root of about 2 KB, and every publish is a conditional update on `{gen, epoch}`. -- **Cheap snapshot and fork.** Both copy only the HEAD root; chunks are shared. +- **Cheap snapshot and restore.** A snapshot copies only the HEAD root; chunks + are shared. A restore makes a new volume that reads the snapshot's chunks. A two-phase, graced GC reclaims unreferenced chunks. - **Move to any host.** Another host takes over with a higher epoch and fetches chunks lazily on first read. A stale holder cannot publish. @@ -66,7 +67,7 @@ file-backed disk. The two `fsync` rows marked "ublk" come from a later run on the same host with the ublk frontend, after the group-commit fix ([#173](https://github.com/seaweedfs/seaweed-block/pull/173)). Snapshot and fork: a host-side proxy without network latency, guest `fsync` or the block -frontend. +frontend. Fork was measured before it was removed from this release. | Measurement | Seaweed Block | Local disk | |---|---|---| @@ -126,10 +127,8 @@ cluster. The `sw-block ops chunk` commands drive the lifecycle: ```bash sw-block ops chunk cut --volume v1 --status-addr # publish changed chunks, advance HEAD sw-block ops chunk snapshot --volume v1 --status-addr --name s1 # name a snapshot -sw-block ops chunk snapshots --volume v1 --chunk-filer # list snapshots -sw-block ops chunk fork --chunk-filer --source v1 --snapshot s1 --target v2 # root copy only -sw-block ops chunk restore --chunk-filer --source v1 --snapshot s1 --target v3 --status-addr # independent copy -sw-block ops chunk restore --volume v3 --status-addr --status # restore progress +sw-block ops chunk snapshots --master --volume v1 --chunk-filer # list snapshots +sw-block ops chunk restore --master --chunk-filer --source v1 --snapshot s1 --target v3 # new volume from a snapshot sw-block ops chunk detach --volume v1 --status-addr # final cut (seal); moving needs revoke + move, see docs/volume-lifecycle.md sw-block ops chunk volume-delete --volume v2 --chunk-filer --master --request-id del-v2 sw-block ops chunk verify --volume v1 --chunk-filer # read-only check of the remote image @@ -142,12 +141,11 @@ Frozen detach and the pre-copy detach are not supported in this release: a detach with `--frozen` (`frozen:true` on `POST /chunk/detach`) is refused with 409 `frozen_detach_unsupported`, and `blockvolume` refuses to start with `--chunk-detach-precopy`. -`restore` creates the target from the snapshot and, with `--status-addr` naming -the blockvolume that serves the target, starts the background restore there: -the target serves at once, copies every chunk under its own keys and becomes -independent of the source (snapshots of it are refused until then). Without -`--status-addr` it only creates the target and prints the command that starts -the restore once the target is attached. +`restore` creates the target from the snapshot; its blockvolume serves at +once and reads every chunk it has not made local from the source's snapshot +(there is no background copy). The source snapshot cannot be deleted while the +target exists. Fork is not supported in this release; the command is removed. +See [Restoring a snapshot](docs/standalone-deployment.md#restoring-a-snapshot-into-a-new-volume). The chunk path (`walstore-chunk`) is a proof of concept. It is not yet a default, a release claim or a production path. diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 6689fed28e..5e86f7be8d 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -117,7 +117,7 @@ named like an admin client's or blockmaster's, but it cannot see a certificate's or recreate the record, then start it. A wrong-size local store left by an earlier release's first start is different: its log repeats `chunk attach check: chunkstore: geometry_mismatch` and it exits; waiting or restarting with the right flags does not help. In one sitting: stop the unit first; then check that the volume never served: - `sw-block ops chunk show --volume --chunk-filer --chunk-path ` prints `"epoch":0` and + `sw-block ops chunk show --master --volume --chunk-filer --chunk-path ` prints `"epoch":0` and `"holder":""` in its head; only then remove `.bin`, `.bin.chunkfresh`, `.bin.chunkmap` and `.replica-floor` from `--durable-root`, and start it with the right flags. If the head shows an epoch above 0 or a holder, do not remove these files; if the volume served before, its local store has its original size: correct the @@ -144,7 +144,7 @@ named like an admin client's or blockmaster's, but it cannot see a certificate's refusal names both numbers), and warns at start when the free space is below its remaining growth plus the WAL; there is no override. The refusal ends the process with status 1 (`blockvolume: durable storage open: ... needs N (size S + WAL W)`), so the shipped unit starts it again every 5 s, refusing each time, until its start limit stops - it; free space on that file system, then start the unit again. A restore or fork target refused this way exists in + it; free space on that file system, then start the unit again. A restore target refused this way exists in the catalog but cannot start, and it can be neither deleted nor moved until it has started once: a delete wants it sealed, revoked and acknowledged, and a forced move is refused because the master knows no holder of it. To recover it, free space on that file system, or start it again on the same host with `--durable-root` on a local @@ -199,10 +199,10 @@ A late upload by a dead holder into a deleted volume can remain; rerun volume-de - scheduled and manual snapshots; - deleting snapshots, and getting space back: - GC deletes the chunks after the grace (`--grace`, 1 hour by default), so a deleted snapshot's space is - reclaimed about 2 hours after the delete unless still referenced by a snapshot, fork or restore; + reclaimed about 2 hours after the delete unless still referenced by a snapshot or a restore target; - then the asynchronous SeaweedFS vacuum compacts the volume files; - `ops chunk verify`; -- forking a snapshot into a new volume that shares immutable objects, or restoring it into a new, independent volume. +- restoring a snapshot into a new volume, which reads the chunks it has not made local from that snapshot (fork is not supported in this release). A snapshot can be refused with `host_slot_busy` / `no background slot` (retryable) while every host slot is held by other volumes' cuts; retry with the same request id. With many volumes on a host, a snapshot may wait for a slot: @@ -290,7 +290,7 @@ Every command on the pages above, and the test that runs it. | `blockvolume` under systemd: exit 75 after an expired start, restart, re-grant | `TestSystemdExpiredStartupExits75ThenRegrantServes` (`cmd/blockvolume`, a real systemd manager, tag `systemd_integration`) | binary | | The shipped units' start limits (`StartLimitIntervalSec=600`, `StartLimitBurst=10`, `RestartPreventExitStatus=78`) | `TestBlockvolumeUnitsBoundStartupRetries` (`internal/testops`, reads the unit files) | unit files | | `systemctl enable`, `stop`, `disable`, `reset-failed`, `systemd-tmpfiles --create` as written on these pages | not run: the tests above start transient units, not the installed ones | not run | -| Headroom refusal at create, and both ways out (free space; `--durable-root` on a file system with room) | `TestHeadroomRefusesARestoreAndAForkTargetThenServesThem`, `TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot`, `TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC` (`cmd/blockvolume`, root, loop-mounted file systems) | binary | +| Headroom refusal at create, and both ways out (free space; `--durable-root` on a file system with room) | `TestHeadroomRefusesRestoreTargetsThenServesThem`, `TestHeadroomRefusedTargetBlastRadiusAndAnotherRoot`, `TestHeadroomRefusedRestoreTargetSurvivesItsSourceDeleteAndGC` (`cmd/blockvolume`, root, loop-mounted file systems) | binary | | A snapshot refused with `host_slot_busy` / `no background slot` while every host slot is held, retried with the same request id | `TestSnapshotLadderF1VolumesOneHost` (`cmd/blockvolume`, `F1_RUN=1`, `F1_HOST_LIMIT_DIR` set, 3 slots; `F1_SLOT_RETRY_SECONDS=0` is its negative control) | binary | | Full local disk; full `--host-limit-dir` | `TestProcedureLocalDiskFull` (`cmd/blockvolume`, root, `testdata/diskfull.sh`); what a Linux guest sees: `TestProcedureLocalDiskFullKernelInitiator` (kernel NVMe/TCP host) | binary | | A first start with the wrong `--durable-blocks`: refused before any local store is created (exit 78) | `TestWrongGeometryFlagIsRefusedBeforeTheStoreIsCreated` (`cmd/blockvolume`) | binary | diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index e7056c0b07..e5672eb7a0 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -521,7 +521,7 @@ The commands below use these placeholders: - **Status:** `GET STATUS/status/durable?volume=` shows the schedule under `Chunk.ScheduledSnapshot`: `lastOkNs`, `nextDueNs`, `lastFailure`, `skipped` and `snapshot_overdue`. ```bash -sw-block ops chunk snapshots --volume v1 --chunk-filer FILER # list +sw-block ops chunk snapshots --master MASTER --volume v1 --chunk-filer FILER # list sw-block ops chunk snapshot --volume v1 --name before-upgrade --status-addr STATUS # take one now ``` @@ -535,7 +535,7 @@ Space comes back in two steps. Neither is immediate. - A deleted snapshot's unshared chunks are therefore removed by the first pass after the delete. A pass waits while a snapshot is being taken (it is tried again shortly), a cut cancels a pass in progress, and a server that no longer holds the volume removes nothing. A snapshot deleted with `sw-block ops chunk` (not through the holder) is cleaned at the next periodic pass. ```bash - sw-block ops chunk snapshot-delete --volume v1 --name sched-20261120T031204Z --chunk-filer FILER + sw-block ops chunk snapshot-delete --master MASTER --volume v1 --name sched-20261120T031204Z --chunk-filer FILER # the holder's next maintenance pass removes the chunks only it named; # each pass logs "maintenance volume=... removed=N" ``` @@ -585,70 +585,32 @@ therefore see every chunk of every volume and snapshot as unreferenced. - Space is returned only by the two steps above (the holder's cleaning, then a SeaweedFS vacuum). `volume.vacuum` is safe: it compacts needles that were already deleted. -### Forking a snapshot into a new volume +### Fork and template retirement -A fork creates a new volume sharing the snapshot's immutable chunks and segments: +Fork is not supported in this release; the command is removed. Restore from a snapshot instead (below). -```bash -sw-block ops chunk fork --source v1 --snapshot before-upgrade --target v2 --chunk-filer FILER --request-id fork-v2 -``` - -Keep the request id to retry an uncertain result. The new HEAD contains a complete image map; reads do not walk back through parent volumes or snapshots. A fork of a fork preserves the original object owners without adding a backing chain. Deleting the source snapshot does not delete objects still referenced by the fork. Use restore when the target must eventually own its data independently. - -### Retiring the source of a template - -A template is an ordinary immutable snapshot, not a separate volume kind. Keep the volume holding an offered template snapshot: volume deletion refuses while any snapshot name exists. To retire the original source instead, first move the template image into a dedicated holder using existing fork and snapshot operations. - -Prerequisites: `v1` is serving, its only snapshot is `seed`, and the standalone cluster spec has new volume placements for `template-holder` and `consumer`. Neither target blockvolume has started yet. Use the same filer and chunk namespace throughout. - -1. Create the holder: - - ```bash - sw-block ops chunk fork --source v1 --snapshot seed --target template-holder --chunk-filer FILER --request-id fork-template-holder - ``` - -2. Start `template-holder` with the normal standalone blockvolume command and its own volume id, endpoints and local root. Wait for its frontend readiness; read back the seed's known data before proceeding. Take the template snapshot: - - ```bash - sw-block ops chunk snapshot --volume template-holder --status-addr HOLDER_STATUS --name template-v1 - ``` - -3. Create a consumer, start its blockvolume on its own placement and root, and verify its known data: - - ```bash - sw-block ops chunk fork --source template-holder --snapshot template-v1 --target consumer --chunk-filer FILER --request-id fork-consumer - ``` - -4. Stop the source writer. Follow [Delete a volume](volume-lifecycle.md#delete-a-volume) for `v1`: plain detach, revoke its exact replica/epoch/sealed generation, wait for its recorded ACK and natural exit, delete `seed`, then delete `v1`. Do not signal the process in place of waiting for its ACK. Require the completed delete answer and `show` state `deleted` before continuing. - -5. Verify both surviving images, including the holder's template snapshot: - - ```bash - sw-block ops chunk verify --volume template-holder --all-snapshots --depth data --timeout 2m --chunk-filer FILER - sw-block ops chunk verify --volume consumer --all-snapshots --depth data --timeout 2m --chunk-filer FILER - ``` - - Read back the known data again and repeat both verify commands after the holder's next maintenance pass. Each holder cleans only its own volume; the objects of a deleted volume are removed by the volume delete itself. - -Keep `template-holder/template-v1` while it is offered for new consumers. Retiring that snapshot later does not delete objects still referenced by existing consumers. Deleting the holder volume itself still requires the ordinary seal/revoke/ACK and snapshot-deletion procedure; do not remove its backing filer directory or object bindings by hand. +Retiring the source of a template is not supported in this release either: a restore target depends on its source snapshot for its whole life (see [Lifetime](#lifetime-of-a-restore-target)), so the source snapshot, and therefore its volume, cannot be deleted while any target exists. ### Restoring a snapshot into a new volume -A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards. +A restore makes a new volume from a snapshot. The new volume reads every chunk it has not made local from the source's snapshot, so the snapshot stays in use for as long as the new volume exists. -1. **Add the target to blockmaster.** Add the target volume (for example `v2`) to blockmaster's topology, and start a blockvolume for it with the same chunk settings (`--chunk-filer`, `--chunk-path`, `--chunk-control-endpoint`) and the source's geometry. -2. **Create the restore and start it:** +1. **Add the target to blockmaster.** Add the target volume (for example `v2`) to blockmaster's topology, with the source's geometry. +2. **Create the restore:** ```bash - sw-block ops chunk restore --source v1 --snapshot sched-20261120T031204Z --target v2 --chunk-filer FILER --status-addr STATUS_OF_V2 + sw-block ops chunk restore --master MASTER --source v1 --snapshot sched-20261120T031204Z --target v2 --chunk-filer FILER --request-id restore-v2 ``` - This creates `v2` from the snapshot (idempotent by `--request-id`; the generated id is printed, so reuse it to retry) and starts the restore driver in v2's blockvolume. - - **Before the target is attached:** run the same command without `--status-addr` to create `v2`. Once its blockvolume is up, run `sw-block ops chunk restore --volume v2 --status-addr STATUS_OF_V2` to start the driver. -3. **v2 serves at once.** It reads chunks it does not hold yet from the source's snapshot. - - Meanwhile the driver fetches every chunk and re-uploads them under v2's own keys. - - It then marks v2 independent: phases `hydrating`, then `owning`, then `independent`. - - Follow it with `sw-block ops chunk restore --volume v2 --status-addr STATUS_OF_V2 --status`. - - Until v2 is independent, a snapshot of v2 is refused (`restore_incomplete`). - - While v2 still fetches chunks, its scheduled snapshots are skipped and counted as `restoring`. After that, until it is independent, they are refused like any snapshot and show as failed attempts with that code. + This creates `v2` from the snapshot and prints one JSON document. It is idempotent by `--request-id` (a generated id is printed when you omit it); reuse it to retry an uncertain result. `--master` is required: it resolves each volume's layout id. +3. **Start v2's blockvolume** with the normal standalone command, its own volume id, endpoints and local root, and the same chunk settings as the source (`--chunk-filer`, `--chunk-path`, `--chunk-control-endpoint`). v2 serves at once. +4. **Reads fill v2.** A block in a chunk that v2 does not hold yet is read from the source's snapshot; the read waits for that chunk, which is then kept locally. There is no background copy: a chunk that is never read stays in the source's snapshot. + - Progress is the volume's count of chunks still absent: `Chunk.Stats.AbsentChunks` in `GET http://STATUS_OF_V2/status/durable?volume=v2` (0 means every chunk is local). + - To make every chunk local, read the whole device once (for example with `dd` to `/dev/null`). + - While any chunk is absent, v2's scheduled snapshots are skipped and counted as `restoring`. +#### Lifetime of a restore target + +- **The source snapshot cannot be deleted** while v2 exists: `ops chunk snapshot-delete` is refused with `snapshot_has_dependents`. Delete v2 first (see [Delete a volume](volume-lifecycle.md#delete-a-volume)); the snapshot can be deleted after that. +- **A snapshot of v2 cannot be restored:** it names the source's chunks, and the restore is refused with `restore_source_not_own`. Restore from the source's snapshot instead. +- **v2's own writes stay in v2:** the source's snapshot never changes. diff --git a/seaweed-block/docs/user-capabilities.md b/seaweed-block/docs/user-capabilities.md index 9ce28691e9..a1d72962e3 100644 --- a/seaweed-block/docs/user-capabilities.md +++ b/seaweed-block/docs/user-capabilities.md @@ -5,7 +5,7 @@ does today, which read-only operations commands exist, and what its status vocabulary means. This page covers Kubernetes block volumes. Agent workspace disks (chunk -snapshots, forks and host moves, a proof of concept) are described in the +snapshots, restores and host moves, a proof of concept) are described in the [README](../README.md#agent-workspace-disks-chunk-lifecycle) and the [standalone deployment](standalone-deployment.md) guide. Feature status is in [Kubernetes status](kubernetes-status.md); the exact release evidence is in diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 7166736875..6b93228b01 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -33,7 +33,7 @@ Snapshots, retention and restore are in | Record | How to read it | What it proves | |---|---|---| | The lease | `sw-block ops workspace show --master MASTER --volume v1`: `replica:`, `epoch:`, `lease state:`, `holder: r1@E` | Which holder blockmaster lets serve. `granted`, `revoking` or `expired` is the host validity at query time, not permission to move | -| HEAD | `sw-block ops chunk show --volume v1 --chunk-filer FILER`: `head.gen`, `head.epoch`, `head.holder`, `head.remoteLSN`, `head.state`, `head.detachedBy` | What any host can start from: every write up to `remoteLSN`. `state` `detached` with `detachedBy` means sealed by that holder | +| HEAD | `sw-block ops chunk show --master MASTER --volume v1 --chunk-filer FILER`: `head.gen`, `head.epoch`, `head.holder`, `head.remoteLSN`, `head.state`, `head.detachedBy` | What any host can start from: every write up to `remoteLSN`. `state` `detached` with `detachedBy` means sealed by that holder | | The ACK | the same `show`: `recorded ACK: r1@E HEAD generation G` | The old holder drained and closed after reading the sealed HEAD G. A clean move needs it | `MASTER` is blockmaster's `--listen` address, `FILER` the SeaweedFS filer gRPC @@ -221,7 +221,7 @@ the volume refuses I/O on this host. Do not go on after any other answer (see the table below). Repeating the command is safe: it answers from the sealed HEAD. -To check: `sw-block ops chunk show --volume v1 --chunk-filer FILER` shows +To check: `sw-block ops chunk show --master MASTER --volume v1 --chunk-filer FILER` shows `head.state` `detached` and `head.detachedBy` `{"holder":"s1/R","epoch":E,"gen":G}`. **4. Revoke**, giving the generation you copied: @@ -392,8 +392,8 @@ sw-block ops workspace show --master MASTER --volume v1 **3. Delete every snapshot of the volume:** ```bash -sw-block ops chunk snapshots --volume v1 --chunk-filer FILER -sw-block ops chunk snapshot-delete --volume v1 --chunk-filer FILER --name s1 +sw-block ops chunk snapshots --master MASTER --volume v1 --chunk-filer FILER +sw-block ops chunk snapshot-delete --master MASTER --volume v1 --chunk-filer FILER --name s1 ``` Each delete answers `{"volumeID":"v1","name":"s1","state":"deleting"}`. @@ -406,7 +406,7 @@ sw-block ops chunk volume-delete --volume v1 --chunk-filer FILER --master MASTER It answers with `"admitted":true,"committed":true,"headMarked":true,"completed":true`. Keep the `--request-id` and use the same one if you have to run the command again. -Afterwards `sw-block ops chunk show --volume v1 --chunk-filer FILER` shows +Afterwards `sw-block ops chunk show --master MASTER --volume v1 --chunk-filer FILER` shows `"state": "deleted"` and `"chunkCount": 0`. **If you sealed and then stopped `blockvolume` with a signal,** the ACK was skipped @@ -425,7 +425,7 @@ follow from that order: the name does not appear in the list, yet another request for that name is refused with `snapshot_exists`, and deleting the volume is refused with `volume v1 has snapshots (NAME); delete them first`. Free it with - `sw-block ops chunk snapshot-delete --volume v1 --chunk-filer FILER --name NAME`, + `sw-block ops chunk snapshot-delete --master MASTER --volume v1 --chunk-filer FILER --name NAME`, or finish it by repeating the request with the same `--request-id`. - **After `outcome_unknown`, repeat the request with the same `--request-id` within 5 minutes.** Later, the unfinished attempt may have been swept, and the request is From 004fd30d354b0a733ca5f53842e2ef6f204a112e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 23:43:57 -0800 Subject: [PATCH 20/29] docs: restored-volume snapshots, release, and three operator rules A restored volume takes no scheduled snapshot until its device has been read once; a manual one names the source's chunks and cannot be restored. ops chunk release is a repair step. The lifecycle rules name one blockmaster per cluster, no restore of its directory from an older copy, and that a deleted volume's name cannot be created again. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/standalone-deployment.md | 5 ++++- seaweed-block/docs/volume-lifecycle.md | 14 ++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index e5672eb7a0..34cde612f1 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -607,10 +607,13 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i 4. **Reads fill v2.** A block in a chunk that v2 does not hold yet is read from the source's snapshot; the read waits for that chunk, which is then kept locally. There is no background copy: a chunk that is never read stays in the source's snapshot. - Progress is the volume's count of chunks still absent: `Chunk.Stats.AbsentChunks` in `GET http://STATUS_OF_V2/status/durable?volume=v2` (0 means every chunk is local). - To make every chunk local, read the whole device once (for example with `dd` to `/dev/null`). - - While any chunk is absent, v2's scheduled snapshots are skipped and counted as `restoring`. + - **A restored volume takes no scheduled snapshot until its whole device has been read once**: while any chunk is absent, each scheduled snapshot is skipped and counted as `restoring`. + - A manual snapshot (`ops chunk snapshot`) is taken in that state too. It names the source's chunks for every chunk v2 has not made local, so, like any snapshot of v2, it cannot be restored (below). #### Lifetime of a restore target - **The source snapshot cannot be deleted** while v2 exists: `ops chunk snapshot-delete` is refused with `snapshot_has_dependents`. Delete v2 first (see [Delete a volume](volume-lifecycle.md#delete-a-volume)); the snapshot can be deleted after that. - **A snapshot of v2 cannot be restored:** it names the source's chunks, and the restore is refused with `restore_source_not_own`. Restore from the source's snapshot instead. - **v2's own writes stay in v2:** the source's snapshot never changes. +- **Deleting v2 releases the source snapshot:** `ops chunk volume-delete` of v2 removes it from the snapshot's dependents. +- **`ops chunk release` is a repair step, not part of this procedure.** `sw-block ops chunk release --master MASTER --source v1 --target v2 --chunk-filer FILER` removes a restore target from its source snapshot's dependents. It works only when the target no longer names the source's chunks (it was deleted), or when the target never got its first HEAD (an interrupted restore). In the second case it first tombstones the target's name, so that name can never be created. A live target is refused with `target_live`. diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 6b93228b01..4d91b3c710 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -161,10 +161,16 @@ These are rules for the operator. The product does not detect every breach. on a fresh one. - **Never revoke before the seal is confirmed** (see the hand-over steps): a revoke without an ACK cannot be undone on one node. -- **Never restore blockmaster's `--authority-store` or `--lifecycle-store` from a copy.** - They decide who may write each volume. An older copy hands out epochs the volumes have - already passed, and every start is then refused. A lost store needs a recovery - procedure, not a restore. +- **Never restore blockmaster's directory from an older copy** (its `--authority-store` + and `--lifecycle-store`). They decide who may write each volume. An older copy hands out + epochs the volumes have already passed, and every start is then refused. A lost store + needs a recovery procedure, not a restore. +- **Run exactly one blockmaster per cluster.** It alone issues each volume's epochs and + leases; there is no second or standby blockmaster in this release. +- **A deleted volume's name cannot be created again.** Its record stays, deleted, and a + create under that name is refused. To start over, create the new volume under another + name. (A snapshot name is different: once its delete has finished, the name can be + taken again.) ## Which procedures run end to end From 1c7d619ded342e74b429c56025e30d6df46a64d7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 25 Nov 2026 23:46:15 -0800 Subject: [PATCH 21/29] docs: an older blockmaster copy can reuse epochs; no promised refusal Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/volume-lifecycle.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/docs/volume-lifecycle.md b/seaweed-block/docs/volume-lifecycle.md index 4d91b3c710..92ea113791 100644 --- a/seaweed-block/docs/volume-lifecycle.md +++ b/seaweed-block/docs/volume-lifecycle.md @@ -162,9 +162,9 @@ These are rules for the operator. The product does not detect every breach. - **Never revoke before the seal is confirmed** (see the hand-over steps): a revoke without an ACK cannot be undone on one node. - **Never restore blockmaster's directory from an older copy** (its `--authority-store` - and `--lifecycle-store`). They decide who may write each volume. An older copy hands out - epochs the volumes have already passed, and every start is then refused. A lost store - needs a recovery procedure, not a restore. + and `--lifecycle-store`). They decide who may write each volume. An older copy can hand + out epochs that were already used; do not do it. A lost store needs a recovery + procedure, not a restore. - **Run exactly one blockmaster per cluster.** It alone issues each volume's epochs and leases; there is no second or standby blockmaster in this release. - **A deleted volume's name cannot be created again.** Its record stays, deleted, and a From 12c1e55e63d8eacf25a3ddc7fe130ea6db43cf5d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:01:51 -0800 Subject: [PATCH 22/29] fix(master): creation ends at the first ready answer or a survivor's write A volume's creation phase ended only at the primary's first ready answer, read by a gate tick. A primary that served right after its stores were attested and died before the next tick left a volume that had acknowledged writes held as creating for good: no gate, no operator failover. Creation now ends, durably and for good, at the first of: - the line's primary answering ready, or - a survivor answering DurableLSN > 0 at the current line (its epoch-table row at the current epoch, or none): under the quorum ack every acknowledged write is on a survivor. A failed write of the end of the store wait keeps the volume held (it is reported as one store awaited) instead of releasing it with no record of its next stage. Tests: the gap through the operator's failover, the first-of rule and its one-way record across a restart, the failed stage write under both gates, the operator's move and a restart, and the primary's awaiting answer alone holding an established volume on both gates and the fenced operator path (each red with its guard removed). Co-Authored-By: Claude Opus 5.5 --- .../host/master/creating_primary_gate_test.go | 4 +- .../core/host/master/creation_phase_test.go | 42 +-- .../host/master/creation_survivor_test.go | 244 ++++++++++++++++++ .../core/host/master/product_loop.go | 92 ++++++- .../core/host/master/store_attestation.go | 35 +-- seaweed-block/docs/design/invariants.md | 2 +- 6 files changed, 358 insertions(+), 61 deletions(-) create mode 100644 seaweed-block/core/host/master/creation_survivor_test.go diff --git a/seaweed-block/core/host/master/creating_primary_gate_test.go b/seaweed-block/core/host/master/creating_primary_gate_test.go index b3379fdf40..b6eebf8ea9 100644 --- a/seaweed-block/core/host/master/creating_primary_gate_test.go +++ b/seaweed-block/core/host/master/creating_primary_gate_test.go @@ -70,7 +70,9 @@ func TestMasterRestartInTheGapDoesNotReassign(t *testing.T) { } h2.Start() defer closeTestMaster(t, h2) - h2.SetPromotionEvidenceProvider(&switchProbe{awaitingEpoch: waitAuthorityLine(t, h2.Publisher(), "vol-rf3").Epoch}) + // The primary still awaits the stores: it served nothing, so no survivor + // holds a write (every end is zero). + h2.SetPromotionEvidenceProvider(&switchProbe{awaitingEpoch: waitAuthorityLine(t, h2.Publisher(), "vol-rf3").Epoch, empty: true}) if inCreationWait(h2) { t.Fatal("fixture: the restarted master still waits for stores") } diff --git a/seaweed-block/core/host/master/creation_phase_test.go b/seaweed-block/core/host/master/creation_phase_test.go index 94ac320dea..fed91b925b 100644 --- a/seaweed-block/core/host/master/creation_phase_test.go +++ b/seaweed-block/core/host/master/creation_phase_test.go @@ -115,7 +115,7 @@ func establishVolume(t *testing.T, h *Host, volumeID string) { t.Fatalf("establish %s: %v", volumeID, err) } h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) // the wait closes - if err := h.attest.noteFirstReady(volumeID); err != nil { // the primary's first ready answer + if _, err := h.attest.noteFirstReady(volumeID); err != nil { // creation ended (the primary's first ready answer) t.Fatalf("establish %s: %v", volumeID, err) } if line, _ := h.Publisher().VolumeAuthorityLine(volumeID); h.inCreationPhase(volumeID, line, nil) != "" { @@ -160,7 +160,7 @@ func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { if established { attestAllStores(t, h) h.attest.awaited("vol-rf3", h.replicaSlotsFor("vol-rf3")) - if err := h.attest.noteFirstReady("vol-rf3"); err != nil { + if _, err := h.attest.noteFirstReady("vol-rf3"); err != nil { t.Fatal(err) } } @@ -195,13 +195,12 @@ func TestCreationPhaseSurvivesAMasterRestart(t *testing.T) { } } -// Creation ends at the primary's first ready answer at its first line, not -// at the last store attestation: a primary restarted after the last -// attestation, before it adopts the complete assignment (it answers not -// ready, and no longer says it awaits the stores), is still creating: no -// fencing round, no reassign. Its first ready answer ends creation, durably, -// and from then on the normal rules apply. -func TestCreationEndsAtThePrimarysFirstReadyAnswer(t *testing.T) { +// Creation does not end at the last store attestation: a primary restarted +// after it, before it adopts the complete assignment (it answers not ready, +// and no longer says it awaits the stores), with no write on any survivor, +// is still creating: no fencing round, no reassign. Creation ends at a +// ready answer or a survivor's write (TestCreationEndsAtTheFirstReadyAnswerOrASurvivorsWrite). +func TestCreationOutlivesTheLastStoreAttestation(t *testing.T) { h := newBootGraceMasterCreating(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) defer closeTestMaster(t, h) attestAllStores(t, h) // every store recorded: the master's wait is over @@ -222,32 +221,17 @@ func TestCreationEndsAtThePrimarysFirstReadyAnswer(t *testing.T) { expectLineStaysR1(t, h, "a restarted primary before its first ready answer") line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") if h.inCreationPhase("vol-rf3", line, nil) == "" { - t.Fatal("creation ended before the primary's first ready answer") - } - p.mu.Lock() - p.currentReady = true // the first ready answer - p.mu.Unlock() - if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { - t.Fatalf("after the first ready answer: still creating (%s)", why) - } - if h.attest.awaitingFirstReady("vol-rf3") { - t.Fatal("the first ready answer was not recorded") - } - p.mu.Lock() - p.currentReady = false // a later not-ready answer reopens nothing - p.mu.Unlock() - if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { - t.Fatalf("creation reopened after it ended (%s)", why) + t.Fatal("creation ended with no write on any survivor") } } -// recordFirstReady records that the volume's primary answered ready at its -// first line (after its stores were attested): fixtures whose primary was -// healthy before the scenario's failure. +// recordFirstReady records the end of creation (after the stores were +// attested), as the primary's first ready answer does: fixtures whose +// primary was healthy before the scenario's failure. func recordFirstReady(t *testing.T, h *Host, volumeID string) { t.Helper() h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)) - if err := h.attest.noteFirstReady(volumeID); err != nil { + if _, err := h.attest.noteFirstReady(volumeID); err != nil { t.Fatal(err) } } diff --git a/seaweed-block/core/host/master/creation_survivor_test.go b/seaweed-block/core/host/master/creation_survivor_test.go new file mode 100644 index 0000000000..5b3c23e9df --- /dev/null +++ b/seaweed-block/core/host/master/creation_survivor_test.go @@ -0,0 +1,244 @@ +package master + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// restartCreatingMaster closes h and starts a master on the same stores, +// with a fresh switchProbe (r1 not ready, r2 ready holding DurableLSN 70). +func restartCreatingMaster(t *testing.T, h *Host, cfg Config) *Host { + t.Helper() + closeTestMaster(t, h) + cfg.Listen = "127.0.0.1:0" + cfg.ControllerConfig.ExpectedSlotsPerVolume = 3 + cfg.Freshness.FreshnessWindow = testFreshness + cfg.Freshness.PendingGrace = time.Millisecond + h2, err := New(cfg) + if err != nil { + t.Fatalf("master restart: %v", err) + } + h2.Start() + h2.SetPromotionEvidenceProvider(&switchProbe{}) + return h2 +} + +// operatorProbe is a switchProbe with the sync-quorum profile the +// operator's move reads from its gate. +type operatorProbe struct{ *switchProbe } + +func (operatorProbe) AckProfile() string { return "sync_quorum" } + +// withOperatorProbe installs p behind the operator's ack profile. +func withOperatorProbe(h *Host, p *switchProbe) { h.SetPromotionEvidenceProvider(operatorProbe{p}) } + +// The gap the creation phase must not open: every store is attested, the +// primary serves at once and a write is acknowledged by the quorum (r2 +// holds it: DurableLSN 70), and the primary dies before any gate tick could +// read a ready answer from it. The volume served, so it is not creating: +// the operator's failover moves it (decided on the fencing round). Without +// a write on any survivor (it served nothing), it is still creating and +// the failover is refused. +func TestAVolumeWhosePrimaryDiedAfterAQuorumWriteFailsOver(t *testing.T) { + for _, wrote := range []bool{true, false} { + t.Run(map[bool]string{true: "a survivor holds the write", false: "no write anywhere"}[wrote], func(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{}) + defer closeTestMaster(t, h) + attestAllStores(t, h) // stage 2: the primary may serve now + p := probeOf(t, h) + p.mu.Lock() + p.currentUnknown = true // the primary is gone: it never answers + p.empty = !wrote + p.mu.Unlock() + withOperatorProbe(h, p) + ingestRF3Incarnations(t, h, silent, readySlot("r2-a"), readySlot("r3-a")) + _, err := h.plannedMoveEvidence("vol-rf3", "r2") + if wrote { + if err != nil { + t.Fatalf("the operator's failover after a quorum-acknowledged write: %v", err) + } + if h.attest.awaitingFirstReady("vol-rf3") { + t.Fatal("the survivor's write did not end creation durably") + } + return + } + if err != ErrMoveWhileCreating { + t.Fatalf("a volume no survivor holds a write of: err=%v; want ErrMoveWhileCreating", err) + } + }) + } +} + +// Creation ends at the first of the primary's ready answer and a +// survivor's answer that it holds a write of the current line; until then +// (stores attested, a not-ready primary, empty survivors) it is creating. +// Ending is one-way and durable. +func TestCreationEndsAtTheFirstReadyAnswerOrASurvivorsWrite(t *testing.T) { + for _, by := range []string{"the primary's ready answer", "a survivor's write"} { + t.Run(by, func(t *testing.T) { + cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir()} + h := newBootGraceMasterCreating(t, cfg) + attestAllStores(t, h) + p := probeOf(t, h) + p.mu.Lock() + p.empty = true // a not-ready primary, nothing on any survivor + p.mu.Unlock() + line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if h.inCreationPhase("vol-rf3", line, nil) == "" { + t.Fatal("creation ended with a not-ready primary and empty survivors") + } + // Neither a survivor's row at another epoch nor the primary's own + // DurableLSN ends it. + for _, c := range []PromotionCandidateEvidence{{ReplicaID: "r2", DurableLSN: 9, LastDataEpoch: line.Epoch + 1}, {ReplicaID: "r1", DurableLSN: 9}} { + if h.inCreationPhase("vol-rf3", line, &PromotionProbeResult{Candidates: []PromotionCandidateEvidence{c}}) == "" { + t.Fatalf("creation ended on %+v", c) + } + } + p.mu.Lock() + if by == "a survivor's write" { + p.empty = false // r2 answers DurableLSN 70; r1 still not ready + } else { + p.currentReady = true // a Healthy volume that never took a write + } + p.mu.Unlock() + if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { + t.Fatalf("after %s: still creating (%s)", by, why) + } + p.mu.Lock() + p.empty, p.currentReady = true, false // later answers reopen nothing + p.mu.Unlock() + if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { + t.Fatalf("creation reopened after it ended (%s)", why) + } + h2 := restartCreatingMaster(t, h, cfg) + defer closeTestMaster(t, h2) + pr := probeOf(t, h2) + pr.mu.Lock() + pr.empty = true + pr.mu.Unlock() + if why := h2.inCreationPhase("vol-rf3", waitAuthorityLine(t, h2.Publisher(), "vol-rf3"), nil); why != "" { + t.Fatalf("after a restart the ended creation is back (%s)", why) + } + }) + } +} + +// When the write that ends the store wait fails, the volume stays held (as +// waiting) and nothing replaces it: no probe, no fencing round, no move, +// also after a restart; once the write succeeds the normal stages follow. +func TestAFailedEndOfTheStoreWaitKeepsTheVolumeHeld(t *testing.T) { + cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), + ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}} + h := newBootGraceMasterCreating(t, cfg) + line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + // Every store recorded, but the record's next write fails: a directory + // stands at its temp path. + if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": testStoreID, "r2": testStoreID, "r3": testStoreID})); err != nil { + t.Fatal(err) + } + block := filepath.Join(cfg.AuthorityStoreDir, storeAttestationFile+".tmp") + if err := os.Mkdir(block, 0o755); err != nil { + t.Fatal(err) + } + time.Sleep(250 * time.Millisecond) // past the boot grace + dead := restarting + dead.eligible = false + for i := 0; i < 2; i++ { + if why := h.inCreationPhase("vol-rf3", line, nil); why == "" { + t.Fatal("a failed write of the end of the store wait released the volume") + } + creatingTick(t, h, dead) + expectLineStaysR1(t, h, "the end of the store wait not recorded") + if _, err := h.plannedMoveEvidence("vol-rf3", "r2"); err != ErrMoveWhileCreating { + t.Fatalf("operator move: err=%v; want ErrMoveWhileCreating", err) + } + } + if h.attest.awaitingFirstReady("vol-rf3") { + t.Fatal("memory moved to stage 2 without the write") + } + h = restartCreatingMaster(t, h, cfg) + if why := h.inCreationPhase("vol-rf3", line, nil); why == "" { + t.Fatal("after a restart the unrecorded end released the volume") + } + if err := os.Remove(block); err != nil { + t.Fatal(err) + } + // The write succeeds: stage 2, ended at once by r2's write (DurableLSN 70). + if why := h.inCreationPhase("vol-rf3", line, nil); why != "" { + t.Fatalf("after the write succeeded: still creating (%s)", why) + } + closeTestMaster(t, h) +} + +// The primary's own answer alone holds a volume whose master record holds +// nothing (an established volume): its assignment at the current epoch +// still awaits the stores. The matching epoch holds on both gates and the +// operator's fenced path; a stale epoch holds nothing (the controls that +// the fixture would move). Removing the answer guard fails the holds. +func TestThePrimarysAwaitingAnswerAloneHoldsAnEstablishedVolume(t *testing.T) { + for _, matching := range []bool{true, false} { + name := map[bool]string{true: "matching epoch", false: "stale epoch"}[matching] + setup := func(t *testing.T) (*Host, *switchProbe) { + h := newBootGraceMaster(t, Config{ControllerConfig: authority.TopologyControllerConfig{PrimaryBootGrace: 200 * time.Millisecond}}) + if h.attest.awaitingFirstReady("vol-rf3") || inCreationWait(h) { + t.Fatal("fixture: the record still holds the volume") + } + p := probeOf(t, h) + epoch := waitAuthorityLine(t, h.Publisher(), "vol-rf3").Epoch + if !matching { + epoch++ + } + p.mu.Lock() + p.awaitingEpoch = epoch + p.mu.Unlock() + time.Sleep(250 * time.Millisecond) // past the boot grace + return h, p + } + t.Run("unsupported gate/"+name, func(t *testing.T) { + h, _ := setup(t) + defer closeTestMaster(t, h) + ineligible := restarting + ineligible.eligible = false + unsupportedTick(t, h, ineligible) + if matching { + expectLineStaysR1(t, h, "the primary's awaiting answer") + return + } + expectFailoverToR2(t, h, "a stale awaiting answer") + }) + t.Run("supported gate/"+name, func(t *testing.T) { + h, p := setup(t) + defer closeTestMaster(t, h) + supportedCreatingTick(t, h, rf3Slot{incarnation: "r1-a", reachable: true, eligible: true}) + p.mu.Lock() + fences := p.fenceCalls + p.mu.Unlock() + line, _ := h.Publisher().VolumeAuthorityLine("vol-rf3") + moved := fences > 0 || line.ReplicaID != "r1" + if matching && moved { + t.Fatalf("the primary's awaiting answer: fences=%d line=%+v", fences, line) + } + if !matching && !moved { + t.Fatal("control: a stale awaiting answer took no replacement decision") + } + }) + t.Run("operator's fenced path/"+name, func(t *testing.T) { + h, p := setup(t) + defer closeTestMaster(t, h) + withOperatorProbe(h, p) + ingestRF3Incarnations(t, h, silent, readySlot("r2-a"), readySlot("r3-a")) // the primary unreachable: the fenced path + _, err := h.plannedMoveEvidence("vol-rf3", "r2") + if matching && err != ErrMoveWhileCreating { + t.Fatalf("err=%v; want ErrMoveWhileCreating", err) + } + if !matching && err == ErrMoveWhileCreating { + t.Fatal("control: a stale awaiting answer refused the move as creating") + } + }) + } +} diff --git a/seaweed-block/core/host/master/product_loop.go b/seaweed-block/core/host/master/product_loop.go index 7699250c2e..f70b3deca6 100644 --- a/seaweed-block/core/host/master/product_loop.go +++ b/seaweed-block/core/host/master/product_loop.go @@ -1103,28 +1103,42 @@ func (h *Host) freshCurrentSlot(volumeID, replicaID string) (authority.ReplicaCa // inCreationPhase is the one decision of the creation phase, which every // replacement entry (both promotion gates, the operator's move and planned // move, the rebalance through the gate) calls first: it returns why the -// volume is creating, or "" once it is not. Two sources, in order: -// - the master's own durable record: it still awaits a replica store, or -// every store is attested but the primary has not yet answered ready at -// its first line (its first ready answer ends creation, recorded durably -// and for good; no other state); -// - the current primary's own answer, when one was read, says its -// assignment at this line's epoch still awaits the stores (the master's -// wait may be over before the re-sent assignment arrives). The answer -// can only hold a volume, never release one. +// volume is creating, or "" once creation ended. A replacement acts only on +// ended: one durable, one-way fact in the master's record, written by the +// first of +// - the line's primary answering ready (its first Healthy), or +// - a survivor answering DurableLSN > 0 at the current line (under the +// quorum ack every acknowledged write is on a survivor, so a volume +// that served and lost its primary before the master read a ready +// answer still ends creation and fails over), +// once every initial store is attested (stage 1 holds whatever is +// answered). Nothing clears it. Besides, the current +// primary's own answer, when one was read, holds the volume while its +// assignment at this line's epoch still awaits the stores (the master's +// wait may be over before the re-sent assignment arrives); an answer can +// only hold a volume, never release one. func (h *Host) inCreationPhase(volumeID string, current authority.AuthorityBasis, answer *PromotionProbeResult) string { if h.attest != nil { if waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)); waiting > 0 { return "the master's record awaits replica stores" } if h.attest.awaitingFirstReady(volumeID) { - if !h.firstReadyNow(volumeID, current, answer) { - return "the primary has not yet answered ready at its first line" + by := "" + if h.firstReadyNow(volumeID, current, answer) { + by = "primary " + current.ReplicaID + " answered ready" + } else if holder, ok := h.survivorHoldingAWrite(volumeID, current, answer); ok { + by = "survivor " + holder + " holds a write" + } else { + return "neither a ready answer of the primary nor a write on a survivor yet" } - if err := h.attest.noteFirstReady(volumeID); err != nil { - return "the first ready answer could not be recorded: " + err.Error() + ended, err := h.attest.noteFirstReady(volumeID) + if err != nil { + return "the end of creation could not be recorded: " + err.Error() } - h.log.Printf("blockmaster: volume=%s creation complete: primary %s answered ready at epoch %d", volumeID, current.ReplicaID, current.Epoch) + if !ended { + return "creation may not end now" + } + h.log.Printf("blockmaster: volume=%s creation complete: %s at %s@%d", volumeID, by, current.ReplicaID, current.Epoch) } } if answer != nil && answer.CurrentKnown && current.Epoch != 0 && answer.Current.AwaitingReplicaStoresEpoch == current.Epoch { @@ -1157,6 +1171,56 @@ func (h *Host) firstReadyNow(volumeID string, current authority.AuthorityBasis, return res.CurrentKnown && res.Current.ReplicaID == current.ReplicaID && res.Current.Ready && res.Current.AwaitingReplicaStoresEpoch == 0 } +// survivorHoldingAWrite: a survivor (any replica but the line's own) answers, +// in a probe of the current line, DurableLSN > 0 with its epoch-table row at +// the current epoch (or no row). It reads the answer given, else a round of +// the survivors alone. It names the survivor. +func (h *Host) survivorHoldingAWrite(volumeID string, current authority.AuthorityBasis, answer *PromotionProbeResult) (string, bool) { + if !current.Assigned || current.ReplicaID == "" { + return "", false + } + res := answer + if res == nil { + h.promotionMu.RLock() + prober := h.promotionProber + h.promotionMu.RUnlock() + if prober == nil { + return "", false + } + r, err := prober.ProbePromotionCandidates(volumeID, current, h.survivorCandidates(volumeID, current.ReplicaID)) + if err != nil { + return "", false + } + res = &r + } + for _, c := range res.Candidates { + if c.ReplicaID == "" || c.ReplicaID == current.ReplicaID { + continue + } + if c.DurableLSN > 0 && (c.LastDataEpoch == 0 || c.LastDataEpoch == current.Epoch) { + return c.ReplicaID, true + } + } + return "", false +} + +// survivorCandidates are the volume's replicas other than the line's own, +// each from its fresh heartbeat slot when it has one. +func (h *Host) survivorCandidates(volumeID, currentReplica string) []authority.ReplicaCandidate { + var out []authority.ReplicaCandidate + for _, id := range h.replicaSlotsFor(volumeID) { + if id == currentReplica { + continue + } + c, ok := h.freshCurrentSlot(volumeID, id) + if !ok { + c = authority.ReplicaCandidate{ReplicaID: id} + } + out = append(out, c) + } + return out +} + // answerOf is the probe's answer, or nil when the probe gave none. func answerOf(result PromotionProbeResult, ok bool) *PromotionProbeResult { if !ok { diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 819b441f60..c69e7c1ec1 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -31,11 +31,12 @@ type attestedStores struct { // meanwhile is not waited for); it is cleared, for good, the first time // every current replica has a recorded store. Initial []string `json:"initial,omitempty"` - // AwaitingFirstReady: every initial store is attested, but the volume's - // primary has not yet answered ready at its first line (first Healthy). - // Set in the same write that clears Initial, cleared for good by the - // first ready answer: creation ends there. A record written before this - // field existed has none, so an established volume is never reopened. + // AwaitingFirstReady: every initial store is attested, but creation has + // not ended: neither has the primary answered ready nor a survivor + // answered that it holds a write of the current line. Set in the same + // write that clears Initial, cleared for good by the first of the two + // (creation ended). A record written before this field existed has none, + // so an established volume is never reopened. AwaitingFirstReady bool `json:"awaiting_first_ready,omitempty"` } @@ -166,17 +167,19 @@ func (s *storeAttestations) awaited(volumeID string, current []string) (waiting, v.AwaitingFirstReady = true // creation ends at the primary's first ready answer vols[volumeID] = v if err := s.persist(vols); err != nil { - // Not cleared: the volume keeps answering from its stores (nothing - // awaited); the next call retries the write. - return 0, len(current) + // Not recorded: the volume stays in its wait (reported as one store + // awaited) until the end of the wait is durable; the next call + // retries the write. Releasing it here would end creation with no + // durable record of its next stage. + return 1, len(current) } s.vols = vols s.notifyLocked(volumeID) return 0, len(current) } -// awaitingFirstReady: the volume's stores are all attested and its primary -// has not yet answered ready at its first line. +// awaitingFirstReady: the volume's stores are all attested and its creation +// has not ended. func (s *storeAttestations) awaitingFirstReady(volumeID string) bool { s.mu.Lock() defer s.mu.Unlock() @@ -184,14 +187,14 @@ func (s *storeAttestations) awaitingFirstReady(volumeID string) bool { return had && v.AwaitingFirstReady } -// noteFirstReady records, durably and for good, that the volume's primary -// answered ready at its first line: its creation is complete. -func (s *storeAttestations) noteFirstReady(volumeID string) error { +// noteFirstReady records, durably and for good, that the volume's creation +// ended. It reports whether creation has ended (false: it may not end now). +func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { s.mu.Lock() defer s.mu.Unlock() v, had := s.vols[volumeID] if !had || !v.AwaitingFirstReady { - return nil + return true, nil } vols := make(map[string]attestedStores, len(s.vols)) for k, x := range s.vols { @@ -200,11 +203,11 @@ func (s *storeAttestations) noteFirstReady(volumeID string) error { v.AwaitingFirstReady = false vols[volumeID] = v if err := s.persist(vols); err != nil { - return err + return false, err } s.vols = vols s.notifyLocked(volumeID) - return nil + return true, nil } // record merges att into the volume's record, in one write: each replica it diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 37fcfd0ad1..44d23bc377 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -958,7 +958,7 @@ Notes: | `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | | `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | | `INV-PROMOTE-FRONTIER-001` | With a known required acknowledgement frontier under `sync_quorum` or `sync_all`, the RF=3 promotion gate allows only probed-ready candidates whose durable LSN is at least the required LSN. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `applyPromotionEvidenceGate`; `core/host/master/probe_round.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe` (`core/host/master/product_loop_test.go`); `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase, ending at the line's primary's first ready answer (recorded durably, for good): before it, or while the primary answers that it awaits replica stores, no replacement decision is made (reassign, fencing round, heal, operator move, rebalance); checked first. | CreatePromo model (VolumeCreate x Promotion) | `core/host/master/product_loop.go` `inCreationPhase`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent`, `TestCreationEndsAtThePrimarysFirstReadyAnswer`, `TestCreatingVolumeRefusesTheOperatorsMove`, `TestCreationPhaseSurvivesAMasterRestart` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | +| `INV-PROMOTE-CREATION-WAIT-001` | Creation is its own phase, ended durably and for good by the first of: the line's primary's ready answer, or a survivor answering DurableLSN > 0 at the line. Until then, or while the primary answers it awaits replica stores, no replacement decision is made; checked first. | CreateEvid2 model (VolumeCreate x Promotion, survivor evidence) | `core/host/master/product_loop.go` `inCreationPhase`, `firstReadyNow`, `survivorHoldingAWrite`, `holdCreating`, `applyPromotionEvidenceGate`, `applyUnsupportedPromotionEvidenceGate`; `core/host/master/planned_move.go` `plannedMoveEvidence`; `core/host/master/store_attestation.go` `awaited`; `core/host/volume/probe_round.go` `probeAnswer` | `TestCreatingVolumeRunsNoFencingRoundOnTheSupportedGate`, `TestCreatingVolumeIsNotReplacedWhenItsPrimaryIsSilent`, `TestCreationOutlivesTheLastStoreAttestation`, `TestCreatingVolumeRefusesTheOperatorsMove`, `TestCreationPhaseSurvivesAMasterRestart` (`core/host/master/creation_phase_test.go`); `TestPrimaryAwaitingReplicaStoresIsNotReplacedForNotReady`, `TestMasterRestartInTheGapDoesNotReassign`, `TestCreatingPrimaryNotReadyForAnotherReasonIsNotReplaced`, `TestCreatingVolumeWithAStaleAwaitingAnswerIsNotReplaced`, `TestCreatingPrimaryWithAnUnacceptableSlotIsNotReplaced` (`core/host/master/creating_primary_gate_test.go`); `TestAVolumeWhosePrimaryDiedAfterAQuorumWriteFailsOver`, `TestCreationEndsAtTheFirstReadyAnswerOrASurvivorsWrite`, `TestAFailedEndOfTheStoreWaitKeepsTheVolumeHeld`, `TestThePrimarysAwaitingAnswerAloneHoldsAnEstablishedVolume` (`core/host/master/creation_survivor_test.go`); `TestAVolumeThatServedBeforeItsFirstGateTickFailsOver` (`cmd/blockvolume/creation_gap_integration_test.go`, tagged); `TestProbeRound_CarriesThePrimarysAwaitingStoresEpoch` (`core/host/master/probe_round_test.go`); `TestProbeAnswerReadsTheWaitBeforeReadiness`, `TestProbeAnswerAfterTheWaitNamesNothing` (`core/host/volume/replica_stores_wait_test.go`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-PROBE-001` | For a replicated volume (two or more slots), the gate allows no candidate unless this tick's promotion probe succeeded with a known ack profile. | M3 Supporting → promotion candidate (the gate, RF=2 and up) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas` | `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe` (`core/host/master/product_loop_test.go`); `TestMountedFailover_ProductLoopRF2DecidesOnThePromotionGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | | `INV-PROMOTE-UNKNOWN-CURRENT-001` | A current primary whose status cannot be read (probe refused, timed out, pod gone) is unknown, never failed: no promotion path reassigns on it; a direct reassign needs the primary's own not-ready report. | M3 Primary → promotion candidate (both promotion paths) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate` (supported path), `applyUnsupportedPromotionEvidenceGate` (unsupported path) | `TestUnsupportedPathNeverReassignsOnAnUnansweredPrimary` (`core/host/master/primary_boot_grace_gate_test.go`); `TestMountedFailover_ProductLoopRF3DoesNotReassignWhenCurrentSlotMissing` (`core/host/master/product_loop_test.go`). Limits: Kubernetes alpha failover on node or pod loss is a manual admin action in this release; the admin's failover runs the fencing round and publishes only on its decision (basis Fenced) when the primary is unreachable (no fresh, reachable heartbeat; any replica count); a reachable RF3 `sync_quorum` primary's move stays refused (it needs a seal) and `best_effort` stays refused (`core/host/master/planned_move.go` `fencedMoveEvidence`; `TestManualFailoverRF3SyncQuorumDecidesOnTheFencingRound`, `TestManualFailoverRF2UnreachablePrimaryDecidesOnTheFencingRound`, `TestManualFailoverRF2BestEffortIsNeverFenced`, `TestManualFailoverRF3ReachablePrimaryIsRefused`, `TestManualFailoverAndThePromotionLoopPublishOneLine`) | — | ACTIVE | | `INV-PROMOTE-FRONTIER-UNKNOWN-001` | With an unknown frontier under `sync_quorum` or `sync_all`, the gate allows the highest-durable ready candidate only if at least N_peers-K+1 of the N_peers peers are probed ready this tick and have a fresh heartbeat (K as in `waitForSyncAcks`); else none. | M3 Supporting → promotion candidate (RF=3 gate) | `core/host/master/product_loop.go` `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/replication/async_ack.go` `waitForSyncAcks` | `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | From e8c55183c9b9d7d0486deeb244bda7d426ffb1c1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:01:51 -0800 Subject: [PATCH 23/29] test(blockvolume): a volume that served before its first gate tick fails over Through the production binaries: an RF3 sync-quorum primary serves and acknowledges a write after its stores are attested and is killed before the next product tick (30 s loop); the survivors' write ends creation, the gate fails the volume over and the write reads back on the new primary. The test checks that the window really occurred. Co-Authored-By: Claude Opus 5.5 --- .../creation_gap_integration_test.go | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/creation_gap_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/creation_gap_integration_test.go b/seaweed-block/cmd/blockvolume/creation_gap_integration_test.go new file mode 100644 index 0000000000..b2c1bd79dc --- /dev/null +++ b/seaweed-block/cmd/blockvolume/creation_gap_integration_test.go @@ -0,0 +1,103 @@ +//go:build subprocess && chunkstore_integration + +package main_test + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// TestAVolumeThatServedBeforeItsFirstGateTickFailsOver is the creation +// phase's gap, through the production binaries: an RF3 sync-quorum volume +// whose primary serves and acknowledges a write right after its stores are +// attested, and dies before the master's next product tick could read a +// ready answer from it. The volume served, so its creation ended (the +// survivors hold the write): the gate fails it over, and the write reads +// back on the new primary. A master that ended creation only at the +// primary's ready answer would hold this volume as creating for good. +// +// The product loop ticks every 30 s, so the tick that binds the line and the +// next one leave a window the test uses (and checks it did). +func TestAVolumeThatServedBeforeItsFirstGateTickFailsOver(t *testing.T) { + bins := buildG54Binaries(t) + h := &plannedHandoffHarness{dir: t.TempDir(), t: t} + h.masterAddr = handoffAddress(t) + type host struct { + id, rid, data, ctrl, status, nvme, root string + d *daemon + } + hosts := make([]*host, 3) + var nodes, placements strings.Builder + for i := range hosts { + id := fmt.Sprintf("s%d", i+1) + hosts[i] = &host{id: id, rid: fmt.Sprintf("r%d", i+1), data: handoffAddress(t), ctrl: handoffAddress(t), status: handoffAddress(t), nvme: handoffAddress(t), root: filepath.Join(h.dir, "vol-"+id)} + fmt.Fprintf(&nodes, " - server_id: %s\n data_addr: %s\n ctrl_addr: %s\n", id, hosts[i].data, hosts[i].ctrl) + fmt.Fprintf(&placements, " - server_id: %s\n replica_id: %s\n", id, hosts[i].rid) + } + spec := filepath.Join(h.dir, "cluster-spec.yaml") + if err := os.WriteFile(spec, []byte("nodes:\n"+nodes.String()+"volumes:\n - id: v1\n size_bytes: 268435456\n replication_factor: 3\n placements:\n"+placements.String()), 0o644); err != nil { + t.Fatal(err) + } + master := h.start(t, "blockmaster", bins.master, + "--authority-store", filepath.Join(h.dir, "master", "authority"), "--lifecycle-store", filepath.Join(h.dir, "master", "lifecycle"), + "--cluster-spec", spec, "--expected-slots-per-volume", "3", "--lifecycle-product-loop-interval", "30s", + "--freshness-window", "2s", "--launcher-replication-ack", "sync-quorum", "--listen", h.masterAddr) + master.waitLog(t, 30*time.Second, "blockmaster: lock acquired") + for _, b := range hosts { + lockDir := b.root + ".locks" + if err := os.MkdirAll(lockDir, 0o700); err != nil { + t.Fatal(err) + } + b.d = h.start(t, "blockvolume-"+b.id, bins.volume, "--volume-lock-dir-test-only", lockDir, "--master", h.masterAddr, + "--server-id", b.id, "--volume-id", "v1", "--replica-id", b.rid, "--data-addr", b.data, "--ctrl-addr", b.ctrl, + "--status-addr", b.status, "--durable-root", b.root, "--durable-impl", "walstore", "--durable-blocks", "65536", + "--durable-blocksize", "4096", "--heartbeat-interval", "200ms", "--t1-readiness", "--replication-ack", "sync-quorum", + "--nvme-listen", b.nvme, "--nvme-subsysnqn", plannedHandoffNQN) + } + ended := func() bool { return master.has("blockmaster: volume=v1 creation complete") } + + // 1. r1 serves at epoch 1 with both replicas counted (its stores are + // attested); block A is written and flushed (acknowledged by the quorum). + p1, survivors := hosts[0], hosts[1:] + h.waitPrimaryAt(t, p1.status, 1) + waitPeersHealthyAt(t, p1.status, 1, survivors[0].rid, survivors[1].rid) + acked := bytes.Repeat([]byte{0xa1}, 4096) + c := dialNVMe(t, p1.nvme, plannedHandoffNQN) + c.write(t, 0, acked) + c.flush(t) // the acknowledgement + c.close() + + // 2. r1 dies before any tick read a ready answer from it. + if ended() { + t.Fatal("fixture: a tick ended creation before the primary died (the window this test needs did not occur)") + } + p1.d.kill(t) + + // 3. The next tick reads the survivors' write: creation ended, and the + // gate fails the volume over. + var p2 *host + poll(t, 120*time.Second, "no survivor became primary at epoch 2 (the volume held as creating?)", func() bool { + for _, b := range survivors { + if statusIsPrimaryAt(b.status, 2) { + p2 = b + return true + } + } + return false + }) + if !master.has("creation complete: survivor") { + t.Fatal("creation did not end on the survivors' write") + } + + // 4. The acknowledged write reads back on the new primary. + r := dialNVMe(t, p2.nvme, plannedHandoffNQN) + defer r.close() + if got := r.read(t, 0, len(acked)); !bytes.Equal(got, acked) { + t.Fatalf("the acknowledged write did not read back on %s", p2.rid) + } +} From d6aa32ce58695ce1a999a64dcce362b40444dc36 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:03:35 -0800 Subject: [PATCH 24/29] fix(master): a delete without the holder's ack finishes only on proof the volume is empty The never-created delete was admitted for any creation-hold reason, including a volume whose primary had acknowledged writes before the master recorded anything. Now: - it is admitted only while creation has not ended, and the master's record is marked durably first, in the lock that ends creation, so creation never ends after the admission (the delete reads the record as it was admitted, also after a restart); - deleting HEAD waits out the holder's lease horizon as before, and then requires proof that the volume is empty, read after the horizon: stage 1 (not every store attested: the primary served nothing), or N-K+1 survivors that answered on valid tables at end 0. A survivor holding a write, a silent survivor or an unknown ack profile refuses; - a volume whose creation ended keeps the live-lease refusal. Part A (M2) and the ledger row INV-WS-DELETE-WITHOUT-ACK-001 name the rule. Co-Authored-By: Claude Opus 5.5 --- .../master/primary_boot_grace_gate_test.go | 15 +- .../core/host/master/store_attestation.go | 48 ++++++- .../host/master/volume_delete_authority.go | 83 +++++++++-- .../master/workspace_delete_proof_test.go | 129 ++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 + 5 files changed, 264 insertions(+), 13 deletions(-) create mode 100644 seaweed-block/core/host/master/workspace_delete_proof_test.go diff --git a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go index 675077bf65..c2ebfd40cb 100644 --- a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go +++ b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go @@ -78,6 +78,9 @@ type switchProbe struct { // awaitingEpoch: the current primary answers that it is not ready only // because its assignment at this epoch awaits replica stores (0: no). awaitingEpoch uint64 + // tableValid: the survivors' answers are read on valid epoch tables + // (evidence a delete's proof counts); r3Silent: r3 gives no valid answer. + tableValid, r3Silent bool // When hold is set, a probe signals entered and then blocks until // release is closed. hold bool @@ -108,13 +111,21 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit p.mu.Lock() } defer p.mu.Unlock() + res := p.answerLocked() + for i := range res.Candidates { + res.Candidates[i].TableValid = p.tableValid && !(p.r3Silent && res.Candidates[i].ReplicaID == "r3") + } + return res, nil +} + +func (p *switchProbe) answerLocked() PromotionProbeResult { if p.empty { return PromotionProbeResult{ AckProfile: "sync-quorum", CurrentKnown: !p.currentUnknown, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, AwaitingReplicaStoresEpoch: p.awaitingEpoch}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true}, {ReplicaID: "r3"}}, - }, nil + } } return PromotionProbeResult{ AckProfile: "sync-quorum", @@ -124,7 +135,7 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit CurrentKnown: !p.currentUnknown, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, AwaitingReplicaStoresEpoch: p.awaitingEpoch, DurableLSN: 70}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}, {ReplicaID: "r3", DurableLSN: p.lagEnd()}}, - }, nil + } } func (p *switchProbe) lagEnd() uint64 { diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index c69e7c1ec1..6f15df49e4 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -38,6 +38,11 @@ type attestedStores struct { // (creation ended). A record written before this field existed has none, // so an established volume is never reopened. AwaitingFirstReady bool `json:"awaiting_first_ready,omitempty"` + // DeleteWithoutAck: a delete without the holder's acknowledgement was + // admitted while the volume was creating (written before the delete's + // reservation). Creation never ends after it, and the delete finishes + // only on proof that the volume is empty (Host.provenEmptyForDelete). + DeleteWithoutAck bool `json:"delete_without_ack,omitempty"` } // storeAttestations is the master's record of which store each replica @@ -188,7 +193,8 @@ func (s *storeAttestations) awaitingFirstReady(volumeID string) bool { } // noteFirstReady records, durably and for good, that the volume's creation -// ended. It reports whether creation has ended (false: it may not end now). +// ended. It reports whether creation has ended: false when a delete without +// the holder's acknowledgement was admitted first (it may not end now). func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { s.mu.Lock() defer s.mu.Unlock() @@ -196,6 +202,9 @@ func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { if !had || !v.AwaitingFirstReady { return true, nil } + if v.DeleteWithoutAck { + return false, nil // the delete reads the record as it was admitted + } vols := make(map[string]attestedStores, len(s.vols)) for k, x := range s.vols { vols[k] = x @@ -210,6 +219,43 @@ func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { return true, nil } +// markDeleteWithoutAck admits, durably, a delete without the holder's +// acknowledgement of a volume whose creation has not ended, in the same +// lock as noteFirstReady: creation cannot end between the check and the +// mark. false: creation ended (or the volume never waited): the ordinary +// delete applies. +func (s *storeAttestations) markDeleteWithoutAck(volumeID string) (bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + v, had := s.vols[volumeID] + if !had || len(v.Initial) == 0 && !v.AwaitingFirstReady { + return false, nil + } + if v.DeleteWithoutAck { + return true, nil + } + vols := make(map[string]attestedStores, len(s.vols)) + for k, x := range s.vols { + vols[k] = x + } + v.DeleteWithoutAck = true + vols[volumeID] = v + if err := s.persist(vols); err != nil { + return false, err + } + s.vols = vols + s.notifyLocked(volumeID) + return true, nil +} + +// deleteWithoutAck: a delete without the holder's acknowledgement was +// admitted for the volume. +func (s *storeAttestations) deleteWithoutAck(volumeID string) bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.vols[volumeID].DeleteWithoutAck +} + // record merges att into the volume's record, in one write: each replica it // names gets that store as its reference; a replica it does not name keeps // its last one. An attestation from a lower epoch than the recorded one is diff --git a/seaweed-block/core/host/master/volume_delete_authority.go b/seaweed-block/core/host/master/volume_delete_authority.go index 34e0729a13..b3b54c4d2a 100644 --- a/seaweed-block/core/host/master/volume_delete_authority.go +++ b/seaweed-block/core/host/master/volume_delete_authority.go @@ -3,6 +3,7 @@ package master import ( "context" "errors" + "fmt" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/lifecycle" @@ -36,16 +37,22 @@ func (a *volumeDeleteAuthority) Reserve(ctx context.Context) error { _, err := h.lifecycle.Deletions.Commit(a.volume, a.token) return err } - // A volume whose creation never completed (the master's durable record - // still awaits a replica store) is deleted without its holder: a live - // lease does not refuse the reservation, which stops every grant; the - // HEAD update still waits for no live lease. A volume that ever completed - // creation keeps the live-lease refusal. - // The line, so a primary that has just answered ready is recorded - // (creation complete) before the delete is decided. + // The delete without the holder's acknowledgement (a live lease does + // not refuse the reservation, which stops every grant) is admitted only + // while creation has not ended, recorded durably before the reservation + // so creation never ends after it; it finishes only on proof that the + // volume is empty (NoLiveLease). A volume whose creation ended keeps the + // live-lease refusal. The line, so a ready answer or a survivor's write + // read now ends creation before the delete is decided. line, _ := h.Publisher().VolumeAuthorityLine(a.volume) - if h.inCreationPhase(a.volume, line, nil) != "" { - return h.Publisher().ReserveNeverCreatedWorkspaceDeletion(ctx, a.volume, persist) + if h.attest != nil && h.inCreationPhase(a.volume, line, nil) != "" { + marked, err := h.attest.markDeleteWithoutAck(a.volume) + if err != nil { + return fmt.Errorf("workspace delete: record the delete without acknowledgement: %w", err) + } + if marked { + return h.Publisher().ReserveNeverCreatedWorkspaceDeletion(ctx, a.volume, persist) + } } return h.Publisher().ReserveWorkspaceDeletion(ctx, a.volume, persist) } @@ -54,7 +61,63 @@ func (a *volumeDeleteAuthority) NoLiveLease(ctx context.Context) error { if a.host.lifecycle == nil || !a.host.lifecycle.Deletions.CommittedSnapshot(a.volume) { return errors.New("workspace delete: committed reservation required") } - return a.host.Publisher().NoLiveWorkspaceLease(ctx, a.volume) + if err := a.host.Publisher().NoLiveWorkspaceLease(ctx, a.volume); err != nil { + return err + } + if a.host.attest == nil || !a.host.attest.deleteWithoutAck(a.volume) { + return nil + } + return a.host.provenEmptyForDelete(a.volume) +} + +// ErrDeleteNotProvenEmpty refuses a delete without the holder's +// acknowledgement of a volume not proven empty. +var ErrDeleteNotProvenEmpty = errors.New("workspace delete: the volume is not proven empty") + +// provenEmptyForDelete is the proof a delete without the holder's +// acknowledgement finishes on. It is read here, after the reservation +// stopped every grant and the holder's lease horizon passed, so no write +// can be acknowledged after it. Proven empty is stage 1 (the primary of a +// volume whose stores are not all attested serves nothing), or N-K+1 +// survivors (the fencing round's count) that answered, each with a valid +// table at end 0; a survivor that did not answer is not empty, and one that +// holds a write refuses the delete for good. +func (h *Host) provenEmptyForDelete(volumeID string) error { + if waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)); waiting > 0 { + return nil + } + line, ok := h.Publisher().VolumeAuthorityLine(volumeID) + if !ok || !line.Assigned { + return fmt.Errorf("%w: no line to read its survivors at", ErrDeleteNotProvenEmpty) + } + h.promotionMu.RLock() + prober := h.promotionProber + h.promotionMu.RUnlock() + if prober == nil { + return fmt.Errorf("%w: no promotion gate to read the survivors", ErrDeleteNotProvenEmpty) + } + survivors := h.survivorCandidates(volumeID, line.ReplicaID) + res, err := prober.ProbePromotionCandidates(volumeID, line, survivors) + if err != nil { + return fmt.Errorf("%w: survivor round: %v", ErrDeleteNotProvenEmpty, err) + } + if !isKnownAckProfile(res.AckProfile) { + return fmt.Errorf("%w: unknown ack profile %q", ErrDeleteNotProvenEmpty, res.AckProfile) + } + empty := map[string]bool{} + for _, c := range res.Candidates { + if c.ReplicaID == "" || c.ReplicaID == line.ReplicaID || !c.TableValid { + continue + } + if c.DurableLSN > 0 { + return fmt.Errorf("%w: survivor %s holds a write (end %d): the volume served", ErrDeleteNotProvenEmpty, c.ReplicaID, c.DurableLSN) + } + empty[c.ReplicaID] = true + } + if need := unknownFrontierSurvivorsNeeded(res.AckProfile, len(survivors)); len(survivors) == 0 || len(empty) < need { + return fmt.Errorf("%w: %d of %d survivors answered empty, need %d", ErrDeleteNotProvenEmpty, len(empty), len(survivors), need) + } + return nil } // ReserveVolumeDeletion exposes the same committed reservation used by startup diff --git a/seaweed-block/core/host/master/workspace_delete_proof_test.go b/seaweed-block/core/host/master/workspace_delete_proof_test.go new file mode 100644 index 0000000000..dabba0b687 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_delete_proof_test.go @@ -0,0 +1,129 @@ +package master + +import ( + "errors" + "testing" +) + +// creatingStage2 is an RF3 volume whose stores are all attested and whose +// creation has not ended: its primary is gone (it never answers) and the +// survivors answer on valid tables, as the case sets. +func creatingStage2(t *testing.T, set func(p *switchProbe)) (*Host, *switchProbe) { + t.Helper() + h := newBootGraceMasterCreating(t, Config{}) + attestAllStores(t, h) + p := probeOf(t, h) + p.mu.Lock() + p.currentUnknown, p.tableValid, p.empty = true, true, true + if set != nil { + set(p) + } + p.mu.Unlock() + return h, p +} + +func deleteAuthority(h *Host, token string) *volumeDeleteAuthority { + return h.VolumeDeleteAuthority("vol-rf3", token) +} + +// Stage 2, no write anywhere, the primary dead: the delete without the +// holder's acknowledgement is admitted and, read after the horizon, both +// survivors answered empty (N-K+1 = 2): it finishes. +func TestAStage2VolumeNoSurvivorHoldsAWriteOfIsDeleted(t *testing.T) { + h, _ := creatingStage2(t, nil) + defer closeTestMaster(t, h) + a := deleteAuthority(h, "del-empty") + if err := a.Reserve(t.Context()); err != nil { + t.Fatal(err) + } + if !h.attest.deleteWithoutAck("vol-rf3") { + t.Fatal("a creating volume's delete was not admitted without the holder's acknowledgement") + } + if err := a.NoLiveLease(t.Context()); err != nil { + t.Fatalf("a volume proven empty: %v", err) + } +} + +// The same volume after a quorum-acknowledged write (r2 holds it): the +// survivor's answer ends creation, so the delete without the holder's +// acknowledgement is not admitted (the ordinary delete applies). +func TestADeleteWithoutAckOfAVolumeThatServedIsRefused(t *testing.T) { + h, _ := creatingStage2(t, func(p *switchProbe) { p.empty = false }) + defer closeTestMaster(t, h) + if err := deleteAuthority(h, "del-served").Reserve(t.Context()); err != nil { + t.Fatal(err) + } + if h.attest.deleteWithoutAck("vol-rf3") { + t.Fatal("a volume a survivor holds a write of was admitted for a delete without acknowledgement") + } + if h.attest.awaitingFirstReady("vol-rf3") { + t.Fatal("the survivor's write did not end creation") + } +} + +// Row mut_no_horizon: the survivors looked empty at the reservation, but a +// write was acknowledged before the holder's horizon passed: the proof is +// read after it, sees the write and refuses. +func TestADeleteWithoutAckReadsItsProofAfterTheHorizon(t *testing.T) { + h, p := creatingStage2(t, nil) + defer closeTestMaster(t, h) + a := deleteAuthority(h, "del-late-write") + if err := a.Reserve(t.Context()); err != nil { + t.Fatal(err) + } + p.mu.Lock() + p.empty = false // r2 now holds a write acknowledged before the horizon + p.mu.Unlock() + if err := a.NoLiveLease(t.Context()); !errors.Is(err, ErrDeleteNotProvenEmpty) { + t.Fatalf("err=%v; want ErrDeleteNotProvenEmpty", err) + } +} + +// Row mut_unstable_read: a silent survivor is not empty. With r3 silent +// only one survivor answered empty, need 2: refused. So is a round whose +// answers carry no valid table. +func TestADeleteWithoutAckNeedsNMinusKPlusOneEmptyAnswers(t *testing.T) { + for name, set := range map[string]func(p *switchProbe){ + "a silent survivor": func(p *switchProbe) { p.r3Silent = true }, + "no valid table at all": func(p *switchProbe) { p.tableValid = false }, + } { + t.Run(name, func(t *testing.T) { + h, _ := creatingStage2(t, set) + defer closeTestMaster(t, h) + a := deleteAuthority(h, "del-unstable") + if err := a.Reserve(t.Context()); err != nil { + t.Fatal(err) + } + if err := a.NoLiveLease(t.Context()); !errors.Is(err, ErrDeleteNotProvenEmpty) { + t.Fatalf("err=%v; want ErrDeleteNotProvenEmpty", err) + } + }) + } +} + +// Once a delete without acknowledgement is admitted, creation never ends +// (the delete reads the record as it was admitted), also after a restart. +func TestCreationDoesNotEndAfterADeleteWithoutAck(t *testing.T) { + cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir()} + h := newBootGraceMasterCreating(t, cfg) + attestAllStores(t, h) + p := probeOf(t, h) + p.mu.Lock() + p.empty, p.tableValid = true, true + p.mu.Unlock() + if err := deleteAuthority(h, "del-freeze").Reserve(t.Context()); err != nil { + t.Fatal(err) + } + p.mu.Lock() + p.currentReady = true // a ready answer after the admission + p.mu.Unlock() + line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if h.inCreationPhase("vol-rf3", line, nil) == "" { + t.Fatal("creation ended after the delete without acknowledgement was admitted") + } + h2 := restartCreatingMaster(t, h, cfg) + defer closeTestMaster(t, h2) + if !h2.attest.deleteWithoutAck("vol-rf3") || !h2.attest.awaitingFirstReady("vol-rf3") { + t.Fatal("after a restart the admitted delete or the creation wait is lost") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 44d23bc377..9049cf47b8 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -124,6 +124,8 @@ flowchart LR | Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | | any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | +| `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only before creation ended, marked durably first (creation never ends after it), and finishes only if, after the holder's lease horizon, the volume is proven empty: stage 1, or N-K+1 survivors answering end 0 on valid tables. | M2 any authority line, creation not ended → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`, `NoLiveLease`, `provenEmptyForDelete`; `core/host/master/store_attestation.go` `markDeleteWithoutAck` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeNoSurvivorHoldsAWriteOfIsDeleted`, `TestADeleteWithoutAckOfAVolumeThatServedIsRefused`, `TestADeleteWithoutAckReadsItsProofAfterTheHorizon`, `TestADeleteWithoutAckNeedsNMinusKPlusOneEmptyAnswers`, `TestCreationDoesNotEndAfterADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_unstable_read`, `mut_no_horizon` | ACTIVE | +| any authority line, creation not ended | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends creation (creation never ends after it); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease horizon as above and then requires proof that the volume is empty, read after it: stage 1 (not every store attested), or N-K+1 survivors answering on valid tables at end 0. A survivor holding a write, a silent survivor or an unknown ack profile refuses. A volume whose creation ended keeps the live-lease refusal | `core/host/master/volume_delete_authority.go` `Reserve`, `NoLiveLease`, `provenEmptyForDelete`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `noteFirstReady`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` | **Workspace lease and move, in blockmaster.** From d9a27835772700c17acac1cfa723477b25525c73 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:06:13 -0800 Subject: [PATCH 25/29] test(nvmerdma): the reopen test's primary attests its stores through the heartbeat RPC The test's volume host has no replication slot, so it never attests stores and the volume stayed in its creation phase. The fixture now sends r1's heartbeat with its store attestation through the master's own ReportHeartbeat RPC, as a replicated primary does after its peers' barriers: no test hook, no hand-written record. Co-Authored-By: Claude Opus 5.5 --- .../frontend/nvmerdma/failover_reopen_test.go | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go b/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go index 2617ae72b7..d846ed52e9 100644 --- a/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go +++ b/seaweed-block/core/frontend/nvmerdma/failover_reopen_test.go @@ -14,8 +14,35 @@ import ( master "github.com/seaweedfs/seaweed-block/core/host/master" volume "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" ) +// attestStores sends r1's heartbeat with its attestation of both replicas' +// stores through the master's own Heartbeat RPC, as a replicated primary +// does once its peers' barriers ran. This test's volume host has no +// replication slot, so it never attests; without the record the volume +// stays in its creation phase and nothing fails it over. +func attestStores(t *testing.T, addr string, epoch uint64) { + t.Helper() + c, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer c.Close() + store := func(b byte) []byte { id := make([]byte, 16); id[15] = b; return id } + att := &control.StoreAttestation{VolumeId: "v1", ReplicaId: "r1", Epoch: epoch, Stores: []*control.AttestedStore{ + {ReplicaId: "r1", StoreId: store(1)}, {ReplicaId: "r2", StoreId: store(2)}}} + if _, err := control.NewObservationServiceClient(c).ReportHeartbeat(context.Background(), &control.HeartbeatReport{ + ServerId: "s1", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "v1", ReplicaId: "r1", DataAddr: "127.0.0.1:19101", CtrlAddr: "127.0.0.1:19102"}}, + StoreAttestation: att}); err != nil { + t.Fatal(err) + } +} + // readyGate is a promotion gate whose candidates all answered ready. type readyGate struct{} @@ -114,6 +141,8 @@ func TestProviderBackendReopensAfterRealMasterFailover(t *testing.T) { t.Logf("real publisher authority: %s epoch%d", line.ReplicaID, line.Epoch) } transition(true, true, "r1", 1) + line, _ := m.Publisher().VolumeAuthorityLine("v1") + attestStores(t, m.Addr(), line.Epoch) provider := memback.NewProvider(h.ProjectionView()) adapters := map[string]*providerBackend{} for _, op := range []string{"read", "write", "sync", "demoted"} { From 6fa6f560894ce909ca1225da29b7698887cfbe53 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:10:17 -0800 Subject: [PATCH 26/29] fix(master): the delete without ack only in stage 1, and its mark freezes the wait The delete without the holder's acknowledgement was admitted whenever the end of creation was not recorded. That includes a volume that is serving acknowledged writes whose end the master could not read (after a master restart or a partition): the reservation stopped its grants, the proof then found a write and refused, and the volume could neither serve, fail over nor be deleted. It is now admitted only in stage 1, while the master's record still awaits a replica store (the primary serves nothing until every store is recorded). The mark is written durably first, in the lock that ends the wait, and freezes the record in stage 1: stores attested after it never end the wait, so the primary never starts serving. Past stage 1 the live-lease refusal stays; a broken creating primary's lease ends by itself and the ordinary delete then applies. The survivor proof at the HEAD update is no longer needed and is removed. Co-Authored-By: Claude Opus 5.5 --- .../master/primary_boot_grace_gate_test.go | 15 +- .../core/host/master/store_attestation.go | 39 +++-- .../host/master/volume_delete_authority.go | 75 ++------ .../master/workspace_delete_proof_test.go | 165 +++++++----------- seaweed-block/docs/design/invariants.md | 4 +- 5 files changed, 98 insertions(+), 200 deletions(-) diff --git a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go index c2ebfd40cb..675077bf65 100644 --- a/seaweed-block/core/host/master/primary_boot_grace_gate_test.go +++ b/seaweed-block/core/host/master/primary_boot_grace_gate_test.go @@ -78,9 +78,6 @@ type switchProbe struct { // awaitingEpoch: the current primary answers that it is not ready only // because its assignment at this epoch awaits replica stores (0: no). awaitingEpoch uint64 - // tableValid: the survivors' answers are read on valid epoch tables - // (evidence a delete's proof counts); r3Silent: r3 gives no valid answer. - tableValid, r3Silent bool // When hold is set, a probe signals entered and then blocks until // release is closed. hold bool @@ -111,21 +108,13 @@ func (p *switchProbe) ProbePromotionCandidates(volumeID string, current authorit p.mu.Lock() } defer p.mu.Unlock() - res := p.answerLocked() - for i := range res.Candidates { - res.Candidates[i].TableValid = p.tableValid && !(p.r3Silent && res.Candidates[i].ReplicaID == "r3") - } - return res, nil -} - -func (p *switchProbe) answerLocked() PromotionProbeResult { if p.empty { return PromotionProbeResult{ AckProfile: "sync-quorum", CurrentKnown: !p.currentUnknown, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, AwaitingReplicaStoresEpoch: p.awaitingEpoch}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true}, {ReplicaID: "r3"}}, - } + }, nil } return PromotionProbeResult{ AckProfile: "sync-quorum", @@ -135,7 +124,7 @@ func (p *switchProbe) answerLocked() PromotionProbeResult { CurrentKnown: !p.currentUnknown, Current: PromotionCandidateEvidence{ReplicaID: "r1", Ready: p.currentReady, AwaitingReplicaStoresEpoch: p.awaitingEpoch, DurableLSN: 70}, Candidates: []PromotionCandidateEvidence{{ReplicaID: "r2", Ready: true, DurableLSN: 70}, {ReplicaID: "r3", DurableLSN: p.lagEnd()}}, - } + }, nil } func (p *switchProbe) lagEnd() uint64 { diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 6f15df49e4..2ed6246cc0 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -39,9 +39,10 @@ type attestedStores struct { // so an established volume is never reopened. AwaitingFirstReady bool `json:"awaiting_first_ready,omitempty"` // DeleteWithoutAck: a delete without the holder's acknowledgement was - // admitted while the volume was creating (written before the delete's - // reservation). Creation never ends after it, and the delete finishes - // only on proof that the volume is empty (Host.provenEmptyForDelete). + // admitted while the volume's stores were still awaited (stage 1), + // written before the delete's reservation. It freezes the record in + // stage 1: the wait never ends after it, so the primary, whose + // assignment keeps awaiting the stores, never serves. DeleteWithoutAck bool `json:"delete_without_ack,omitempty"` } @@ -164,6 +165,10 @@ func (s *storeAttestations) awaited(volumeID string, current []string) (waiting, if waiting > 0 || len(current) == 0 { return waiting, len(current) } + if v.DeleteWithoutAck { + // A delete without acknowledgement froze the wait: it never ends. + return 1, len(current) + } vols := make(map[string]attestedStores, len(s.vols)) for k, x := range s.vols { vols[k] = x @@ -193,8 +198,7 @@ func (s *storeAttestations) awaitingFirstReady(volumeID string) bool { } // noteFirstReady records, durably and for good, that the volume's creation -// ended. It reports whether creation has ended: false when a delete without -// the holder's acknowledgement was admitted first (it may not end now). +// ended. It reports whether creation has ended. func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { s.mu.Lock() defer s.mu.Unlock() @@ -202,9 +206,6 @@ func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { if !had || !v.AwaitingFirstReady { return true, nil } - if v.DeleteWithoutAck { - return false, nil // the delete reads the record as it was admitted - } vols := make(map[string]attestedStores, len(s.vols)) for k, x := range s.vols { vols[k] = x @@ -220,20 +221,30 @@ func (s *storeAttestations) noteFirstReady(volumeID string) (bool, error) { } // markDeleteWithoutAck admits, durably, a delete without the holder's -// acknowledgement of a volume whose creation has not ended, in the same -// lock as noteFirstReady: creation cannot end between the check and the -// mark. false: creation ended (or the volume never waited): the ordinary -// delete applies. -func (s *storeAttestations) markDeleteWithoutAck(volumeID string) (bool, error) { +// acknowledgement of a volume whose stores are still awaited (stage 1: its +// primary has served nothing), in the same lock as the end of the wait: +// the wait cannot end between the check and the mark, and never ends after +// it. false: the volume is past stage 1 (or never waited), and the +// ordinary delete, refused while a lease is live, applies. +func (s *storeAttestations) markDeleteWithoutAck(volumeID string, current []string) (bool, error) { s.mu.Lock() defer s.mu.Unlock() v, had := s.vols[volumeID] - if !had || len(v.Initial) == 0 && !v.AwaitingFirstReady { + if !had || len(v.Initial) == 0 { return false, nil } if v.DeleteWithoutAck { return true, nil } + waiting := 0 + for _, id := range current { + if _, ok := v.Stores[id]; !ok { + waiting++ + } + } + if waiting == 0 || len(current) == 0 { + return false, nil // every store recorded: the wait ends at its next read + } vols := make(map[string]attestedStores, len(s.vols)) for k, x := range s.vols { vols[k] = x diff --git a/seaweed-block/core/host/master/volume_delete_authority.go b/seaweed-block/core/host/master/volume_delete_authority.go index b3b54c4d2a..f0d5138020 100644 --- a/seaweed-block/core/host/master/volume_delete_authority.go +++ b/seaweed-block/core/host/master/volume_delete_authority.go @@ -39,14 +39,15 @@ func (a *volumeDeleteAuthority) Reserve(ctx context.Context) error { } // The delete without the holder's acknowledgement (a live lease does // not refuse the reservation, which stops every grant) is admitted only - // while creation has not ended, recorded durably before the reservation - // so creation never ends after it; it finishes only on proof that the - // volume is empty (NoLiveLease). A volume whose creation ended keeps the - // live-lease refusal. The line, so a ready answer or a survivor's write - // read now ends creation before the delete is decided. - line, _ := h.Publisher().VolumeAuthorityLine(a.volume) - if h.attest != nil && h.inCreationPhase(a.volume, line, nil) != "" { - marked, err := h.attest.markDeleteWithoutAck(a.volume) + // in stage 1, while the master's record still awaits a replica store: + // the primary serves nothing until every store is recorded. The record + // is marked durably first, in the lock that ends the wait, and the mark + // freezes it in stage 1, so the primary never starts serving. Past stage + // 1 (also while creation has not been recorded as ended: the volume may + // be serving) the live-lease refusal stays; a broken primary's lease + // ends by itself, and the ordinary delete then applies. + if h.attest != nil { + marked, err := h.attest.markDeleteWithoutAck(a.volume, h.replicaSlotsFor(a.volume)) if err != nil { return fmt.Errorf("workspace delete: record the delete without acknowledgement: %w", err) } @@ -61,63 +62,7 @@ func (a *volumeDeleteAuthority) NoLiveLease(ctx context.Context) error { if a.host.lifecycle == nil || !a.host.lifecycle.Deletions.CommittedSnapshot(a.volume) { return errors.New("workspace delete: committed reservation required") } - if err := a.host.Publisher().NoLiveWorkspaceLease(ctx, a.volume); err != nil { - return err - } - if a.host.attest == nil || !a.host.attest.deleteWithoutAck(a.volume) { - return nil - } - return a.host.provenEmptyForDelete(a.volume) -} - -// ErrDeleteNotProvenEmpty refuses a delete without the holder's -// acknowledgement of a volume not proven empty. -var ErrDeleteNotProvenEmpty = errors.New("workspace delete: the volume is not proven empty") - -// provenEmptyForDelete is the proof a delete without the holder's -// acknowledgement finishes on. It is read here, after the reservation -// stopped every grant and the holder's lease horizon passed, so no write -// can be acknowledged after it. Proven empty is stage 1 (the primary of a -// volume whose stores are not all attested serves nothing), or N-K+1 -// survivors (the fencing round's count) that answered, each with a valid -// table at end 0; a survivor that did not answer is not empty, and one that -// holds a write refuses the delete for good. -func (h *Host) provenEmptyForDelete(volumeID string) error { - if waiting, _ := h.attest.awaited(volumeID, h.replicaSlotsFor(volumeID)); waiting > 0 { - return nil - } - line, ok := h.Publisher().VolumeAuthorityLine(volumeID) - if !ok || !line.Assigned { - return fmt.Errorf("%w: no line to read its survivors at", ErrDeleteNotProvenEmpty) - } - h.promotionMu.RLock() - prober := h.promotionProber - h.promotionMu.RUnlock() - if prober == nil { - return fmt.Errorf("%w: no promotion gate to read the survivors", ErrDeleteNotProvenEmpty) - } - survivors := h.survivorCandidates(volumeID, line.ReplicaID) - res, err := prober.ProbePromotionCandidates(volumeID, line, survivors) - if err != nil { - return fmt.Errorf("%w: survivor round: %v", ErrDeleteNotProvenEmpty, err) - } - if !isKnownAckProfile(res.AckProfile) { - return fmt.Errorf("%w: unknown ack profile %q", ErrDeleteNotProvenEmpty, res.AckProfile) - } - empty := map[string]bool{} - for _, c := range res.Candidates { - if c.ReplicaID == "" || c.ReplicaID == line.ReplicaID || !c.TableValid { - continue - } - if c.DurableLSN > 0 { - return fmt.Errorf("%w: survivor %s holds a write (end %d): the volume served", ErrDeleteNotProvenEmpty, c.ReplicaID, c.DurableLSN) - } - empty[c.ReplicaID] = true - } - if need := unknownFrontierSurvivorsNeeded(res.AckProfile, len(survivors)); len(survivors) == 0 || len(empty) < need { - return fmt.Errorf("%w: %d of %d survivors answered empty, need %d", ErrDeleteNotProvenEmpty, len(empty), len(survivors), need) - } - return nil + return a.host.Publisher().NoLiveWorkspaceLease(ctx, a.volume) } // ReserveVolumeDeletion exposes the same committed reservation used by startup diff --git a/seaweed-block/core/host/master/workspace_delete_proof_test.go b/seaweed-block/core/host/master/workspace_delete_proof_test.go index dabba0b687..1254428d98 100644 --- a/seaweed-block/core/host/master/workspace_delete_proof_test.go +++ b/seaweed-block/core/host/master/workspace_delete_proof_test.go @@ -1,129 +1,82 @@ package master import ( - "errors" "testing" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) -// creatingStage2 is an RF3 volume whose stores are all attested and whose -// creation has not ended: its primary is gone (it never answers) and the -// survivors answer on valid tables, as the case sets. -func creatingStage2(t *testing.T, set func(p *switchProbe)) (*Host, *switchProbe) { - t.Helper() - h := newBootGraceMasterCreating(t, Config{}) - attestAllStores(t, h) - p := probeOf(t, h) - p.mu.Lock() - p.currentUnknown, p.tableValid, p.empty = true, true, true - if set != nil { - set(p) +// The state with no exit: every store attested (stage 2) but the end of +// creation never recorded (the master read neither a ready answer nor a +// survivor's write since), while the primary may be serving acknowledged +// writes under its live lease. The delete keeps the live-lease refusal: no +// reservation stops that primary's grants. +func TestAStage2VolumeKeepsTheLiveLeaseRefusal(t *testing.T) { + h, lc, _, _, _ := neverCreatedVolume(t, false) + line := waitAuthorityLine(t, h.Publisher(), "v") + published, _ := h.Publisher().PublishedAuthorityLine("v") + server := h.workspaceLineOwner(published, "v", line.ReplicaID, line.Epoch) + if err := h.ingestStoreAttestation(server, attestation("v", line.ReplicaID, line.Epoch, map[string]storage.StoreID{line.ReplicaID: storeOf(line.ReplicaID)})); err != nil { + t.Fatal(err) + } + if waiting, _ := h.attest.awaited("v", h.replicaSlotsFor("v")); waiting != 0 || !h.attest.awaitingFirstReady("v") { + t.Fatal("fixture: the volume is not in stage 2") + } + if h.inCreationPhase("v", line, nil) == "" { + t.Fatal("fixture: the end of creation was recorded") + } + _, err := lc.ReserveVolumeDeletion(t.Context(), &control.MarkVolumeDeletingRequest{VolumeId: "v", Token: "del-stage2"}) + if status.Code(err) != codes.FailedPrecondition { + t.Fatalf("delete of a stage-2 volume under a live lease: %v; want FailedPrecondition", err) + } + if h.attest.deleteWithoutAck("v") { + t.Fatal("a stage-2 volume was marked for a delete without acknowledgement") } - p.mu.Unlock() - return h, p } -func deleteAuthority(h *Host, token string) *volumeDeleteAuthority { - return h.VolumeDeleteAuthority("vol-rf3", token) -} - -// Stage 2, no write anywhere, the primary dead: the delete without the -// holder's acknowledgement is admitted and, read after the horizon, both -// survivors answered empty (N-K+1 = 2): it finishes. -func TestAStage2VolumeNoSurvivorHoldsAWriteOfIsDeleted(t *testing.T) { - h, _ := creatingStage2(t, nil) - defer closeTestMaster(t, h) - a := deleteAuthority(h, "del-empty") +// A delete without acknowledgement admitted in stage 1 freezes the store +// wait: stores attested after it never end the wait (the primary, whose +// assignment keeps awaiting them, never serves), also after a restart, and +// the delete finishes at its HEAD update. +func TestTheDeleteMarkFreezesTheStoreWait(t *testing.T) { + cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir()} + h := newBootGraceMasterCreating(t, cfg) + a := h.VolumeDeleteAuthority("vol-rf3", "del-frozen") if err := a.Reserve(t.Context()); err != nil { t.Fatal(err) } if !h.attest.deleteWithoutAck("vol-rf3") { - t.Fatal("a creating volume's delete was not admitted without the holder's acknowledgement") + t.Fatal("a stage-1 volume's delete was not admitted without acknowledgement") } - if err := a.NoLiveLease(t.Context()); err != nil { - t.Fatalf("a volume proven empty: %v", err) + line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") + if err := h.ingestStoreAttestation("node-a", attestation("vol-rf3", "r1", line.Epoch, map[string]storage.StoreID{"r1": testStoreID, "r2": testStoreID, "r3": testStoreID})); err != nil { + t.Fatal(err) + } + if !inCreationWait(h) || h.attest.awaitingFirstReady("vol-rf3") { + t.Fatal("the store wait ended after the delete mark") + } + h = restartCreatingMaster(t, h, cfg) + defer closeTestMaster(t, h) + if !inCreationWait(h) || !h.attest.deleteWithoutAck("vol-rf3") { + t.Fatal("after a restart the frozen wait or the mark is lost") + } + if err := h.VolumeDeleteAuthority("vol-rf3", "del-frozen").NoLiveLease(t.Context()); err != nil { + t.Fatalf("the frozen stage-1 delete's HEAD update: %v", err) } } -// The same volume after a quorum-acknowledged write (r2 holds it): the -// survivor's answer ends creation, so the delete without the holder's -// acknowledgement is not admitted (the ordinary delete applies). -func TestADeleteWithoutAckOfAVolumeThatServedIsRefused(t *testing.T) { - h, _ := creatingStage2(t, func(p *switchProbe) { p.empty = false }) +// Past stage 1 nothing is marked: the ordinary delete applies. +func TestAStage2VolumeIsNotMarkedForADeleteWithoutAck(t *testing.T) { + h := newBootGraceMasterCreating(t, Config{}) defer closeTestMaster(t, h) - if err := deleteAuthority(h, "del-served").Reserve(t.Context()); err != nil { + attestAllStores(t, h) + if err := h.VolumeDeleteAuthority("vol-rf3", "del-ordinary").Reserve(t.Context()); err != nil { t.Fatal(err) } if h.attest.deleteWithoutAck("vol-rf3") { - t.Fatal("a volume a survivor holds a write of was admitted for a delete without acknowledgement") - } - if h.attest.awaitingFirstReady("vol-rf3") { - t.Fatal("the survivor's write did not end creation") - } -} - -// Row mut_no_horizon: the survivors looked empty at the reservation, but a -// write was acknowledged before the holder's horizon passed: the proof is -// read after it, sees the write and refuses. -func TestADeleteWithoutAckReadsItsProofAfterTheHorizon(t *testing.T) { - h, p := creatingStage2(t, nil) - defer closeTestMaster(t, h) - a := deleteAuthority(h, "del-late-write") - if err := a.Reserve(t.Context()); err != nil { - t.Fatal(err) - } - p.mu.Lock() - p.empty = false // r2 now holds a write acknowledged before the horizon - p.mu.Unlock() - if err := a.NoLiveLease(t.Context()); !errors.Is(err, ErrDeleteNotProvenEmpty) { - t.Fatalf("err=%v; want ErrDeleteNotProvenEmpty", err) - } -} - -// Row mut_unstable_read: a silent survivor is not empty. With r3 silent -// only one survivor answered empty, need 2: refused. So is a round whose -// answers carry no valid table. -func TestADeleteWithoutAckNeedsNMinusKPlusOneEmptyAnswers(t *testing.T) { - for name, set := range map[string]func(p *switchProbe){ - "a silent survivor": func(p *switchProbe) { p.r3Silent = true }, - "no valid table at all": func(p *switchProbe) { p.tableValid = false }, - } { - t.Run(name, func(t *testing.T) { - h, _ := creatingStage2(t, set) - defer closeTestMaster(t, h) - a := deleteAuthority(h, "del-unstable") - if err := a.Reserve(t.Context()); err != nil { - t.Fatal(err) - } - if err := a.NoLiveLease(t.Context()); !errors.Is(err, ErrDeleteNotProvenEmpty) { - t.Fatalf("err=%v; want ErrDeleteNotProvenEmpty", err) - } - }) - } -} - -// Once a delete without acknowledgement is admitted, creation never ends -// (the delete reads the record as it was admitted), also after a restart. -func TestCreationDoesNotEndAfterADeleteWithoutAck(t *testing.T) { - cfg := Config{AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir()} - h := newBootGraceMasterCreating(t, cfg) - attestAllStores(t, h) - p := probeOf(t, h) - p.mu.Lock() - p.empty, p.tableValid = true, true - p.mu.Unlock() - if err := deleteAuthority(h, "del-freeze").Reserve(t.Context()); err != nil { - t.Fatal(err) - } - p.mu.Lock() - p.currentReady = true // a ready answer after the admission - p.mu.Unlock() - line := waitAuthorityLine(t, h.Publisher(), "vol-rf3") - if h.inCreationPhase("vol-rf3", line, nil) == "" { - t.Fatal("creation ended after the delete without acknowledgement was admitted") - } - h2 := restartCreatingMaster(t, h, cfg) - defer closeTestMaster(t, h2) - if !h2.attest.deleteWithoutAck("vol-rf3") || !h2.attest.awaitingFirstReady("vol-rf3") { - t.Fatal("after a restart the admitted delete or the creation wait is lost") + t.Fatal("a stage-2 volume was marked for a delete without acknowledgement") } } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 9049cf47b8..c3e4ebe09f 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -124,8 +124,8 @@ flowchart LR | Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | | any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | -| `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only before creation ended, marked durably first (creation never ends after it), and finishes only if, after the holder's lease horizon, the volume is proven empty: stage 1, or N-K+1 survivors answering end 0 on valid tables. | M2 any authority line, creation not ended → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`, `NoLiveLease`, `provenEmptyForDelete`; `core/host/master/store_attestation.go` `markDeleteWithoutAck` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeNoSurvivorHoldsAWriteOfIsDeleted`, `TestADeleteWithoutAckOfAVolumeThatServedIsRefused`, `TestADeleteWithoutAckReadsItsProofAfterTheHorizon`, `TestADeleteWithoutAckNeedsNMinusKPlusOneEmptyAnswers`, `TestCreationDoesNotEndAfterADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_unstable_read`, `mut_no_horizon` | ACTIVE | -| any authority line, creation not ended | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends creation (creation never ends after it); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease horizon as above and then requires proof that the volume is empty, read after it: stage 1 (not every store attested), or N-K+1 survivors answering on valid tables at end 0. A survivor holding a write, a silent survivor or an unknown ack profile refuses. A volume whose creation ended keeps the live-lease refusal | `core/host/master/volume_delete_authority.go` `Reserve`, `NoLiveLease`, `provenEmptyForDelete`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `noteFirstReady`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` | +| `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE | +| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease horizon as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` | **Workspace lease and move, in blockmaster.** From e7f238c4a8ebb0d4b0a0eb5b5287b78e2cae5683 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:14:14 -0800 Subject: [PATCH 27/29] fix(master): a store record rewrite keeps the delete mark; writer census record() rebuilt a volume's store record from a new attestation and carried Initial and AwaitingFirstReady over but not DeleteWithoutAck, so a late attestation of the last store erased the mark and ended the frozen wait. The mark is now carried like the other one-way fields and compared in sameAttestation. TestTheDeleteMarkFreezesTheStoreWait (an attestation of every store after the mark, then a restart) is the red control. A source census pins the rules: a record is built only in open and in record, record carries the mark over, and only markDeleteWithoutAck writes it (true); its controls break each rule. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/store_attestation.go | 3 +- .../master/store_attestation_census_test.go | 116 ++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/host/master/store_attestation_census_test.go diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 2ed6246cc0..5195f2e107 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -301,6 +301,7 @@ func (s *storeAttestations) record(att *control.StoreAttestation) error { } next.Initial = cur.Initial // cleared only by awaited next.AwaitingFirstReady = cur.AwaitingFirstReady // cleared only by noteFirstReady + next.DeleteWithoutAck = cur.DeleteWithoutAck // set only by markDeleteWithoutAck, never cleared if had && sameAttestation(cur, next) { return nil } @@ -318,7 +319,7 @@ func (s *storeAttestations) record(att *control.StoreAttestation) error { } func sameAttestation(a, b attestedStores) bool { - if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) || len(a.Initial) != len(b.Initial) || a.AwaitingFirstReady != b.AwaitingFirstReady { + if a.Primary != b.Primary || a.Epoch != b.Epoch || len(a.Stores) != len(b.Stores) || len(a.Initial) != len(b.Initial) || a.AwaitingFirstReady != b.AwaitingFirstReady || a.DeleteWithoutAck != b.DeleteWithoutAck { return false } for k, v := range a.Stores { diff --git a/seaweed-block/core/host/master/store_attestation_census_test.go b/seaweed-block/core/host/master/store_attestation_census_test.go new file mode 100644 index 0000000000..ecb53dd8eb --- /dev/null +++ b/seaweed-block/core/host/master/store_attestation_census_test.go @@ -0,0 +1,116 @@ +package master + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "sort" + "strings" + "testing" +) + +// deleteMarkCensus lists the violations of the DeleteWithoutAck writer rules +// in the given Go sources (file name -> text): +// - a record (an attestedStores literal) is built only in open (a fresh +// record, no mark yet) and in record, which must carry the mark over +// from the record it replaces; +// - the mark is assigned only in markDeleteWithoutAck, and only true. +func deleteMarkCensus(t *testing.T, files map[string]string) []string { + t.Helper() + var out []string + fset := token.NewFileSet() + for name, src := range files { + f, err := parser.ParseFile(fset, name, src, 0) + if err != nil { + t.Fatal(err) + } + for _, d := range f.Decls { + fn, ok := d.(*ast.FuncDecl) + if !ok || fn.Body == nil { + continue + } + carries := false + ast.Inspect(fn.Body, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.CompositeLit: + if id, ok := x.Type.(*ast.Ident); ok && id.Name == "attestedStores" { + if fn.Name.Name != "open" && fn.Name.Name != "record" { + out = append(out, name+": "+fn.Name.Name+" builds a store record") + } + } + case *ast.AssignStmt: + for i, l := range x.Lhs { + sel, ok := l.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "DeleteWithoutAck" || i >= len(x.Rhs) { + continue + } + rhs := x.Rhs[i] + if r, ok := rhs.(*ast.SelectorExpr); ok && r.Sel.Name == "DeleteWithoutAck" && fn.Name.Name == "record" { + carries = true + continue + } + if v, ok := rhs.(*ast.Ident); ok && v.Name == "true" && fn.Name.Name == "markDeleteWithoutAck" { + continue + } + out = append(out, name+": "+fn.Name.Name+" writes DeleteWithoutAck") + } + } + return true + }) + if fn.Name.Name == "record" && !carries { + out = append(out, name+": record does not carry DeleteWithoutAck over") + } + } + } + sort.Strings(out) + return out +} + +func masterSources(t *testing.T) map[string]string { + t.Helper() + names, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + files := map[string]string{} + for _, n := range names { + if strings.HasSuffix(n, "_test.go") { + continue + } + b, err := os.ReadFile(n) + if err != nil { + t.Fatal(err) + } + files[n] = string(b) + } + return files +} + +// Every writer of the delete mark, and every rewrite of a store record, +// keeps the mark: it is set once, by markDeleteWithoutAck, and never lost. +func TestDeleteMarkWriterCensus(t *testing.T) { + if v := deleteMarkCensus(t, masterSources(t)); len(v) != 0 { + t.Fatalf("delete mark census: %v", v) + } +} + +// The census fails on each rule broken: a record rewrite that drops the +// mark, a new place that builds a record, and a write that clears it. +func TestDeleteMarkWriterCensusControls(t *testing.T) { + src := masterSources(t)["store_attestation.go"] + carry := "\tnext.DeleteWithoutAck = cur.DeleteWithoutAck" + if !strings.Contains(src, carry) { + t.Fatal("control fixture: the carry line moved") + } + for name, bad := range map[string]string{ + "dropped carry": strings.Replace(src, carry, "\t_ = cur", 1), + "new builder": src + "\nfunc rebuild() attestedStores { return attestedStores{} }\n", + "cleared mark": src + "\nfunc clearMark(v *attestedStores) { v.DeleteWithoutAck = false }\n", + } { + if v := deleteMarkCensus(t, map[string]string{"store_attestation.go": bad}); len(v) == 0 { + t.Errorf("%s: the census found nothing", name) + } + } +} From 8d5d262b155656e825fda5bb38f1f51830cef211 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:14:25 -0800 Subject: [PATCH 28/29] docs(invariants): the creation phase's machine in Part A, with its diagram Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 44d23bc377..7a749418b1 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -125,6 +125,24 @@ flowchart LR | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | | any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | +**Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established. + +```mermaid +stateDiagram-v2 + [*] --> AwaitingStores: first bind of a new volume (record opened with its initial replicas) + AwaitingStores --> AwaitingStores: the write that ends the wait fails (still held, reported as one store awaited) + AwaitingStores --> AwaitingEnd: every current replica's store attested (written durably) + AwaitingEnd --> Established: first of the primary's ready answer, or a survivor's DurableLSN > 0 at the line (written durably) + Established --> Established: later answers reopen nothing +``` + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| (none) | AwaitingStores | the master binds a volume for the first time; the record lists its initial replicas | `core/host/master/store_attestation.go` `openStoreRecord`, `open` | `INV-PROMOTE-CREATION-WAIT-001` | +| AwaitingStores | AwaitingEnd | every current replica has an attested store; Initial is cleared and `awaiting_first_ready` set in one durable write; a failed write leaves the record as it was and the volume held | `core/host/master/store_attestation.go` `awaited` | `INV-PROMOTE-CREATION-WAIT-001` | +| AwaitingEnd | Established | the line's primary answers ready, or a survivor answers DurableLSN > 0 with its epoch-table row at the current epoch (or none), in any probe; recorded durably and for good | `core/host/master/product_loop.go` `inCreationPhase`, `firstReadyNow`, `survivorHoldingAWrite`; `core/host/master/store_attestation.go` `noteFirstReady` | `INV-PROMOTE-CREATION-WAIT-001` | +| AwaitingStores, AwaitingEnd | (no change) | no replacement decision: no reassign, fencing round, heal, operator move or rebalance; also while the primary's own answer says its assignment at the line's epoch awaits the stores | `core/host/master/product_loop.go` `holdCreating`, `noteCreating`; `core/host/master/planned_move.go` `plannedMoveEvidenceAt`, `fencedMoveEvidence` | `INV-PROMOTE-CREATION-WAIT-001` | + **Workspace lease and move, in blockmaster.** TERM-HOLDER-001 uses one owner decision, `PublishedLine.Owner` (core/authority), From 3f1d36f934dd969c32252b5b9133d82a6893d44e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 26 Nov 2026 00:14:50 -0800 Subject: [PATCH 29/29] docs(invariants): the delete mark in the creation machine; its ledger row in Part B Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3246b393a6..9e8375a9f4 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -124,7 +124,6 @@ flowchart LR | Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | | any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | -| `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE | | any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease horizon as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` | **Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established. @@ -136,6 +135,8 @@ stateDiagram-v2 AwaitingStores --> AwaitingEnd: every current replica's store attested (written durably) AwaitingEnd --> Established: first of the primary's ready answer, or a survivor's DurableLSN > 0 at the line (written durably) Established --> Established: later answers reopen nothing + AwaitingStores --> DeleteMarked: delete without the holder's acknowledgement admitted (mark written first) + DeleteMarked --> DeleteMarked: stores attested after the mark (the wait never ends: the primary serves nothing) ``` | From | To | Event and guard | Enforced in | Protects | @@ -143,6 +144,7 @@ stateDiagram-v2 | (none) | AwaitingStores | the master binds a volume for the first time; the record lists its initial replicas | `core/host/master/store_attestation.go` `openStoreRecord`, `open` | `INV-PROMOTE-CREATION-WAIT-001` | | AwaitingStores | AwaitingEnd | every current replica has an attested store; Initial is cleared and `awaiting_first_ready` set in one durable write; a failed write leaves the record as it was and the volume held | `core/host/master/store_attestation.go` `awaited` | `INV-PROMOTE-CREATION-WAIT-001` | | AwaitingEnd | Established | the line's primary answers ready, or a survivor answers DurableLSN > 0 with its epoch-table row at the current epoch (or none), in any probe; recorded durably and for good | `core/host/master/product_loop.go` `inCreationPhase`, `firstReadyNow`, `survivorHoldingAWrite`; `core/host/master/store_attestation.go` `noteFirstReady` | `INV-PROMOTE-CREATION-WAIT-001` | +| AwaitingStores | DeleteMarked | the delete's reservation, under the lock that ends the wait, while a current replica's store is still unattested; written durably before the reservation; from then on `awaited` never ends the wait and every record rewrite keeps the mark. AwaitingEnd and Established are never marked (the live-lease refusal stays) | `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`, `record`; `core/host/master/volume_delete_authority.go` `Reserve` | `INV-WS-DELETE-WITHOUT-ACK-001` | | AwaitingStores, AwaitingEnd | (no change) | no replacement decision: no reassign, fencing round, heal, operator move or rebalance; also while the primary's own answer says its assignment at the line's epoch awaits the stores | `core/host/master/product_loop.go` `holdCreating`, `noteCreating`; `core/host/master/planned_move.go` `plannedMoveEvidenceAt`, `fencedMoveEvidence` | `INV-PROMOTE-CREATION-WAIT-001` | **Workspace lease and move, in blockmaster.** @@ -1076,6 +1078,7 @@ Notes: | `INV-SNAPK-DELETE-ORDER-001` | A volume delete runs in its order, each prefix safe and the whole re-runnable: HEAD deleting, this volume released from every source, its objects deleted, HEAD deleted. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume` | `TestDeleteVolume`, `TestDeleteVolume_InterruptAtEveryStep`, `TestRunMarkDeleting_InterruptAtEveryStep`, `TestRunMarkDeleted_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-OWNED-001` | Every object entry carries the id of its volume; a volume delete removes an object only if it carries that id, so a late delete of a finished run never removes the object of a volume created again under the name. | M9 deleting → deleted | `core/frontend/chunkstore/layout` `delete.go` `DeleteVolume`; `objects.go` `ObjectStore.DeleteOfVolume` | `TestDeleteVolume_ALateDeleteSparesTheNameReused`, `TestDeleteVolume` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-DELETE-GATE-001` | HEAD becomes deleting only with a committed deletion reservation, no live lease (unclaimed grants included), no open activity and no snapshot with dependents; from deleting on, no holder transition, claim or removal applies. | M2 any → DeleteReserved; M9 idle → deleting | `core/frontend/chunkstore/layout` `delete.go` `Head.MarkDeleting`; `head.go` `holderErr`; `core/authority/workspace_delete_reservation.go`; `core/host/master/volume_delete_authority.go` `ReserveVolumeDeletion`, `CheckVolumeNoLiveLease`; `cmd/sw-block/chunk_volume_delete.go` `masterAuthority` | `TestMarkDeleting_Closure`, `TestMarkDeleted_Closure`, `TestDeleting_RefusesEveryHolderStep`, `TestDeleteVolume`; `TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease`, `TestDeleteReservationClosesPausedGrantWriters`, `TestDeleteReservationMustBeDurableBeforeItCanProveNoLease`, `TestDeleteReservationContextAndPersistenceFailuresStayUnknown`, `TestDeleteOfALiveVolumeIsRefusedBeforePersisting`, `TestDeleteReservationReplayAndRestart`, `TestDeletionReservationGuardSites` (`core/authority`); `TestVolumeDeleteAuthorityReservationSurvivesRestart`, `TestVolumeDeleteAuthorityRPCs` (`core/host/master`; durable RPC/restart probes run on Linux); `TestOpsChunkVolumeDeleteRequiresTheMastersLeaseProof`, `TestOpsChunkVolumeDeleteClosesAPausedFirstGrant`, `TestChunkVolumeDeleteAuthorityRPCSites` (`cmd/sw-block`) | The reservation makes no-live-lease stable; a claim racing the conditional HEAD update still fails its generation check. The snapshot kernel model is external; composed model review pending. | ACTIVE | +| `INV-WS-DELETE-WITHOUT-ACK-001` | A delete without the holder's acknowledgement is admitted only while the master's record still awaits a replica store (stage 1), marked durably first; the mark freezes the wait, so the primary never serves. Past stage 1 the live-lease refusal stays. | M2 any authority line, stores still awaited → DeleteReserved without the holder's acknowledgement | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited` | `TestANeverCreatedVolumeIsDeletedWithoutItsHolder`, `TestAnEstablishedVolumeIsNotDeletedUnderALiveLease` (`core/host/master/workspace_delete_never_created_test.go`); `TestAStage2VolumeKeepsTheLiveLeaseRefusal`, `TestTheDeleteMarkFreezesTheStoreWait`, `TestAStage2VolumeIsNotMarkedForADeleteWithoutAck` (`core/host/master/workspace_delete_proof_test.go`); `TestDeleteMarkWriterCensus`, `TestDeleteMarkWriterCensusControls` (`core/host/master/store_attestation_census_test.go`) | CreateEvid2 model rows `mut_delete_on_flag_only`, `mut_no_horizon` | ACTIVE | | `INV-SNAPK-DELETE-GUARD-001` | A source scan requires DeleteVolume to run no-holder check, deleting, release, object deletes and deleted in that order, and allows it as the only remover besides RemoveUnreachable. | M9 idle → deleting → deleted | `core/frontend/chunkstore/layout` (source scan of `delete.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-VOLUME-DIR-001` | A volume's master-minted layout identity is immutable; its directory is -, created exclusively and never reused. A foreign chunk's owning directory is checked against its full VOLUME id. | Content-named layout and lifecycle create/lookup/launch | `core/frontend/chunkstore/layout` `VolumeDir`, `Image.Chunk`; `core/lifecycle/store.go` `CreateVolume`; `core/host/master/services.go` `CreateVolume`, `GetVolume`; `core/rpc/lifecycleclient` `ResolveVolume`; `core/launcher/k8s_renderer.go`; `cmd/blockvolume/main.go` `parseFlags`; `core/host/volume/chunk_control.go` `catalogVolume`, `ListSnapshots`, `DeleteSnapshot`, `Usage`; `cmd/blockvolume/chunk_remote.go` `chunkAttachCheck` | `TestRead_ForeignChunkFromSourcePool`, `TestRead_ForeignChunkNeedsTheOwnersVolumeID`; `TestLifecycleLayoutIdentity`, `TestLayoutIdentityWriterAndReaders`; `TestGetLifecycleVolumeResolvesOnlyTheDurableIdentity`; `TestResolveVolumeNeverInventsAnIdentity`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestBlockvolumeLayoutIdentitySelectsTheLocalRoot`; `TestChunkControlUsesTheBoundLayoutIdentity`, `TestChunkControlCatalogLookupErrorIsNotAbsence`, `TestChunkAttachCheckAppliesVolumeRules`; `TestHeadReaders_Enumeration`, `TestDeleteAndDirectorySites_Enumeration` | Lifecycle ids are durable record fields, not assignment epochs. Old records without the field are refused by the new-layout lookup; host metadata is bound to the full name/id and does not fall back to a previous incarnation. Data-path, scheduled snapshot and cleaning callers plus Linux crash qualification remain cutover work. | ACTIVE | | `INV-SNAPK-TOMBSTONE-001` | For a restore target without HEAD (never created, or a restore died between its two creates) the operator writes a deleted HEAD exclusively in its directory before releasing, so the restore cannot create it later. | M9 source HEAD, dependents | `core/frontend/chunkstore/layout` `delete.go` `OperatorReleaseDependent`, `TargetStore.CreateDeletedHead` | `TestOperatorReleaseDependent`, `TestOperatorReleaseDependent_TombstoneLosesToTheRestore`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE |