Merge pull request #374 from seaweedfs/train/20261122-12

train 12: HEAD reopen claim + expected-server slot facts
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-21 16:46:32 -08:00
commit b4633efd2c
35 files changed
+973 -133

No files matched your search

@@ -416,8 +416,19 @@ func assembleVolumeTopology(
) VolumeTopologySnapshot {
slots := make([]ReplicaCandidate, 0, len(expected.Slots))
// A replica's fact counts only from the server its expected slot names:
// another server reporting the same replica id (rule §9's foreign claim
// does not cover a known replica id) must not supply its addresses or
// health to the line.
expectedServer := make(map[string]string, len(expected.Slots))
for _, e := range expected.Slots {
expectedServer[e.ReplicaID] = e.ServerID
}
byReplicaID := map[string]slotWithServer{}
for _, f := range freshSlots {
if f.serverID != expectedServer[f.slot.ReplicaID] {
continue
}
if _, ok := byReplicaID[f.slot.ReplicaID]; !ok {
byReplicaID[f.slot.ReplicaID] = f
}
@@ -0,0 +1,39 @@
package authority
import "testing"
// INV-OBS-SLOT-FROM-EXPECTED-SERVER-001: a replica's slot in the assembled
// topology takes its addresses and health only from a fresh fact reported
// by the server its expected slot names. Another server's fact for the
// same replica (whatever it claims, and whichever comes first) is never
// used: with no fact from the expected server the slot is a placeholder.
func TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer(t *testing.T) {
expected := VolumeExpected{VolumeID: "v1", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}, {ReplicaID: "r2", ServerID: "node-b"}}}
foreign := slotWithServer{serverID: "node-x", slot: SlotFact{VolumeID: "v1", ReplicaID: "r1", DataAddr: "10.9.9.9:1", CtrlAddr: "10.9.9.9:2", Reachable: true, ReadyForPrimary: true, Eligible: true, EvidenceScore: 99}}
own := slotWithServer{serverID: "node-a", slot: SlotFact{VolumeID: "v1", ReplicaID: "r1", DataAddr: "10.0.0.1:1", CtrlAddr: "10.0.0.1:2", Reachable: true, Eligible: true}}
r2 := slotWithServer{serverID: "node-b", slot: SlotFact{VolumeID: "v1", ReplicaID: "r2", DataAddr: "10.0.0.2:1", CtrlAddr: "10.0.0.2:2", Reachable: true, Eligible: true}}
slot := func(topo VolumeTopologySnapshot, replica string) ReplicaCandidate {
t.Helper()
for _, s := range topo.Slots {
if s.ReplicaID == replica {
return s
}
}
t.Fatalf("no slot %s in %+v", replica, topo.Slots)
return ReplicaCandidate{}
}
// The foreign fact comes first: the expected server's fact still wins.
got := slot(assembleVolumeTopology("v1", expected, []slotWithServer{foreign, own, r2}, AuthorityBasis{}, false), "r1")
if got.DataAddr != own.slot.DataAddr || got.CtrlAddr != own.slot.CtrlAddr || got.ServerID != "node-a" || got.EvidenceScore != 0 {
t.Fatalf("r1 = %+v, want node-a's fact (addresses %s/%s, score 0)", got, own.slot.DataAddr, own.slot.CtrlAddr)
}
// Only the foreign server reported r1: the slot is a placeholder, never
// the foreign addresses or health.
got = slot(assembleVolumeTopology("v1", expected, []slotWithServer{foreign, r2}, AuthorityBasis{}, false), "r1")
if got.DataAddr != "" || got.CtrlAddr != "" || got.Reachable || got.Eligible || got.ReadyForPrimary {
t.Fatalf("r1 = %+v, want a placeholder (no foreign addresses or health)", got)
}
}
@@ -35,6 +35,7 @@ func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) {
}
defer p.Close()
s := openRecovered(t, p)
claimed := freshV1Claim(t, r)
if _, e = s.Write(0, block(0x72)); e != nil {
t.Fatal(e)
}
@@ -54,7 +55,7 @@ func TestHostCutLimitDoesNotGateGuestIO(t *testing.T) {
t.Fatal("limiter blocked read", e)
}
h, _ := r.GetHead(context.Background())
if h.Gen != 0 {
if h.Gen != claimed.Gen {
t.Fatal("refused cut published")
}
}
@@ -83,7 +83,13 @@ type chunkLineage struct {
// host blocks it until local recovery is done) the projection has epoch 0
// and is not healthy; a layer is never attached under that.
func chunkAuthority(proj frontend.Projection, volumeID string) bool {
return proj.VolumeID == volumeID && proj.Healthy && proj.Epoch > 0 && proj.ReplicaID != ""
return chunkAssignment(proj, volumeID) && proj.Healthy
}
// A sealed recovery is non-serving but its assigned identity can still answer
// the read-only plain-seal replay (INV-WS-SEAL-REPLAY-001).
func chunkAssignment(proj frontend.Projection, volumeID string) bool {
return proj.VolumeID == volumeID && proj.Epoch > 0 && proj.ReplicaID != ""
}
// chunkAuthorityGap names the projection fields that fail chunkAuthority,
@@ -367,10 +373,7 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
return nil, fmt.Errorf("durable: chunk remote for %s: %w", volumeID, err)
}
lin := chunkLineage{volumeID: proj.VolumeID, replicaID: proj.ReplicaID, epoch: proj.Epoch, endpoint: proj.EndpointVersion}
holder := p.cfg.ChunkHolder
if holder == "" {
holder = proj.ReplicaID
}
holder := p.chunkHolder(proj)
bound := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx}
if pace, ok := p.cfg.ChunkBudget.(interface {
WaitUpload(context.Context, int) error
@@ -413,18 +416,25 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
}
if !h.fresh {
// An existing local volume is this holder's image only while HEAD is
// still this holder's publication. Another holder's HEAD means the
// still this holder's publication (INV-WS-STALE-LOCAL-ROOT-001).
// Check again on the exact claim image before its CAS. Another holder means the
// workspace moved away and back: refuse rather than serve, or cut
// over, the newer image with the stale one.
head, err := remote.GetHead(ctx)
if err != nil {
return nil, fmt.Errorf("durable: read HEAD before attaching existing volume %s: %w", volumeID, err)
}
if head.Gen != 0 && head.Holder != holder {
err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD",
ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder)
log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)",
volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder)
cfg.PrepareRestore = func(head storage.ChunkHead) error {
if head.Gen != 0 && head.Holder != holder {
err := fmt.Errorf("%w: %w: volume %s local root %s, HEAD holder %q gen %d epoch %d, local holder %q; remove or quarantine the local root to attach fresh from HEAD",
ErrChunkStaleLocalRoot, storage.ErrChunkLayerFenced, volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder)
log.Printf("durable: refusing to attach volume=%s root=%s: HEAD holder=%q gen=%d epoch=%d is not this holder %q (remove or quarantine the local root)",
volumeID, h.path, head.Holder, head.Gen, head.Epoch, holder)
return err
}
return nil
}
if err := cfg.PrepareRestore(head); err != nil {
return nil, err
}
}
@@ -462,20 +472,18 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
// restore here, so HEAD is never claimed for a mis-ordered ship.
return h.backend.seedAndRebase(func() error { return ws.SeedChunkFrontier(head.RemoteLSN) })
}
claimStart := time.Now()
log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder)
head, err := storage.ClaimChunkHead(ctx, remote, cfg)
if err != nil {
log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err)
return nil, fmt.Errorf("durable: restore HEAD claim: %w", err)
}
claimed := "claimed"
if head.Gen == 0 {
claimed = "no HEAD to claim (new lineage)"
}
log.Printf("durable: HEAD claim for volume=%s done in %s: gen=%d epoch=%d holder=%q, %s", volumeID, time.Since(claimStart), head.Gen, head.Epoch, head.Holder, claimed)
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
}
// INV-WS-REOPEN-FENCE-001: local-root reopens claim too, without
// reseeding their acknowledged WAL or replacing it with remote absence.
claimStart := time.Now()
log.Printf("durable: HEAD claim for volume=%s starting: target epoch=%d holder=%q", volumeID, cfg.Epoch, cfg.Holder)
head, err := storage.ClaimChunkHead(ctx, remote, cfg)
if err != nil {
log.Printf("durable: HEAD claim for volume=%s failed after %s: %v", volumeID, time.Since(claimStart), err)
return nil, fmt.Errorf("durable: restore HEAD claim: %w", err)
}
log.Printf("durable: HEAD claim for volume=%s done in %s: gen=%d epoch=%d holder=%q", volumeID, time.Since(claimStart), head.Gen, head.Epoch, head.Holder)
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
layer, attachErr := storage.AttachChunkLayer(ws, remote, cfg)
if attachErr == nil {
@@ -1087,7 +1095,14 @@ var ErrPlainDetachBusy = errors.New("durable: plain detach requires idle fronten
// closing an idle frontend (including a closed handle). M5 PlainStop -> Quiesce uses
// only the caller context, not the live-serving freeze timer.
func (p *DurableProvider) DetachVolumePlain(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) {
return p.detachVolume(ctx, volumeID, true)
result, last, err := p.detachVolume(ctx, volumeID, true)
if err != nil && !errors.Is(err, ErrNotChunkVolume) && !errors.Is(err, ErrChunkAwaitingAuthority) {
return result, last, err
}
// INV-WS-SEAL-REPLAY-001: success is always a fresh remote proof, also
// after restart when no layer exists, including deferred authority startup.
// A cached result is not sufficient.
return p.replayPlainSeal(ctx, volumeID, result)
}
func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, plain bool) (storage.ChunkCutResult, uint64, error) {
@@ -90,7 +90,7 @@ func TestChunkAuthorityWaitLogsTheWaitTheClaimAndTheEnd(t *testing.T) {
[]string{"volume=v1: master authority after", `replica="r1" epoch=3 endpoint=1`, "first attach attempt"},
[]string{`HEAD claim for volume=v1 starting: target epoch=3 holder="r1"`},
[]string{`HEAD claim for volume=v1 observed HEAD gen=0 epoch=0 holder=""`, "; preparing"},
[]string{"HEAD claim for volume=v1 done in ", `gen=0 epoch=0 holder="", no HEAD to claim (new lineage)`},
[]string{"HEAD claim for volume=v1 done in ", `gen=1 epoch=3 holder="r1"`},
[]string{"chunk authority wait for volume=v1 ended after", ": attached after 1 attempt(s)"},
)
if strings.Count(got, "first attach attempt") != 1 {
@@ -19,17 +19,18 @@ func TestWALStoreChunk_CutVolumeReturnsInstalledHead(t *testing.T) {
remote := storage.NewMemChunkRemote()
p := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
r, err := p.CutVolume(ctx, "v1", 0)
head, _ := remote.GetHead(ctx)
// (r.Stats is W3's: its fields read zero until then.)
if err != nil || r.Noop || head.Gen != 1 || r.Head.Gen != head.Gen || r.H != s.NextLSN()-1 || r.Head.RemoteLSN != r.H {
if err != nil || r.Noop || head.Gen != claimed.Gen+1 || r.Head.Gen != head.Gen || r.H != s.NextLSN()-1 || r.Head.RemoteLSN != r.H {
t.Fatalf("cut: %+v %v; remote HEAD gen %d", r, err, head.Gen)
}
again, err := p.CutVolume(ctx, "v1", 0)
if err != nil || !again.Noop || again.Head.Gen != 1 || again.H != r.H {
if err != nil || !again.Noop || again.Head.Gen != r.Head.Gen || again.H != r.H {
t.Fatalf("cut with nothing new: %+v %v", again, err)
}
if _, err := p.CutVolume(ctx, "v9", 0); !errors.Is(err, durable.ErrVolumeNotOpen) {
@@ -241,6 +241,7 @@ func TestWALStoreChunk_CutVolumeRefusesUnwrittenMinLSNBeforePublishing(t *testin
remote := storage.NewMemChunkRemote()
p := chunkProvider(t, t.TempDir(), remote, v1View(), 0)
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
@@ -248,11 +249,11 @@ func TestWALStoreChunk_CutVolumeRefusesUnwrittenMinLSNBeforePublishing(t *testin
if _, err := p.CutVolume(ctx, "v1", last+1); err == nil {
t.Fatal("a cut to an LSN never written succeeded")
}
if head, _ := remote.GetHead(ctx); head.Gen != 0 || remote.Puts() != 0 {
if head, _ := remote.GetHead(ctx); head.Gen != claimed.Gen || remote.Puts() != 0 {
t.Fatalf("a refused minLSN published: HEAD gen %d, %d chunks stored", head.Gen, remote.Puts())
}
r, err := p.CutVolume(ctx, "v1", last)
if err != nil || r.H != last || r.Head.Gen != 1 {
if err != nil || r.H != last || r.Head.Gen != claimed.Gen+1 {
t.Fatalf("cut to the last written LSN: %+v %v", r, err)
}
}
@@ -237,6 +237,7 @@ func TestWALStoreChunk_LineageDriftRefusesCapture(t *testing.T) {
view := v1View()
p := chunkProvider(t, t.TempDir(), remote, view, 0)
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
@@ -248,7 +249,7 @@ func TestWALStoreChunk_LineageDriftRefusesCapture(t *testing.T) {
_, err := p.CaptureVolume(context.Background(), "v1")
head, _ := remote.GetHead(context.Background())
if drift == nil {
if err != nil || head.Gen != 1 {
if err != nil || head.Gen != claimed.Gen+1 {
t.Fatalf("capture under the attach lineage: %v (HEAD gen %d)", err, head.Gen)
}
return
@@ -256,7 +257,7 @@ func TestWALStoreChunk_LineageDriftRefusesCapture(t *testing.T) {
if !errors.Is(err, storage.ErrChunkCaptureRefused) {
t.Fatalf("capture after %s drift: %v; want refused", name, err)
}
if head.Gen != 0 || remote.Puts() != 0 {
if head.Gen != claimed.Gen || remote.Puts() != 0 {
t.Fatalf("capture after %s drift published: HEAD gen %d, %d chunks stored", name, head.Gen, remote.Puts())
}
})
@@ -273,6 +274,7 @@ func TestWALStoreChunk_LineageDriftDuringHeldUploadRefusesPublication(t *testing
view := v1View()
p := chunkProvider(t, t.TempDir(), g, view, 0)
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
if _, err := s.Write(1, block(1)); err != nil {
t.Fatal(err)
}
@@ -286,7 +288,7 @@ func TestWALStoreChunk_LineageDriftDuringHeldUploadRefusesPublication(t *testing
if err := recvErr(t, errc, "CaptureVolume"); !errors.Is(err, storage.ErrChunkCaptureRefused) {
t.Fatalf("capture whose lineage moved during upload: %v; want refused", err)
}
if head, _ := remote.GetHead(context.Background()); head.Gen != 0 {
if head, _ := remote.GetHead(context.Background()); head.Gen != claimed.Gen {
t.Fatalf("stale lineage published HEAD gen %d", head.Gen)
}
}
@@ -45,6 +45,7 @@ func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) {
remote := storage.NewMemChunkRemote()
p := schedProvider(t, remote, 0)
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
for c := uint32(0); c < 4; c++ { // four dirty chunks
if _, err := s.Write(c*pcChunkBlocks+1, block(byte(c+1))); err != nil {
t.Fatal(err)
@@ -52,7 +53,7 @@ func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) {
}
// A negative invariant: checked repeatedly over several scheduler polls.
for i := 0; i < 15; i++ {
if h := headGen(t, remote); h.Gen != 0 {
if h := headGen(t, remote); h.Gen != claimed.Gen {
t.Fatalf("a cut was published with the timer off (HEAD gen %d, %d chunks)", h.Gen, len(h.Chunks))
}
time.Sleep(100 * time.Millisecond)
@@ -61,7 +62,7 @@ func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) {
if _, err := p.CaptureVolume(context.Background(), "v1"); err != nil {
t.Fatal(err)
}
if h := headGen(t, remote); h.Gen == 0 || len(h.Chunks) != 4 {
if h := headGen(t, remote); h.Gen != claimed.Gen+1 || len(h.Chunks) != 4 {
t.Fatalf("explicit cut HEAD gen %d with %d chunks, want 4", h.Gen, len(h.Chunks))
}
}
@@ -73,6 +74,7 @@ func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) {
remote := storage.NewMemChunkRemote()
p := schedProvider(t, remote, interval)
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
begin := time.Now()
time.Sleep(2 * time.Second)
@@ -83,8 +85,8 @@ func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) {
t.Fatal(err)
}
explicit := time.Now()
if h := headGen(t, remote); h.Gen != 1 {
t.Fatalf("explicit cut: HEAD gen %d, want 1", h.Gen)
if h := headGen(t, remote); h.Gen != claimed.Gen+1 {
t.Fatalf("explicit cut: HEAD gen %d, want open claim + 1", h.Gen)
}
if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil {
t.Fatal(err)
@@ -95,13 +97,13 @@ func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) {
if time.Now().After(explicit.Add(interval - 300*time.Millisecond)) {
t.Skip("scheduling too slow to separate the two deadlines on this host")
}
if h := headGen(t, remote); h.Gen != 1 {
if h := headGen(t, remote); h.Gen != claimed.Gen+1 {
t.Fatalf("automatic cut %s after the explicit one (HEAD gen %d): the timer did not restart", time.Since(explicit), h.Gen)
}
// Progress, no timer (#227): the automatic cut follows; a loaded host only
// delays it (the early-cut check above is the timing assertion, and it
// skips when the host cannot separate the two deadlines).
for headGen(t, remote).Gen < 2 {
for headGen(t, remote).Gen < claimed.Gen+2 {
time.Sleep(50 * time.Millisecond)
}
}
@@ -186,6 +188,7 @@ func TestWALStoreChunk_PublishSettledHook(t *testing.T) {
}
t.Cleanup(func() { _ = p.Close() })
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote)
for i, lba := range []uint32{1, 0, pcChunkBlocks + 1} {
if lba != 0 {
if _, err := s.Write(lba, block(byte(i+1))); err != nil {
@@ -198,8 +201,10 @@ func TestWALStoreChunk_PublishSettledHook(t *testing.T) {
}
mu.Lock()
defer mu.Unlock()
if len(got) != 2 || got[0] != "v1:0->1" || got[1] != "v1:1->2" {
t.Fatalf("reports %v; want [v1:0->1 v1:1->2] (the middle capture changed nothing)", got)
wantFirst := fmt.Sprintf("v1:%d->%d", claimed.Gen, claimed.Gen+1)
wantSecond := fmt.Sprintf("v1:%d->%d", claimed.Gen+1, claimed.Gen+2)
if len(got) != 2 || got[0] != wantFirst || got[1] != wantSecond {
t.Fatalf("reports %v; want [%s %s] (the middle capture changed nothing)", got, wantFirst, wantSecond)
}
}
@@ -261,6 +266,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) {
return loopEvent{}
}
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote.MemChunkRemote)
begin := time.Now() // the loop started during open: its first deadline is at most begin + interval
if _, err := s.Write(1, block(0x01)); err != nil {
t.Fatal(err)
@@ -307,8 +313,8 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) {
t.Fatal("the explicit cut did not finish")
}
explicitAt := time.Now()
if h := headGen(t, remote); h.Gen != 1 {
t.Fatalf("explicit cut: HEAD gen %d, want 1", h.Gen)
if h := headGen(t, remote); h.Gen != claimed.Gen+1 {
t.Fatalf("explicit cut: HEAD gen %d, want open claim + 1", h.Gen)
}
if _, err := s.Write(pcChunkBlocks+1, block(0x02)); err != nil {
t.Fatal(err)
@@ -335,7 +341,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) {
if cut2.event != "cut" || cut2.skipped {
t.Fatalf("loop event %+v; want the next periodic cut taken", cut2)
}
if h := headGen(t, remote); h.Gen != 2 {
t.Fatalf("after the next periodic cut: HEAD gen %d, want 2", h.Gen)
if h := headGen(t, remote); h.Gen != claimed.Gen+2 {
t.Fatalf("after the next periodic cut: HEAD gen %d, want open claim + 2", h.Gen)
}
}
@@ -54,6 +54,20 @@ func openRecovered(t *testing.T, p *durable.DurableProvider) storage.LogicalStor
return s
}
// freshV1Claim is only for fresh v1View fixtures, never reopened/local roots.
// INV-WS-CLAIM-BEFORE-SERVE-001: validate the open before using its baseline.
func freshV1Claim(t *testing.T, remote *storage.MemChunkRemote) storage.ChunkHead {
t.Helper()
head := headHolder(t, remote)
assigned := v1View().Projection()
if head.Gen != 1 || head.Epoch != assigned.Epoch || head.Holder != assigned.ReplicaID ||
head.State != storage.ChunkHeadActive || head.RemoteLSN != 0 || head.DetachedBy != nil ||
len(head.Chunks) != 0 || len(head.Segments) != 0 || head.ManifestChunkCount != 0 || head.ChunkBytes != 0 || remote.Puts() != 0 {
t.Fatalf("fresh open did not establish exactly one empty assigned active claim: HEAD=%+v PUTs=%d", head, remote.Puts())
}
return head
}
func block(fill byte) []byte { return bytes.Repeat([]byte{fill}, 4096) }
func headBlock(t *testing.T, remote *storage.MemChunkRemote, lba uint32) []byte {
@@ -197,6 +197,7 @@ func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) {
}
t.Cleanup(func() { _ = p.Close() })
s := openRecovered(t, p)
claimed := freshV1Claim(t, remote.MemChunkRemote)
if _, err = s.Write(1, block(0x48)); err != nil {
t.Fatal(err)
}
@@ -205,7 +206,7 @@ func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) {
t.Fatalf("whole cut did not expire: %v", err)
}
h, err := remote.GetHead(context.Background())
if err != nil || h.Gen != 0 {
if err != nil || h.Gen != claimed.Gen {
t.Fatalf("expired upload published: %+v %v", h, err)
}
}
@@ -0,0 +1,229 @@
package durable_test
import (
"context"
"errors"
"reflect"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type plainSealReplayRemote struct {
*storage.MemChunkRemote
mu sync.Mutex
loseSeal, unreadable bool
reads, cas int
corrupt func(*storage.ChunkHead)
}
func (r *plainSealReplayRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
r.mu.Lock()
r.reads++
unreadable, corrupt := r.unreadable, r.corrupt
r.mu.Unlock()
if unreadable {
return storage.ChunkHead{}, errInjected
}
h, err := r.MemChunkRemote.GetHead(ctx)
if corrupt != nil {
corrupt(&h)
}
return h, err
}
func (r *plainSealReplayRemote) CASHead(ctx context.Context, v storage.ChunkHeadVersion, h storage.ChunkHead) (uint64, error) {
r.mu.Lock()
r.cas++
lose := r.loseSeal && h.State == storage.ChunkHeadDetached
r.mu.Unlock()
gen, err := r.MemChunkRemote.CASHead(ctx, v, h)
if err == nil && lose {
r.mu.Lock()
r.unreadable = true
r.mu.Unlock()
return 0, errInjected
}
return gen, err
}
func TestPlainSealLostAnswerRestartReplaysFilerProof(t *testing.T) {
ctx := hangGuard(t)
r := &plainSealReplayRemote{MemChunkRemote: storage.NewMemChunkRemote()}
root := t.TempDir()
first := chunkProvider(t, root, r, v1View(), 0)
s := openRecovered(t, first)
writeSync(t, s, 1, 0x42)
r.mu.Lock()
r.loseSeal = true
r.mu.Unlock()
if _, _, err := first.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
t.Fatal("seal did not lose its committed answer", err)
}
sealed := headHolder(t, r.MemChunkRemote)
if sealed.State != storage.ChunkHeadDetached {
t.Fatal("seal was not actually committed")
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
r.mu.Lock()
r.loseSeal, r.unreadable = false, false
r.mu.Unlock()
view := v1View()
second := chunkProvider(t, root, r, view, 0)
if _, err := second.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := second.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) {
t.Fatal("restart must keep the sealed incarnation non-serving", err)
}
// Startup reports the sealed recovery failure and remains non-serving;
// the assigned identity must still be able to answer this read-only retry.
notServing := view.Projection()
notServing.Healthy = false
view.set(notServing)
r.mu.Lock()
reads, cas := r.reads, r.cas
r.mu.Unlock()
result, last, err := second.DetachVolumePlain(ctx, "v1")
if err != nil || !reflect.DeepEqual(result.Head, sealed) || result.H != sealed.RemoteLSN || last != sealed.RemoteLSN {
t.Fatalf("re-sent seal did not return the original filer proof: result=%+v last=%d err=%v", result, last, err)
}
r.mu.Lock()
gotReads, gotCAS := r.reads, r.cas
r.mu.Unlock()
if gotReads <= reads || gotCAS != cas || !reflect.DeepEqual(headHolder(t, r.MemChunkRemote), sealed) {
t.Fatal("replay used no filer read or published a new generation")
}
for _, tc := range []struct {
name string
mutate func(*storage.ChunkHead)
}{
{"active", func(h *storage.ChunkHead) { h.State = storage.ChunkHeadActive; h.DetachedBy = nil }},
{"holder", func(h *storage.ChunkHead) { h.Holder = "other" }},
{"epoch", func(h *storage.ChunkHead) { h.Epoch++ }},
{"missing-proof", func(h *storage.ChunkHead) { h.DetachedBy = nil }},
{"proof-generation", func(h *storage.ChunkHead) { h.DetachedBy.Gen++ }},
{"proof-holder", func(h *storage.ChunkHead) { h.DetachedBy.Holder = "other" }},
{"proof-epoch", func(h *storage.ChunkHead) { h.DetachedBy.Epoch++ }},
} {
t.Run(tc.name, func(t *testing.T) {
r.mu.Lock()
r.corrupt = tc.mutate
r.mu.Unlock()
defer func() { r.mu.Lock(); r.corrupt = nil; r.mu.Unlock() }()
if _, _, err := second.DetachVolumePlain(ctx, "v1"); err == nil {
t.Fatal("invalid filer proof returned success")
}
})
}
initial := view.Projection()
r.mu.Lock()
r.corrupt = func(*storage.ChunkHead) { moved := initial; moved.EndpointVersion++; view.set(moved) }
r.mu.Unlock()
if _, _, err := second.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrChunkEpochStale) {
t.Fatal("replay ignored authority movement during its read", err)
}
view.set(initial)
r.mu.Lock()
r.corrupt = nil
r.unreadable = true
r.mu.Unlock()
if _, _, err := second.DetachVolumePlain(ctx, "v1"); err == nil {
t.Fatal("unreadable filer returned a cached seal")
}
r.mu.Lock()
r.unreadable = false
r.mu.Unlock()
ended, cancel := context.WithCancel(ctx)
cancel()
if _, _, err := second.DetachVolumePlain(ended, "v1"); !errors.Is(err, context.Canceled) {
t.Fatal("replay hid caller cancellation", err)
}
if err := second.Close(); err != nil {
t.Fatal(err)
}
if _, _, err := second.DetachVolumePlain(ctx, "v1"); err == nil {
t.Fatal("closed provider replayed a seal")
}
}
func TestPlainSealReplayNeverUsesProcessMemory(t *testing.T) {
ctx := hangGuard(t)
r := &plainSealReplayRemote{MemChunkRemote: storage.NewMemChunkRemote()}
p := chunkProvider(t, t.TempDir(), r, v1View(), 0)
s := openRecovered(t, p)
writeSync(t, s, 1, 0x53)
if _, _, err := p.DetachVolumePlain(ctx, "v1"); err != nil {
t.Fatal(err)
}
r.mu.Lock()
r.unreadable = true
r.mu.Unlock()
if _, _, err := p.DetachVolumePlain(ctx, "v1"); err == nil {
t.Fatal("re-sent plain seal answered from process memory despite unreadable filer")
}
}
// INV-WS-SEAL-REPLAY-001: deferred healthy startup must not hide a filer seal.
func TestPlainSealReplayDuringDeferredAuthorityStartup(t *testing.T) {
ctx := hangGuard(t)
r := &plainSealReplayRemote{MemChunkRemote: storage.NewMemChunkRemote()}
root := t.TempDir()
first := chunkProvider(t, root, r, v1View(), 0)
s := openRecovered(t, first)
writeSync(t, s, 1, 0x64)
r.mu.Lock()
r.loseSeal = true
r.mu.Unlock()
if _, _, err := first.DetachVolumePlain(ctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) {
t.Fatal("seal did not lose its committed answer", err)
}
sealed := headHolder(t, r.MemChunkRemote)
if err := first.Close(); err != nil {
t.Fatal(err)
}
r.mu.Lock()
r.loseSeal, r.unreadable = false, false
r.mu.Unlock()
view := v1View()
assigned := view.Projection()
assigned.Healthy = false
view.set(assigned)
second := chunkProvider(t, root, r, view, 0)
if _, err := second.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := second.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
// This is the actual awaiting/no-layer schedule, before any healthy attach.
if _, err := second.CaptureVolume(ctx, "v1"); !errors.Is(err, durable.ErrChunkAwaitingAuthority) {
t.Fatal("recovery did not enter deferred authority startup", err)
}
r.mu.Lock()
reads, cas := r.reads, r.cas
r.mu.Unlock()
result, last, err := second.DetachVolumePlain(ctx, "v1")
if err != nil || !reflect.DeepEqual(result.Head, sealed) || result.H != sealed.RemoteLSN || last != sealed.RemoteLSN {
t.Fatalf("awaiting restart did not replay exact filer proof: result=%+v last=%d err=%v", result, last, err)
}
r.mu.Lock()
gotReads, gotCAS := r.reads, r.cas
r.mu.Unlock()
if gotReads <= reads || gotCAS != cas || !reflect.DeepEqual(headHolder(t, r.MemChunkRemote), sealed) {
t.Fatal("replay skipped filer proof or changed sealed HEAD")
}
if view.Projection().Healthy {
t.Fatal("replay made the projection healthy")
}
if _, err := second.CaptureVolume(ctx, "v1"); !errors.Is(err, durable.ErrChunkAwaitingAuthority) {
t.Fatal("replay enabled unhealthy cuts", err)
}
if err := second.Close(); err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,109 @@
package durable_test
import (
"bytes"
"context"
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type reopenClaimRaceRemote struct {
storage.ChunkRemote
foreign storage.ChunkHead
reads int
}
func (r *reopenClaimRaceRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
h, err := r.ChunkRemote.GetHead(ctx)
if err != nil {
return h, err
}
r.reads++
if r.reads == 1 {
// The early local-root check sees our publication. Before the claim's
// independent read, another holder publishes below the current epoch.
if _, err := r.ChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, r.foreign); err != nil {
return storage.ChunkHead{}, err
}
}
return h, nil
}
func TestLocalReopenRejectsForeignClaimImage(t *testing.T) {
ctx := hangGuard(t)
r := storage.NewMemChunkRemote()
root := t.TempDir()
first := chunkProvider(t, root, r, viewAs("rA", 3), 0)
s := openRecovered(t, first)
writeSync(t, s, 0, 0x31)
if _, err := first.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
writeSync(t, s, 1, 0x42)
if err := first.Close(); err != nil {
t.Fatal(err)
}
foreign := headHolder(t, r)
foreign.Epoch, foreign.Holder = 4, "rB"
race := &reopenClaimRaceRemote{ChunkRemote: r, foreign: foreign}
second := chunkProvider(t, root, race, viewAs("rA", 5), 0)
if _, err := second.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
_, err := second.RecoverVolume(ctx, "v1")
if !errors.Is(err, durable.ErrChunkStaleLocalRoot) || !errors.Is(err, storage.ErrChunkLayerFenced) {
t.Errorf("foreign claim image admitted over local WAL: %v", err)
}
if race.reads < 2 {
t.Fatal("control did not reach the independent claim observation")
}
if after := headHolder(t, r); after.Epoch != 4 || after.Holder != "rB" || after.Gen != foreign.Gen+1 {
t.Errorf("refused reopen changed the foreign HEAD: %+v", after)
}
be, err := second.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if _, err := be.Read(ctx, 0, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) {
t.Errorf("foreign claim image exposed I/O: %v", err)
}
if got, err := second.LogicalStorage("v1").Read(1); err != nil || !bytes.Equal(got, block(0x42)) {
t.Errorf("refusal changed acknowledged local bytes: %v", err)
}
}
func TestLocalReopenClaimsBeforeServing(t *testing.T) {
ctx := hangGuard(t)
r := storage.NewMemChunkRemote()
root := t.TempDir()
first := chunkProvider(t, root, r, v1View(), 0)
s := openRecovered(t, first)
writeSync(t, s, 0, 0x31)
if _, err := first.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
before := headHolder(t, r)
writeSync(t, s, 1, 0x42) // locally acknowledged, not yet in HEAD
if err := first.Close(); err != nil {
t.Fatal(err)
}
second := chunkProvider(t, root, r, v1View(), 0)
s = openRecovered(t, second)
after := headHolder(t, r)
if after.Gen <= before.Gen || after.Epoch != before.Epoch || after.Holder != before.Holder || after.RemoteLSN != before.RemoteLSN {
t.Errorf("local reopen served without replacing the old CAS guard: before=%+v after=%+v", before, after)
}
if got, err := s.Read(1); err != nil || !bytes.Equal(got, block(0x42)) {
t.Fatal("claim replaced locally acknowledged bytes with HEAD", err)
}
if _, err := second.CaptureVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
if !bytes.Equal(headBlock(t, r, 0), block(0x31)) || !bytes.Equal(headBlock(t, r, 1), block(0x42)) {
t.Fatal("reopen did not publish the complete acknowledged image")
}
}
@@ -0,0 +1,75 @@
package durable
import (
"context"
"fmt"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func (p *DurableProvider) chunkHolder(proj frontend.Projection) string {
if p.cfg.ChunkHolder != "" {
return p.cfg.ChunkHolder
}
return proj.ReplicaID
}
// replayPlainSeal implements M5 PlainSeal -> RemoteProof. It also works when
// RecoverVolume refused a sealed incarnation and installed no local layer.
func (p *DurableProvider) replayPlainSeal(ctx context.Context, volumeID string, result storage.ChunkCutResult) (storage.ChunkCutResult, uint64, error) {
p.mu.Lock()
h, ok := p.volumes[volumeID]
if p.closed || !ok {
p.mu.Unlock()
return storage.ChunkCutResult{}, 0, ErrVolumeNotOpen
}
if h.impl != ImplWALStoreChunk {
p.mu.Unlock()
return storage.ChunkCutResult{}, 0, ErrNotChunkVolume
}
p.inflight.Add(1) // Close cannot pass its join before this admitted read.
p.mu.Unlock()
defer p.inflight.Done()
h.attachMu.Lock()
defer h.attachMu.Unlock()
if err := ctx.Err(); err != nil {
return storage.ChunkCutResult{}, 0, err
}
proj := p.view.Projection()
if !chunkAssignment(proj, volumeID) {
return storage.ChunkCutResult{}, 0, ErrChunkNotPrimary
}
lin := chunkLineage{volumeID: proj.VolumeID, replicaID: proj.ReplicaID, epoch: proj.Epoch, endpoint: proj.EndpointVersion}
if h.chunkLineage != (chunkLineage{}) && h.chunkLineage != lin {
return storage.ChunkCutResult{}, 0, ErrChunkEpochStale
}
if err := h.backend.stopPlainDetachIfIdle(); err != nil {
// A seal may already have committed before this read-back. Do not
// expose the before-mutation plain_detach_busy promise here.
return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: replay admission: %v", ErrDetachOutcomeUnknown, err)
}
h.chunkDetach = true
p.stopChunkLoop(h)
inner, err := p.cfg.ChunkRemoteFor(volumeID)
if err != nil {
return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w", ErrDetachOutcomeUnknown, err)
}
remote := &closeBoundRemote{ChunkRemote: inner, done: p.closeCtx}
head, err := storage.ReadDetachedChunkHead(ctx, remote, proj.Epoch, p.chunkHolder(proj))
if err != nil {
return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w", ErrDetachOutcomeUnknown, err)
}
current := p.view.Projection()
if current.VolumeID != lin.volumeID || current.ReplicaID != lin.replicaID || current.Epoch != lin.epoch || current.EndpointVersion != lin.endpoint {
return storage.ChunkCutResult{}, 0, ErrChunkEpochStale
}
if err := ctx.Err(); err != nil {
return storage.ChunkCutResult{}, 0, err
}
if p.closeCtx.Err() != nil {
return storage.ChunkCutResult{}, 0, errProviderClosed
}
result.H, result.Head = head.RemoteLSN, head
return result, head.RemoteLSN, nil
}
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"errors"
"fmt"
"sync/atomic"
"testing"
@@ -76,63 +77,68 @@ func TestRestoreSeedPrecedesTakeoverCAS(t *testing.T) {
t.Logf("VOLUME check -> seed nextLSN=%d/durable=%d -> takeover -> serve", nextAtCAS, durableAtCAS)
}
// A restored restart under the same assignment must reactivate a detached
// image before exposing I/O, not treat it as an already-settled active claim.
func TestRestoreEqualOwnerDetachedHEADIsReactivated(t *testing.T) {
ctx := hangGuard(t)
remote := storage.NewMemChunkRemote()
makeProvider := func() *durable.DurableProvider {
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "node-a/r1",
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
return p
}
source := makeProvider()
openRecovered(t, source)
be, err := source.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
want := block(0xA7)
if _, err = be.Write(ctx, 4096, want); err != nil {
t.Fatal(err)
}
if err = be.Sync(ctx); err != nil {
t.Fatal(err)
}
cut, _, err := source.DetachVolume(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if err = source.Close(); err != nil {
t.Fatal(err)
}
restarted := makeProvider()
if _, err = restarted.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err = restarted.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
h, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if h.Gen <= cut.Head.Gen || h.Epoch != cut.Head.Epoch || h.Holder != cut.Head.Holder || h.State != storage.ChunkHeadActive || h.DetachedBy != nil || h.RemoteLSN != cut.H {
t.Errorf("ready with stale detached proof: HEAD=%+v detached=%+v", h, cut.Head)
}
frontend, err := restarted.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
got := make([]byte, 4096)
if _, err = frontend.Read(ctx, 4096, got); err != nil {
t.Fatal(err)
}
if !bytes.Equal(got, want) {
t.Fatal("restart changed exact data")
// A storage restart between the successful plain seal and teardown must not
// erase the proof the planned new host needs. Neither local-root nor fresh
// same-assignment reopen may reactivate it or expose I/O.
func TestRestoreEqualOwnerDetachedHEADStaysSealed(t *testing.T) {
for _, local := range []bool{false, true} {
t.Run(fmt.Sprint(local), func(t *testing.T) {
ctx := hangGuard(t)
remote := storage.NewMemChunkRemote()
root := t.TempDir()
makeProvider := func(root string, view *stubView, holder string) *durable.DurableProvider {
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: holder,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
return p
}
source := makeProvider(root, v1View(), "node-a/r1")
s := openRecovered(t, source)
want := block(0xA7)
writeSync(t, s, 1, 0xA7)
cut, _, err := source.DetachVolumePlain(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if err := source.Close(); err != nil {
t.Fatal(err)
}
if !local {
root = t.TempDir()
}
restarted := makeProvider(root, v1View(), "node-a/r1")
if _, err := restarted.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
if _, err := restarted.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) {
t.Errorf("sealed incarnation reopened for serving: %v", err)
}
h := headHolder(t, remote)
if h.Gen != cut.Head.Gen || h.Epoch != cut.Head.Epoch || h.Holder != cut.Head.Holder || h.State != storage.ChunkHeadDetached || h.DetachedBy == nil || *h.DetachedBy != *cut.Head.DetachedBy || h.RemoteLSN != cut.H {
t.Errorf("restart changed sealed proof: HEAD=%+v seal=%+v", h, cut.Head)
}
be, err := restarted.Open(ctx, "v1")
if err != nil {
t.Fatal(err)
}
if _, err := be.Read(ctx, 4096, make([]byte, 4096)); !errors.Is(err, frontend.ErrNotReady) {
t.Errorf("sealed restart exposed I/O: %v", err)
}
if !bytes.Equal(headBlock(t, remote, 1), want) {
t.Fatal("restart changed sealed bytes")
}
planned := makeProvider(t.TempDir(), viewAs("r2", 4), "node-b/r2")
loaded := openRecovered(t, planned)
if got, err := loaded.Read(1); err != nil || !bytes.Equal(got, want) {
t.Fatal("planned new holder could not load sealed image", err)
}
taken := headHolder(t, remote)
if taken.State != storage.ChunkHeadActive || taken.Epoch != 4 || taken.Holder != "node-b/r2" || taken.Gen <= cut.Head.Gen || taken.RemoteLSN != cut.H {
t.Fatalf("planned takeover did not consume preserved seal: %+v", taken)
}
})
}
}
@@ -7,6 +7,7 @@ package volume
import (
"context"
"errors"
"reflect"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
@@ -68,6 +69,16 @@ func TestChunkControl_CutToUnwrittenMinLSNPublishesNothing(t *testing.T) {
if _, err := dp.RecoverVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
claimed, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
assigned := (healthyView{}).Projection()
if claimed.Gen != 1 || claimed.Epoch != assigned.Epoch || claimed.Holder != assigned.ReplicaID ||
claimed.State != storage.ChunkHeadActive || claimed.RemoteLSN != 0 || claimed.DetachedBy != nil ||
len(claimed.Chunks) != 0 || len(claimed.Segments) != 0 || claimed.ManifestChunkCount != 0 || claimed.ChunkBytes != 0 || remote.Puts() != 0 {
t.Fatalf("fresh open did not establish exactly one empty assigned active claim: HEAD=%+v PUTs=%d", claimed, remote.Puts())
}
if _, err := s.Write(1, make([]byte, 4096)); err != nil {
t.Fatal(err)
}
@@ -80,10 +91,10 @@ func TestChunkControl_CutToUnwrittenMinLSNPublishesNothing(t *testing.T) {
if _, err := ctl.Cut(ctx, "v1", last+5); err == nil {
t.Fatal("a cut to an LSN never written succeeded")
}
if head, _ := remote.GetHead(ctx); head.Gen != 0 || remote.Puts() != 0 {
t.Fatalf("a refused minLSN published: HEAD gen %d, %d chunks stored", head.Gen, remote.Puts())
if head, err := remote.GetHead(ctx); err != nil || !reflect.DeepEqual(head, claimed) || remote.Puts() != 0 {
t.Fatalf("a refused minLSN published beyond the open claim: HEAD %+v (claim %+v), %d chunks stored, err=%v", head, claimed, remote.Puts(), err)
}
if r, err := ctl.Cut(ctx, "v1", last); err != nil || r.CutLSN != last || r.HeadGen != 1 {
if r, err := ctl.Cut(ctx, "v1", last); err != nil || r.CutLSN != last || r.HeadGen != claimed.Gen+1 {
t.Fatalf("cut to the last written LSN: %+v %v", r, err)
}
}
@@ -250,7 +250,7 @@ func TestHeadBeltRetryOfUnconfirmedClaimStillCools(t *testing.T) {
if _, err := ClaimChunkHead(retryCtx, f, ChunkLayerConfig{Epoch: 2, Holder: "new", HeadCoolingWindow: chunkHeadOperationTimeout + chunkHeadSettleTime}); err != nil {
t.Fatal(err)
}
if time.Since(start) < chunkHeadOperationTimeout+chunkHeadSettleTime || f.stats().cas != 1 {
t.Fatal("retry bypassed cooling or replayed a settled claim")
if time.Since(start) < chunkHeadOperationTimeout+chunkHeadSettleTime || f.stats().cas != 2 {
t.Fatal("retry bypassed cooling or failed to fence the previous incarnation")
}
}
@@ -191,7 +191,8 @@ func assertPrecopyMeasuredRefusal(t *testing.T, report PrecopyReport, err error)
t.Helper()
if !errors.Is(err, ErrPrecopyNotConverged) || report.Frozen ||
report.Estimate <= 1200*time.Millisecond ||
(report.Reason != "tail_too_large" && report.Reason != "barrier_over_budget") {
(report.Reason != "tail_too_large" && report.Reason != "barrier_over_budget" &&
!(report.Reason == "freeze_budget_exceeded" && report.Estimate > precopyFreezeLimit)) {
t.Fatalf("not a valid measured over-budget refusal: report=%+v err=%v", report, err)
}
}
@@ -0,0 +1,121 @@
package storage
import (
"bytes"
"context"
"errors"
"fmt"
"testing"
)
// A server-held CAS outlives its caller. No old-process code runs after the
// reopen: releaseDeferredCAS only evaluates the request's original guard.
func TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS(t *testing.T) {
for _, gen := range []uint64{0, 7} {
t.Run(fmt.Sprint(gen), func(t *testing.T) {
r := newFakeChunkRemote()
if gen != 0 {
r.head = ChunkHead{Gen: gen, Epoch: 2, Holder: "host-a", Chunks: map[uint64]ChunkRef{}}
}
old := copyHead(r.head)
old.Epoch, old.Holder = 2, "host-a"
old.RemoteLSN = 1
r.casModes = []fakeCASMode{casDeferred}
if _, err := r.CASHead(context.Background(), ChunkHeadVersion{Gen: gen, Epoch: r.head.Epoch}, old); !errors.Is(err, errFakeCASUnknown) {
t.Fatal("old cut was not left in flight", err)
}
claimed, err := ClaimChunkHead(context.Background(), r, ctConfig(2))
if err != nil {
t.Fatal(err)
}
if n := r.releaseDeferredCAS(); n != 0 {
t.Fatalf("killed process CAS landed after reopen: applied=%d claimedGen=%d", n, claimed.Gen)
}
if claimed.Gen != gen+1 || claimed.RemoteLSN != 0 || claimed.Epoch != 2 || claimed.Holder != "host-a" {
t.Fatalf("reopen must fence the old generation without changing the image or owner: %+v", claimed)
}
})
}
}
func TestClaimChunkHeadSameOwnerReopenPreservesSeal(t *testing.T) {
r := newFakeChunkRemote()
r.head = ChunkHead{Gen: 7, Epoch: 2, Holder: "host-a", RemoteLSN: 3,
State: ChunkHeadDetached, DetachedBy: &ChunkDetachedBy{Gen: 7, Epoch: 2, Holder: "host-a"}}
sealed := copyHead(r.head)
cfg := ctConfig(2)
prepared := false
cfg.PrepareRestore = func(ChunkHead) error { prepared = true; return nil }
_, err := ClaimChunkHead(context.Background(), r, cfg)
if !errors.Is(err, ErrChunkLayerDetached) || prepared || r.stats().cas != 0 || !sameHead(r.stats().head, sealed) {
t.Fatalf("reopen undid seal: err=%v prepared=%t CAS=%d HEAD=%+v", err, prepared, r.stats().cas, r.stats().head)
}
// The planned new holder can consume the sealed image at a higher epoch;
// it is a takeover, not a reopen of the sealed incarnation.
next, err := ClaimChunkHead(context.Background(), r, ChunkLayerConfig{Epoch: 3, Holder: "host-b"})
if err != nil || next.Gen != 8 || next.RemoteLSN != 3 || next.State != ChunkHeadActive || next.DetachedBy != nil {
t.Fatalf("planned holder cannot claim preserved seal: HEAD=%+v err=%v", next, err)
}
}
func TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites(t *testing.T) {
s, path, crash := crashableStore(t)
r := newFakeChunkRemote()
cfg := ctConfig(2)
old := mustAttach(t, s, r, cfg)
a := makeBlock(4096, 0x31)
b := makeBlock(4096, 0x42)
c := makeBlock(4096, 0x53)
if _, err := s.Write(0, a); err != nil {
t.Fatal(err)
}
if _, err := old.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
if _, err := s.Write(1, b); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
r.casModes = []fakeCASMode{casDeferred}
if _, err := old.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) {
t.Fatal("old cut was not unresolved", err)
}
// Close removes the old local publisher but cannot cancel a request already
// retained by the server. It also must preserve that request's intent.
if err := old.Close(); err != nil {
t.Fatal(err)
}
crash()
s, _ = reopen(t, path)
claimed, err := ClaimChunkHead(ctTimeout(t), r, cfg)
if err != nil {
t.Fatal(err)
}
next := mustAttach(t, s, r, cfg)
landed := r.releaseDeferredCAS()
if _, err := s.Write(2, c); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
_, firstErr := next.Cut(ctTimeout(t))
if firstErr != nil {
t.Logf("new process first CAS after late request: %v; fenced=%t", firstErr, next.Fenced())
if _, err := next.Cut(ctTimeout(t)); err != nil {
t.Fatal("retry lost the new process's progress", err)
}
}
image := r.imageOf(t, r.stats().head)
for i, want := range [][]byte{a, b, c} {
got, err := s.Read(uint32(i))
if err != nil || !bytes.Equal(got, want) || !bytes.Equal(image[i*4096:(i+1)*4096], want) {
t.Fatalf("acknowledged block %d lost locally or remotely: %v", i, err)
}
}
if landed != 0 || firstErr != nil {
t.Fatalf("reopen did not exclude old CAS: landed=%d claimedGen=%d firstErr=%v (all acknowledged bytes survived retry)", landed, claimed.Gen, firstErr)
}
}
+9 -13
View File
@@ -37,6 +37,11 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi
if head.Epoch > cfg.Epoch || (head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder != cfg.Holder) {
return ChunkHead{}, ErrChunkLayerFenced
}
// INV-WS-SEALED-REOPEN-001: the sealing incarnation cannot reopen its
// committed handoff proof. A higher-epoch takeover remains a separate claim.
if chunkHeadIsDetached(head) && head.Epoch == cfg.Epoch && head.Holder == cfg.Holder {
return copyHead(head), ErrChunkLayerDetached
}
// Preparation uses exactly the validated image this CAS will protect.
// A failing seed cannot fence the old holder before this host is ready.
if cfg.PrepareRestore != nil {
@@ -47,19 +52,10 @@ func ClaimChunkHead(ctx context.Context, remote ChunkRemote, cfg ChunkLayerConfi
if err := allowed(); err != nil {
return ChunkHead{}, err
}
// No HEAD is a new volume, not a restore: there is no old holder to
// fence. The first content cut keeps exclusive-create semantics.
if head.Gen == 0 {
return head, nil
}
if head.Gen != 0 && head.Epoch == cfg.Epoch && head.Holder == cfg.Holder && !chunkHeadIsDetached(head) && head.DetachedBy == nil {
// A previous claim may have committed but timed out during cooling.
// An identical root alone does not prove that wait completed.
if err := confirmChunkTakeover(ctx, remote, head, cfg.HeadCoolingWindow); err != nil {
return ChunkHead{}, err
}
return head, allowed() // idempotent restart or settled prior claim
}
// INV-WS-HEAD-BELT-001: even the same owner must replace the generation
// before serving. A killed incarnation may have left a CAS in flight;
// readback alone cannot invalidate that request's original precondition.
// An empty HEAD also needs an exclusive create before an old first cut.
next := copyHead(head)
next.Epoch, next.Holder = cfg.Epoch, cfg.Holder
// A new holder's takeover starts serving the same image as active. The
@@ -75,13 +75,13 @@ func TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift(t *testing.T) {
if err == nil || after.Gen != before.Gen || after.Epoch != 3 {
t.Fatalf("drift published: head=%+v err=%v", after, err)
}
// An identical already-settled claim is idempotent and creates no new gen.
// Reopening the same owner preserves the image but fences its old generation.
if _, err := ClaimChunkHead(context.Background(), remote, ChunkLayerConfig{Epoch: 3, Holder: "current"}); err != nil {
t.Fatal(err)
}
final, _ := remote.GetHead(context.Background())
if final.Gen != before.Gen {
t.Fatal("idempotent claim advanced HEAD")
if final.Gen != before.Gen+1 || final.RemoteLSN != before.RemoteLSN {
t.Fatal("same-owner reopen did not replace only the generation")
}
}
@@ -0,0 +1,27 @@
package storage
import (
"context"
"fmt"
)
// ReadDetachedChunkHead implements INV-WS-SEAL-REPLAY-001. A re-sent seal
// succeeds only on this remote observation, never on a remembered result or
// a generation comparison with a previously observed root. It writes nothing.
func ReadDetachedChunkHead(ctx context.Context, remote ChunkRemote, epoch uint64, holder string) (ChunkHead, error) {
if remote == nil || epoch == 0 || holder == "" {
return ChunkHead{}, fmt.Errorf("%w: seal replay needs remote and assigned owner", ErrChunkCaptureRefused)
}
head, err := readChunkHead(ctx, remote)
if err != nil {
return ChunkHead{}, err
}
if head.Epoch != epoch || head.Holder != holder {
return ChunkHead{}, ErrChunkLayerFenced
}
proof := head.DetachedBy
if head.Gen == 0 || !chunkHeadIsDetached(head) || proof == nil || proof.Gen != head.Gen || proof.Epoch != epoch || proof.Holder != holder {
return ChunkHead{}, fmt.Errorf("%w: HEAD is not this owner's exact detached proof", ErrChunkCASOutcomeUnknown)
}
return copyHead(head), nil
}
+17 -6
View File
@@ -172,13 +172,13 @@ stateDiagram-v2
}
state "HEAD holder" as H {
[*] --> Attaching
Attaching --> Claiming: fresh local root
Attaching --> Holder: existing root, HEAD is this holder's
Attaching --> Claiming: fresh or same-holder local root
Attaching --> Refused: existing root, HEAD published by another holder
Claiming --> Cooling: CAS to this epoch and holder, state active
Claiming --> Cooling: replace generation (or exclusive create), same image
Cooling --> Holder: configured window elapsed (zero for single filer), exact HEAD reread
Cooling --> HolderFenced: publication displaced
Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch
Claiming --> Detached: same epoch/holder already sealed; refuse before preparation
Holder --> Detached: Detach final cut, state detached
Holder --> HolderFenced: a superseding HEAD is seen
}
@@ -194,7 +194,8 @@ stateDiagram-v2
| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` |
| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` |
| (startup) | Refused | `--chunk-filer` is not the only filer of its group: a master lists another filer or several, or no master lists it within 60 s (`ErrNotSingleFiler`) | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `INV-WS-SINGLE-FILER-001` |
| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the configured cooling window (zero at one serialization point) and an exact generation/epoch/holder readback | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` |
| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; fresh roots seed from HEAD before the CAS; existing roots retain local WAL; active incarnations replace the generation (or exclusive-create HEAD); a sealed same-owner incarnation remains detached; I/O opens only after the configured cooling window (zero at one serialization point) and an exact generation/epoch/holder readback | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001`, `INV-WS-REOPEN-FENCE-001` |
| Claiming | Detached (non-serving) | same epoch/holder HEAD is already detached: refuse with ErrChunkLayerDetached before restore preparation or CAS; a higher-epoch takeover still consumes the sealed image | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-SEALED-REOPEN-001` |
| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` |
| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` |
| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` |
@@ -215,6 +216,10 @@ stateDiagram-v2
Admit --> Refused: budget refused, closed, fenced, detached, base install, or lineage or lease invalid
Admit --> PlainStop: plain detach and idle frontend lock acquired
PlainStop --> Quiesce: idle frontend closed; caller-bounded offline seal
PlainStop --> RemoteProof: repeat plain seal, including after restart
Settled --> RemoteProof: plain seal result needs a fresh filer read
RemoteProof --> SealedReply: exact detached proof and unchanged authority
RemoteProof --> Refused: unreadable, foreign or malformed proof; never use memory
Admit --> FrozenForecast: guest already frozen with an explicit origin
FrozenForecast --> Refused: unknown or non-fitting remaining budget
FrozenForecast --> Quiesce: plausible estimate or explicit final override; skip staging
@@ -249,6 +254,7 @@ stateDiagram-v2
| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` |
| Stage | native remaining bytes above half the COW side cap trigger logical-read pre-copy straight to remote; repeat only while the remainder shrinks; legacy fixtures retain the chunk-count bound; each new key is intent-rooted first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-PAYLOAD-BOUNDED-001`, `INV-CUT-READ-LOGICAL-001` |
| Plain detach | plain=true acquires exclusive idle frontend admission (closed handles allowed), then StopIO and caller-bounded seal. Busy requests mutate nothing; publication and settlement retain authority/HEAD checks. | `provider_chunk.go` `DetachVolumePlain`; `storage_adapter.go` `stopPlainDetachIfIdle`; `chunk_control.go` `handleChunkDetach` | `INV-CUT-PLAIN-DETACH-001`, `INV-WS-HEAD-BELT-001` |
| Plain seal replay | a fresh filer HEAD must be detached with exact epoch/holder and matching detachedBy generation/epoch/holder; idle admission remains closed, authority is checked across the read, and no CAS occurs. Missing process state, including deferred authority startup, is allowed; cache alone never answers success. | `provider_seal_replay.go` `replayPlainSeal`; `chunk_seal_replay.go` `ReadDetachedChunkHead` | `INV-WS-SEAL-REPLAY-001` |
| Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-001` |
| Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` |
| Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
@@ -403,7 +409,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
185 rows: 163 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 170 new.
189 rows: 167 ACTIVE, 19 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 174 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -528,9 +534,12 @@ Notes:
| `INV-WS-HEAD-CAS-001` | Every HEAD publish is conditional on `{gen, epoch}` at one serialization point. A conflicting observed owner fences the publisher. Multiple independent filer serialization points are not made atomic by readback. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE |
| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestMemChunkRemote_RefusesLowerRemoteLSN` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`); `TestNativeReplacementCutBehindHEADRefuses` (`core/storage/legacy_replacement_v3_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE |
| `INV-WS-HEAD-KEY-PROVENANCE-001` | Every key a HEAD names is named by its predecessor HEAD or was uploaded by this owner under an intent that rooted it until the CAS settled; a key that left every root is never named again. | M5 Manifest → CAS | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | — | — | STUB |
| `INV-WS-REOPEN-FENCE-001` | Before I/O, an active reopened holder replaces the observed HEAD generation, including the same epoch/holder and an empty HEAD. A previous incarnation's delayed CAS cannot publish afterward. Local acknowledged WAL is retained. | M4 Claiming -> Holder | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS`, `TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites` (`core/storage/chunk_reopen_belt_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `HeadReopenBelt` `OldCASCannotLandAfterReopen` | ACTIVE |
| `INV-WS-SEALED-REOPEN-001` | A same-epoch/holder reopen cannot reactivate a detached HEAD. It refuses before preparation, CAS or serving, retaining the exact generation, owner, frontier, image and detachedBy proof for the planned new holder. | M4 Claiming -> Detached | `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestClaimChunkHeadSameOwnerReopenPreservesSeal` (`core/storage/chunk_reopen_belt_test.go`); `TestRestoreEqualOwnerDetachedHEADStaysSealed` (`core/frontend/durable/provider_seed_order_test.go`) | `SealedReopen` `SealedReopenPreservesProof` | ACTIVE |
| `INV-WS-SEAL-REPLAY-001` | A repeated plain seal, also after restart, succeeds only from a fresh filer HEAD with exact owner/epoch and detachedBy proof. It returns that original HEAD/frontier without a CAS or new generation. An unreadable or mismatched proof cannot be answered from process memory. | M5 PlainStop -> RemoteProof -> SealedReply | `core/frontend/durable/provider_seal_replay.go` `replayPlainSeal`; `core/storage/chunk_seal_replay.go` `ReadDetachedChunkHead` | `TestPlainSealLostAnswerRestartReplaysFilerProof`, `TestPlainSealReplayNeverUsesProcessMemory`, `TestPlainSealReplayDuringDeferredAuthorityStartup` (`core/frontend/durable/provider_plain_seal_replay_test.go`) | `PlainSealReplay` `SuccessNeedsFreshExactProof`, `ValidProofDoesNotNeedProcessMemory` | ACTIVE |
| `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE |
| `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE |
| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE |
| `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`) | — | ACTIVE |
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE |
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
@@ -697,6 +706,7 @@ Notes:
| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE |
| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE |
| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE |
| `INV-OBS-SLOT-FROM-EXPECTED-SERVER-001` | A replica's slot in the assembled topology takes addresses and health only from a fresh fact reported by the server its expected slot names; another server's fact for the same replica is never used, so with none from that server the slot is a placeholder. | AUTHORITY/ORDER: observation to assignment line | `core/authority/snapshot_builder.go` `assembleVolumeTopology` | `TestAssembleVolumeTopology_SlotFactOnlyFromTheExpectedServer` (`core/authority/snapshot_slot_server_test.go`) | — (pure assembly; the unit test is the proof form) | ACTIVE |
| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE |
| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE |
| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE |
@@ -786,6 +796,7 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a
| Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work |
|---|---|---|---|---|
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes.
@@ -0,0 +1,29 @@
--------------------------- MODULE HeadReopenBelt ---------------------------
\* One same-owner reopen, one server-held old CAS, one new acknowledged image.
\* The single serialization point evaluates a CAS guard at application time.
EXTENDS Naturals, TLC
CONSTANT ClaimWrites
VARIABLES gen, image, pending, sent, reopened, late, acked, published
vars == <<gen, image, pending, sent, reopened, late, acked, published>>
Init == /\ gen = 1 /\ image = 0 /\ pending = FALSE /\ sent = FALSE
/\ reopened = FALSE /\ late = FALSE /\ acked = FALSE /\ published = FALSE
SendOld == /\ ~sent /\ ~reopened /\ sent' = TRUE /\ pending' = TRUE
/\ UNCHANGED <<gen, image, reopened, late, acked, published>>
Reopen == /\ sent /\ ~reopened /\ reopened' = TRUE
/\ gen' = IF ClaimWrites THEN gen + 1 ELSE gen
/\ UNCHANGED <<image, pending, sent, late, acked, published>>
ApplyOld == /\ pending /\ pending' = FALSE
/\ gen' = IF gen = 1 THEN 2 ELSE gen
/\ image' = IF gen = 1 THEN 1 ELSE image
/\ late' = (late \/ (gen = 1 /\ reopened))
/\ UNCHANGED <<sent, reopened, acked, published>>
AckNew == /\ reopened /\ ~acked /\ acked' = TRUE
/\ UNCHANGED <<gen, image, pending, sent, reopened, late, published>>
PublishNew == /\ acked /\ ~published /\ published' = TRUE
/\ gen' = gen + 1 /\ image' = 2
/\ UNCHANGED <<pending, sent, reopened, late, acked>>
Next == SendOld \/ Reopen \/ ApplyOld \/ AckNew \/ PublishNew
Spec == Init /\ [][Next]_vars
OldCASCannotLandAfterReopen == ~late
PublishedAcknowledgedImage == published => image = 2
=============================================================================
@@ -0,0 +1,24 @@
---------------------------- MODULE PlainSealReplay ----------------------------
\* One seal invocation, possibly after restart. Only a new filer observation
\* can justify success. No controller pending-record or boot decision is modeled.
EXTENDS Naturals, TLC
CONSTANTS PreferMemory, RequireExact, RequireLayer
Heads == {"valid", "active", "holder", "epoch", "bad-proof", "unreadable", "moved"}
VARIABLES pc, cached, kind, observed, success
vars == <<pc, cached, kind, observed, success>>
Init == /\ pc = 0 /\ cached = TRUE /\ kind \in Heads
/\ observed = "none" /\ success = FALSE
Restart == /\ pc = 0 /\ pc' = 1 /\ cached' = FALSE
/\ UNCHANGED <<kind, observed, success>>
Read == /\ pc \in {0, 1} /\ pc' = 2 /\ observed' = kind
/\ UNCHANGED <<cached, kind, success>>
Reply == /\ pc \in {0, 1, 2}
/\ (pc = 2 \/ (PreferMemory /\ cached)) /\ pc' = 3
/\ success' = ((PreferMemory /\ cached) \/
(pc = 2 /\ (~RequireExact \/ observed = "valid") /\
(~RequireLayer \/ cached)))
/\ UNCHANGED <<cached, kind, observed>>
Spec == Init /\ [][Restart \/ Read \/ Reply]_vars
SuccessNeedsFreshExactProof == success => observed = "valid"
ValidProofDoesNotNeedProcessMemory == pc = 3 /\ observed = "valid" => success
=============================================================================
+70
View File
@@ -572,3 +572,73 @@ controls in `TestWorkspaceUncertaintyPrecedesRequestRefusal`. Actual request
cancellation retains its own controls, including a conflicting dependency status.
These are reply-classification claims, not authority-durability or delivery proof.
#344 review qualification: `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. (The HTTP-level drain refusal test was removed when `/chunk/detach` stopped admitting frozen requests in this release.) `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard.
### Same-owner process reopen belt
`HeadReopenBelt.tla` checks M4 Claiming -> Holder and
`INV-WS-REOPEN-FENCE-001` at one HEAD serialization point. One old server-held
CAS, one reopen and one new acknowledged image are interleaved. Claim replaces
the generation while preserving the observed image; the old CAS evaluates its
original generation when applied. This abstracts storage I/O and durability;
native tests cover WAL recovery and acknowledged bytes.
TLC 2.19, tool SHA256
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`,
2026-11-21: `cfg/HeadReopenBelt.cfg` exhausted 14 generated / 12 distinct states,
depth 6, queue empty. `OldCASCannotLandAfterReopen` and
`PublishedAcknowledgedImage` hold. `cfg/HeadReopenBelt_no_claim.cfg` violates
`OldCASCannotLandAfterReopen` at depth 4 (5 distinct states). That negative maps
to `TestClaimChunkHeadSameOwnerReopenRejectsKilledProcessCAS` and the real
cut/recovered-WAL control `TestHeadBeltSameOwnerReopenPreservesAcknowledgedWrites`;
`TestLocalReopenClaimsBeforeServing` covers the provider existing-root path.
The finite model checks one nonempty base; the native/public claim test also
covers an empty root with a delayed first-cut exclusive create.
### Same-incarnation reopen after seal
`SealedReopen.tla` checks the ruled same-epoch/holder M4 Claiming -> Detached
refusal (`INV-WS-SEALED-REOPEN-001`). It abstracts one detached proof and one
reopen: no prepare, CAS, generation change or serving is permitted. This is a
local guard model, not the full handover/liveness or RPC-delivery model.
TLC 2.19 (same tool SHA256 above), 2026-11-21: `cfg/SealedReopen.cfg` exhausted
2 generated / 2 distinct states, depth 2, queue empty. Both
`SealedReopenPreservesProof` and `SealedReopenCannotServe` hold.
`cfg/SealedReopen_reactivate.cfg` violates `SealedReopenPreservesProof` at depth 2.
That negative maps to `TestClaimChunkHeadSameOwnerReopenPreservesSeal` and
`TestRestoreEqualOwnerDetachedHEADStaysSealed`. The latter performs a real plain
seal, restarts storage on either the retained local root or a fresh root under
the same assignment, verifies unchanged proof/bytes and no frontend I/O, then
loads that exact sealed image on the planned new holder at a higher epoch.
The earlier test expecting same-owner reactivation is replaced by this ruled
terminal behavior. The active-root generation belt model and its bounds remain
unchanged; its serving precondition excludes a sealed same-owner incarnation.
### Plain seal replay from the filer
`PlainSealReplay.tla` checks M5 PlainStop -> RemoteProof -> SealedReply and
`INV-WS-SEAL-REPLAY-001`. One operation may keep process memory or restart;
seven read observations represent valid proof, active HEAD, wrong holder,
wrong epoch, malformed proof, unreadable filer or moved authority. The caller
must obtain a new exact proof for success, and a valid proof needs no process
memory. This is an idempotent storage request, not a controller HEAD-only
pending-record/boot proof; no such controller behavior is added here.
TLC 2.19 (same tool SHA256 above), 2026-11-21: `cfg/PlainSealReplay.cfg`
exhausted 42 generated / 42 distinct states, depth 4, queue empty. Both
`SuccessNeedsFreshExactProof` and `ValidProofDoesNotNeedProcessMemory` hold.
Negatives: `_memory` violates the first property at depth 2 (10 distinct
states); `_no_exact` violates it at depth 3 (25 distinct); `_layer` violates
the second at depth 4 (36 distinct). The memory negative maps to
`TestPlainSealReplayNeverUsesProcessMemory`; the exact-proof negative maps to
the corrupt proof/authority subcontrols in
`TestPlainSealLostAnswerRestartReplaysFilerProof`; the layer negative maps to
that test's lost committed answer -> storage restart -> successful re-send.
Native controls additionally require the original full HEAD and no CAS/new
generation. CAS atomicity, local WAL recovery and remote-call cancellation
remain native/existing-spec obligations rather than claims of this small model.
The provider dispatch control `TestPlainSealReplayDuringDeferredAuthorityStartup`
sets Healthy=false before RecoverVolume, witnesses the no-layer authority wait,
and checks fresh proof replay without CAS or enabling cuts. This is native
integration coverage of the existing RemoteProof transition; the model is unchanged.
+16
View File
@@ -0,0 +1,16 @@
----------------------------- MODULE SealedReopen -----------------------------
\* Same owner/epoch only. A legitimate new-owner takeover is a separate action.
EXTENDS Naturals, TLC
CONSTANT PreserveSeal
VARIABLES gen, state, reopened, prepared, serving
vars == <<gen, state, reopened, prepared, serving>>
Init == /\ gen = 7 /\ state = "detached" /\ reopened = FALSE
/\ prepared = FALSE /\ serving = FALSE
Reopen == /\ ~reopened /\ reopened' = TRUE
/\ gen' = IF PreserveSeal THEN gen ELSE gen + 1
/\ state' = IF PreserveSeal THEN state ELSE "active"
/\ prepared' = ~PreserveSeal /\ serving' = ~PreserveSeal
Spec == Init /\ [][Reopen]_vars
SealedReopenPreservesProof == gen = 7 /\ state = "detached"
SealedReopenCannotServe == ~prepared /\ ~serving
=============================================================================
@@ -0,0 +1,3 @@
CONSTANT ClaimWrites = TRUE
SPECIFICATION Spec
INVARIANTS OldCASCannotLandAfterReopen PublishedAcknowledgedImage
@@ -0,0 +1,3 @@
CONSTANT ClaimWrites = FALSE
SPECIFICATION Spec
INVARIANTS OldCASCannotLandAfterReopen PublishedAcknowledgedImage
@@ -0,0 +1,3 @@
CONSTANTS PreferMemory = FALSE RequireExact = TRUE RequireLayer = FALSE
SPECIFICATION Spec
INVARIANTS SuccessNeedsFreshExactProof ValidProofDoesNotNeedProcessMemory
@@ -0,0 +1,3 @@
CONSTANTS PreferMemory = FALSE RequireExact = TRUE RequireLayer = TRUE
SPECIFICATION Spec
INVARIANTS SuccessNeedsFreshExactProof ValidProofDoesNotNeedProcessMemory
@@ -0,0 +1,3 @@
CONSTANTS PreferMemory = TRUE RequireExact = TRUE RequireLayer = FALSE
SPECIFICATION Spec
INVARIANTS SuccessNeedsFreshExactProof ValidProofDoesNotNeedProcessMemory
@@ -0,0 +1,3 @@
CONSTANTS PreferMemory = FALSE RequireExact = FALSE RequireLayer = FALSE
SPECIFICATION Spec
INVARIANTS SuccessNeedsFreshExactProof ValidProofDoesNotNeedProcessMemory
@@ -0,0 +1,3 @@
CONSTANT PreserveSeal = TRUE
SPECIFICATION Spec
INVARIANTS SealedReopenPreservesProof SealedReopenCannotServe
@@ -0,0 +1,3 @@
CONSTANT PreserveSeal = FALSE
SPECIFICATION Spec
INVARIANTS SealedReopenPreservesProof SealedReopenCannotServe