From 7cd5240aeabfc3c5241f8d54dddfbe0797d98f46 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 04:41:29 -0800 Subject: [PATCH 1/6] storage: touched-set bookkeeping: attach allocation, drained pause, status Three accounting fixes for the touched-set candidates, each with a red: the live touched set is allocated before the layer's hooks are published (a v1.1 store's first map entry change otherwise allocated the bitmap under the store's lock); a drained pre-copy cut charges its dirty-set and whole-volume walks to the pause (they ran inside it, uncounted); and the status's dirty count includes a cut's judged candidates until its HEAD installs. The unknown-commit-outcome test now compares the remote image byte for byte. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 103 +++++++++++++++++- seaweed-block/core/storage/chunk_layer.go | 21 +++- 2 files changed, 121 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index 05242b2405..d2f3bb1132 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -2,6 +2,7 @@ package storage import ( "bytes" + "context" "crypto/sha256" "encoding/binary" "errors" @@ -325,7 +326,7 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) { if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { t.Fatalf("the injected cut answered %v, want its outcome unknown", err) } - w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut + last5 := w.write(t, s, 5*ctChunkBlocks, 0xa5) // chunk 5, after the cut var err error var last chunkCutResult for i := 0; i < 3; i++ { // the next cuts settle the unknown outcome and publish @@ -346,6 +347,15 @@ func TestUnknownCommitOutcomeLosesNoChunk(t *testing.T) { t.Fatalf("chunk %d changed=%v after the unknown outcome and the next cut, want %v", idx, changed, want) } } + // Byte for byte: the remote is exactly the written image (the baseline + // with the three writes), not merely different in the right chunks. + if want := w.imageAt(last5); !bytes.Equal(img, want) { + for at := 0; at < len(want); at += ctBlockSize { + if !bytes.Equal(img[at:at+ctBlockSize], want[at:at+ctBlockSize]) { + t.Fatalf("the remote image differs from the written one at block %d", at/ctBlockSize) + } + } + } } // The candidate set's OR keeps the summary, so a set ORed back is listed in @@ -600,3 +610,94 @@ func TestACutThatAbortsAfterTakingTheRequestReissuesIt(t *testing.T) { t.Fatalf("the next cut left request generation %d pending", got) } } + +// The live touched set exists once the layer attaches, before any write, +// on both store formats: a first map entry change only sets a bit (never +// allocates the bitmap under the store's lock). On v1.0 the record shadow's +// attach already seeds it; v1.1's record open does not, so it is allocated +// explicitly before the hooks are published. +func TestTheTouchedSetExistsAtAttach(t *testing.T) { + for _, format := range []string{"v1.0", "v1.1"} { + t.Run(format, func(t *testing.T) { + if format == "v1.1" { + withV11Format(t) + } else { + v10Only(t) + } + s, _ := newChunkTestStore(t) + // attachChunkLayer itself, not mustAttach: its reconcile wait reads + // Stats, whose candidate listing would seed the set. + layer, err := attachChunkLayer(s, newFakeChunkRemote(), ctConfig(1)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = layer.Close() }) + l := layer.(*chunkLayerImpl) + l.unkMu.Lock() + allocated := l.touched != nil + l.unkMu.Unlock() + if !allocated { + t.Fatal("no touched set after attach: the first write would allocate it under the store lock") + } + }) + } +} + +// A chunk a cut judged a candidate stays in the status's DirtyChunks until +// that cut's HEAD installs, even after the flush checkpoints it out of the +// WAL dirty map while the cut's upload is in flight. +func TestStatsCountsACutsCandidatesUntilItsHeadInstalls(t *testing.T) { + s, _ := newChunkTestStore(t) + f := newFakeChunkRemote() + layer := mustAttach(t, s, f, ctConfig(1)) + l := layer.(*chunkLayerImpl) + w := newWriteLog() + if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set + t.Fatal(err) + } + w.write(t, s, 2*ctChunkBlocks, 0x22) // chunk 2 + entered, release := holdPuts(t, f) + t.Cleanup(release) + done := startCapture(t, layer) + waitKey(t, entered, "chunk upload") + mustSyncFlush(t, s) // the write leaves the dirty map while the cut holds chunk 2 + got := l.Stats().DirtyChunks + release() + if err := waitErr(t, done, "capture"); err != nil { + t.Fatal(err) + } + if got < 1 { + t.Fatalf("status during the cut's upload: %d dirty chunks, want chunk 2 counted", got) + } +} + +// A pre-copy cut keeps its frontend drained through the candidate step, so +// every walk it makes there is pause work and is charged: a BASE's +// whole-volume pass (allDirty) is charged with the judging it feeds, +// compared with the same drained cut without it. +func TestADrainedCutChargesItsWholeVolumeWalkToThePause(t *testing.T) { + s, _ := newChunkTestStore(t) + l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) + if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set + t.Fatal(err) + } + l.precopyPrepare = func(context.Context) (func(), error) { return func() {}, nil } // drained to the freeze + t.Cleanup(func() { l.precopyPrepare = nil }) + plain, err := l.Cut(ctTimeout(t)) // drained, no whole-volume walk + if err != nil { + t.Fatal(err) + } + l.stMu.Lock() + l.allDirty = true // as after a BASE: every chunk is walked + l.stMu.Unlock() + walked, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + // The whole-volume cut adds, inside the drained pause, the BASE pass (one + // visit per chunk) and the judging of every chunk that pass names (one + // per chunk): both are charged. Charging before the pass drops the first. + if got, want := walked.Stats.PauseCandidateOps-plain.Stats.PauseCandidateOps, 2*int64(l.numChunks); got < want { + t.Fatalf("a drained cut's whole-volume walk added %d pause candidate operations (%d -> %d), want at least %d (the pass and the judging, %d chunks each)", got, plain.Stats.PauseCandidateOps, walked.Stats.PauseCandidateOps, want, l.numChunks) + } +} diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index eefbe8a971..d2b8c0285d 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -475,6 +475,12 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) hooks.beforeMutation = l.beforeCOWMutation hooks.beforeDestructive = l.holdCOWDestructive + // The live touched set exists before the hooks are published: the first + // map entry change (under WALStore.mu) only sets a bit, never allocates a + // volume-sized bitmap. + l.unkMu.Lock() + l.touchedLocked(false) + l.unkMu.Unlock() if !s.chunk.CompareAndSwap(nil, hooks) { l.cancel() return nil, errors.New("storage: a chunk layer is already attached") @@ -1826,7 +1832,6 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } candidates, visits := l.candidatesFrom(members, h) visits += int64(len(taken.summary)) // the summary words the walk read - l.pauseOp(int(visits)) // each step counts itself if it ever runs in the pause for idx := range dirtyTaken { visits++ candidates[idx] = true @@ -1844,6 +1849,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } } l.stMu.Unlock() + // Charged after every walk (the touched set, the dirty set, a BASE's + // whole-volume pass): a drained pre-copy frontend is still paused here. + l.pauseOp(int(visits)) candidateOracleCompare(oracleWant, candidates) // tests only // A chunk known to hold HEAD's bytes at its current version (a clean // fill, or a compare by a cut that did not publish) is not compared @@ -2899,7 +2907,16 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { out.ReconcileDone = 0 l.stMu.Unlock() - out.DirtyChunks = len(l.captureCandidates()) + dirty := l.captureCandidates() + // A cut's judged candidates stay counted until its HEAD installs: one the + // flush checkpointed out of the dirty map meanwhile is in neither source + // above. Read under stMu; the cut keeps its own taken set. + l.stMu.Lock() + for idx := range l.inflight { + dirty[idx] = true + } + l.stMu.Unlock() + out.DirtyChunks = len(dirty) out.AbsentChunks = l.absentHydratable() return out From ce484652981c4670ad65e02f7df00dc1797957e4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:46:27 -0800 Subject: [PATCH 2/6] storage: #948 tests: bounded close, exact union, exact pause deltas The direct-attach test bounds its Close as mustAttach does. The status test pins the exact union of live and in-flight candidates during an upload (distinct and overlapping) and the in-flight part leaving after HEAD installs. The drained-pause test pins exact deltas: 2k for k dirty chunks, 2N for a whole-volume pass, and nothing carried over. Co-Authored-By: Claude Opus 5.5 --- .../storage/chunk_cut_candidate_set_test.go | 74 +++++++++++++------ 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go index d2f3bb1132..715df2c68c 100644 --- a/seaweed-block/core/storage/chunk_cut_candidate_set_test.go +++ b/seaweed-block/core/storage/chunk_cut_candidate_set_test.go @@ -631,7 +631,15 @@ func TestTheTouchedSetExistsAtAttach(t *testing.T) { if err != nil { t.Fatal(err) } - t.Cleanup(func() { _ = layer.Close() }) + t.Cleanup(func() { // bounded, as mustAttach's + done := make(chan struct{}) + go func() { _ = layer.Close(); close(done) }() + select { + case <-done: + case <-time.After(ctLocalBound): + t.Errorf("chunk layer Close did not return within %v", ctLocalBound) + } + }) l := layer.(*chunkLayerImpl) l.unkMu.Lock() allocated := l.touched != nil @@ -643,9 +651,10 @@ func TestTheTouchedSetExistsAtAttach(t *testing.T) { } } -// A chunk a cut judged a candidate stays in the status's DirtyChunks until -// that cut's HEAD installs, even after the flush checkpoints it out of the -// WAL dirty map while the cut's upload is in flight. +// The status's DirtyChunks is the exact union of the live candidates and a +// cut's in-flight ones while its upload runs (a chunk in both counts once, +// one only in flight still counts), and the in-flight part leaves the count +// once that cut's HEAD installs. func TestStatsCountsACutsCandidatesUntilItsHeadInstalls(t *testing.T) { s, _ := newChunkTestStore(t) f := newFakeChunkRemote() @@ -655,26 +664,35 @@ func TestStatsCountsACutsCandidatesUntilItsHeadInstalls(t *testing.T) { if _, err := l.Cut(ctTimeout(t)); err != nil { // the seed, and an empty touched set t.Fatal(err) } - w.write(t, s, 2*ctChunkBlocks, 0x22) // chunk 2 + w.write(t, s, 2*ctChunkBlocks, 0x22) // chunk 2: in flight only, once flushed + w.write(t, s, 3*ctChunkBlocks, 0x33) // chunk 3: in flight, and written again below entered, release := holdPuts(t, f) t.Cleanup(release) done := startCapture(t, layer) waitKey(t, entered, "chunk upload") - mustSyncFlush(t, s) // the write leaves the dirty map while the cut holds chunk 2 - got := l.Stats().DirtyChunks + w.write(t, s, 3*ctChunkBlocks+1, 0x3b) // chunk 3 again: live and in flight + w.write(t, s, 4*ctChunkBlocks, 0x44) // chunk 4: live only + mustSyncFlush(t, s) // chunk 2's write leaves the dirty map + during := l.Stats().DirtyChunks release() if err := waitErr(t, done, "capture"); err != nil { t.Fatal(err) } - if got < 1 { - t.Fatalf("status during the cut's upload: %d dirty chunks, want chunk 2 counted", got) + after := l.Stats().DirtyChunks + if during != 3 { + t.Fatalf("during the cut's upload: %d dirty chunks, want 3 (chunk 2 in flight, 3 in both, 4 live)", during) + } + if after != 2 { + t.Fatalf("after the cut's HEAD installed: %d dirty chunks, want 2 (chunks 3 and 4, written since)", after) } } // A pre-copy cut keeps its frontend drained through the candidate step, so -// every walk it makes there is pause work and is charged: a BASE's -// whole-volume pass (allDirty) is charged with the judging it feeds, -// compared with the same drained cut without it. +// every walk it makes there is pause work, charged exactly once: over the +// same drained cut with nothing to walk, k dirty chunks add 2k (the +// dirty-set visit and the judging of each), and a BASE's whole-volume pass +// over N chunks adds 2N (the pass and the judging of each). A walk charged +// before it ran, or charged twice, misses the exact delta. func TestADrainedCutChargesItsWholeVolumeWalkToThePause(t *testing.T) { s, _ := newChunkTestStore(t) l := mustAttach(t, s, newFakeChunkRemote(), ctConfig(1)).(*chunkLayerImpl) @@ -683,21 +701,31 @@ func TestADrainedCutChargesItsWholeVolumeWalkToThePause(t *testing.T) { } l.precopyPrepare = func(context.Context) (func(), error) { return func() {}, nil } // drained to the freeze t.Cleanup(func() { l.precopyPrepare = nil }) - plain, err := l.Cut(ctTimeout(t)) // drained, no whole-volume walk - if err != nil { - t.Fatal(err) + cut := func(what string) int64 { + t.Helper() + r, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatalf("%s: %v", what, err) + } + return r.Stats.PauseCandidateOps + } + plain := cut("a drained cut with nothing to walk") + const k = 3 + l.stMu.Lock() + for i := uint64(0); i < k; i++ { + l.dirty[i] = true + } + l.stMu.Unlock() + if got, want := cut("k dirty chunks")-plain, int64(2*k); got != want { + t.Fatalf("a drained cut over %d dirty chunks charged %d more pause operations, want %d", k, got, want) } l.stMu.Lock() l.allDirty = true // as after a BASE: every chunk is walked l.stMu.Unlock() - walked, err := l.Cut(ctTimeout(t)) - if err != nil { - t.Fatal(err) + if got, want := cut("a whole-volume pass")-plain, 2*int64(l.numChunks); got != want { + t.Fatalf("a drained cut's whole-volume pass charged %d more pause operations, want %d (the pass and the judging, %d chunks each)", got, want, l.numChunks) } - // The whole-volume cut adds, inside the drained pause, the BASE pass (one - // visit per chunk) and the judging of every chunk that pass names (one - // per chunk): both are charged. Charging before the pass drops the first. - if got, want := walked.Stats.PauseCandidateOps-plain.Stats.PauseCandidateOps, 2*int64(l.numChunks); got < want { - t.Fatalf("a drained cut's whole-volume walk added %d pause candidate operations (%d -> %d), want at least %d (the pass and the judging, %d chunks each)", got, plain.Stats.PauseCandidateOps, walked.Stats.PauseCandidateOps, want, l.numChunks) + if got := cut("nothing to walk again"); got != plain { + t.Fatalf("a drained cut with nothing to walk after them charged %d, want %d (nothing carried over)", got, plain) } } From 4c4e753b618996a7e2ea538eb925f273fd0a22e1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 05:51:03 -0800 Subject: [PATCH 3/6] storage: test: the slow-extent red tolerates a slow fsync TestWALStoreV3SlowExtentKeepsReclaimMoving flaked on a busy Windows host: a single slow fsync pushed one bounded cycle past its 500 ms admission budget (attempts of 500-577 ms, against cycles whose writes take about 77 ms). The slow disk is now 5 ms per extent write and the budget half a whole-map cycle from the measured sleep (about 1.2 s): a bounded cycle (about 160 ms of writes) leaves room for a slow fsync, and a whole-map cycle (about 2.4 s) still outlasts the budget. Co-Authored-By: Claude Opus 5.5 --- .../storage/walstore_bounded_flush_v3_test.go | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go index 0f989241f2..a2f20da1c4 100644 --- a/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go +++ b/seaweed-block/core/storage/walstore_bounded_flush_v3_test.go @@ -6,6 +6,7 @@ import ( "math" "math/rand" "path/filepath" + "sort" "testing" "time" ) @@ -181,11 +182,11 @@ func TestWALStoreV3DrainHeldIsTheFlusherPhase(t *testing.T) { } // A dense image written as single 4 KiB writes in random order, three -// WALs' worth, on a slow disk (every extent write takes 2 ms), with a 500 ms admission -// budget. A whole-map cycle (about 480 entries, about 1 s) frees nothing -// until it ends, so a write times out waiting for space; bounded cycles free -// space every sixteenth of the WAL, and no write times out while reclaim -// moves. The guest sees a slow disk, not errors. +// WALs' worth, on a slow disk (every extent write takes 5 ms), with an +// admission budget of half a whole-map cycle. A whole-map cycle (about 480 +// entries) frees nothing until it ends, so a write times out waiting for +// space; bounded cycles free space every sixteenth of the WAL, and no write +// times out while reclaim moves. The guest sees a slow disk, not errors. func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) { const walSize = 2 << 20 const count = 3 * walSize / 4096 @@ -195,8 +196,17 @@ func TestWALStoreV3SlowExtentKeepsReclaimMoving(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = s.Close() }) - s.admissionTimeout = 500 * time.Millisecond - s.flusher.beforeExtentWriteForTest = func() { time.Sleep(2 * time.Millisecond) } + // The slow disk is a 5 ms sleep per extent write. The admission budget is + // half a whole-map cycle (about 480 records), from the sleep as measured + // on this host: a whole-map cycle still outlasts it (the red), while a + // bounded cycle (a sixteenth of this WAL, about 32 records) leaves room + // for a slow fsync on a busy host (the budget is about 1.2 s, the bounded + // cycle's writes about 160 ms). + const delay = 5 * time.Millisecond + sleep := measuredSleep(delay) + s.admissionTimeout = 240 * sleep + t.Logf("measured sleep %v: admission budget %v", sleep, s.admissionTimeout) + s.flusher.beforeExtentWriteForTest = func() { time.Sleep(delay) } lbas := rand.New(rand.NewSource(1)).Perm(count) start := time.Now() busy := 0 @@ -528,3 +538,15 @@ func TestWALStoreV3HeldDrainEndsInTheProductionDrain(t *testing.T) { } } } + +// measuredSleep is the median time a sleep of d actually takes on this host. +func measuredSleep(d time.Duration) time.Duration { + var got [9]time.Duration + for i := range got { + start := time.Now() + time.Sleep(d) + got[i] = time.Since(start) + } + sort.Slice(got[:], func(i, j int) bool { return got[i] < got[j] }) + return got[len(got)/2] +} From 0dbe9b919147c45903fe36adf0c52eca9b54f40e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 06:39:03 -0800 Subject: [PATCH 4/6] storage: test: three tests read a locked store file through the store Three tests read or damaged the store file through a second handle while the store held its byte-range lock: mandatory on Windows, so they failed there only. They now go through the open store's own file: the slots by slotsV3Of, a record by damageOpenRecord. What they assert is unchanged. Fixes #953. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/base_install_v3_test.go | 6 ++--- .../core/storage/reset_store_v3_test.go | 26 +++++++++++++++++-- .../core/storage/walstore_v3_test.go | 4 +-- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/storage/base_install_v3_test.go b/seaweed-block/core/storage/base_install_v3_test.go index 89ccb1ebcf..85d7120db1 100644 --- a/seaweed-block/core/storage/base_install_v3_test.go +++ b/seaweed-block/core/storage/base_install_v3_test.go @@ -455,7 +455,7 @@ func TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites(t *testing.T) { // An attached layer without the transition protocol still refuses, writing // nothing. Actual supported layers are covered by the chunk/provider controls. func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing.T) { - s, path := newMappedCheckpointStoreV3(t) + s, _ := newMappedCheckpointStoreV3(t) cfg := ctConfig(1) cfg.Bitmap = nil cfg.BarrierBound = 1 @@ -463,11 +463,11 @@ func TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer(t *testing hooks := *s.chunk.Load() hooks.baseTransitionV3 = nil s.chunk.Store(&hooks) - a0, b0 := slotsV3(t, path) + a0, b0 := slotsV3Of(t, s) // the store holds the file's lock: read through it if _, err := s.beginBaseInstallV3(0, idA); !errors.Is(err, errV3NotYet) { t.Fatalf("begin with a chunk layer attached: err = %v, want errV3NotYet", err) } - if a, b := slotsV3(t, path); a != a0 || b != b0 { + if a, b := slotsV3Of(t, s); a != a0 || b != b0 { t.Fatal("a refused begin wrote a descriptor slot") } } diff --git a/seaweed-block/core/storage/reset_store_v3_test.go b/seaweed-block/core/storage/reset_store_v3_test.go index 92df3a99ae..34b37aaa2f 100644 --- a/seaweed-block/core/storage/reset_store_v3_test.go +++ b/seaweed-block/core/storage/reset_store_v3_test.go @@ -14,6 +14,28 @@ import ( // dark: only these tests call it. // slotsV3 decodes both descriptor slots of the file at path. +// slotsV3Of reads both descriptor slots through the open store's own file: +// a second handle cannot read a range the store holds locked (Windows). +func slotsV3Of(t *testing.T, s *WALStore) (a, b descriptorV3) { + t.Helper() + for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + buf := make([]byte, slotSizeV3) + if _, err := s.fd.ReadAt(buf, off); err != nil { + t.Fatal(err) + } + d, err := decodeSlotV3(buf, nil) + if err != nil { + t.Fatalf("slot %d: %v", i, err) + } + if i == 0 { + a = d + } else { + b = d + } + } + return a, b +} + func slotsV3(t *testing.T, path string) (a, b descriptorV3) { t.Helper() f, err := os.Open(path) @@ -383,7 +405,7 @@ func TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault(t *testing.T) { // unchanged (same position and LSN), but it is a new write: the read must // retry and return it, not report WAL damage. func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage(t *testing.T) { - s, path := newStoreV3(t, WModeStrict) + s, _ := newStoreV3(t, WModeStrict) t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) resolved, invalid := newHeldV3(t), newHeldV3(t) writeSynced(t, s, 1, 1) // LSN 1 @@ -403,7 +425,7 @@ func TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage }) waitV3(t, resolved.parked, "Read after resolving LSN 2") s.v3.testReadResolved = nil - damageRecord(t, path, 2) + damageOpenRecord(t, s, 2) // through the store's file: it holds the range locked if _, err := s.Recover(); err != nil { // drops LSN 2 and fences its bytes t.Fatalf("Recover: %v", err) } diff --git a/seaweed-block/core/storage/walstore_v3_test.go b/seaweed-block/core/storage/walstore_v3_test.go index f28637d12e..4e643a9440 100644 --- a/seaweed-block/core/storage/walstore_v3_test.go +++ b/seaweed-block/core/storage/walstore_v3_test.go @@ -869,7 +869,7 @@ func TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut(t *testing.T) // recovery drops its cut, must not acknowledge it; a fresh Sync after the // recovery acknowledges normally. func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) { - s, path := newStoreV3(t, WModeLagged) + s, _ := newStoreV3(t, WModeLagged) t.Cleanup(func() { crashRecoveryHardeningStore(t, s) }) h := newHeldV3(t) writeSynced(t, s, 1, 1) @@ -880,7 +880,7 @@ func TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery(t *testing.T) { syn := h.start(func() error { _, err := s.Sync(); return err }) waitV3(t, h.parked, "the outer Sync before its completion") s.v3.testSyncBeforeCompletion = nil - damageRecord(t, path, 2) + damageOpenRecord(t, s, 2) // through the store's file: it holds the range locked if _, err := s.Recover(); err != nil { t.Fatalf("Recover: %v", err) } From 59a0ebca91c4993d12d4eb37bd5e08fbd95c65a6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 07:04:38 -0800 Subject: [PATCH 5/6] sw-block: retire-host answers 0/2/75/1 with --json; a forced move's preview carries the typed reason retire-host follows finalize-format's contract: exit 0 retired, 2 refused, 75 the master could not be reached, 1 any other failure or usage error, and --json prints result, reason, server, volumes and message for every outcome. The master's HOST_HOLDS_WORK refusal names each held volume in its typed metadata. The forced-move preview answers the typed reason the move itself would carry (reason_code, e.g. BINARY_TOO_OLD), and force-move --dry-run --json shows it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/cluster_format.go | 82 +++++++++++++++---- .../cmd/sw-block/cluster_format_json_test.go | 80 ++++++++++++++++++ .../cmd/sw-block/cluster_format_test.go | 8 +- seaweed-block/cmd/sw-block/workspace.go | 1 + .../cmd/sw-block/workspace_clean_test.go | 24 ++++++ seaweed-block/core/host/master/format_gate.go | 11 ++- .../core/host/master/format_gate_test.go | 10 +++ .../core/host/master/workspace_service.go | 5 +- .../core/rpc/control/workspace.pb.go | 19 ++++- .../core/rpc/lifecycleclient/reason.go | 4 + seaweed-block/core/rpc/proto/workspace.proto | 4 + 11 files changed, 223 insertions(+), 25 deletions(-) diff --git a/seaweed-block/cmd/sw-block/cluster_format.go b/seaweed-block/cmd/sw-block/cluster_format.go index ad0a050b0a..c92a8b9471 100644 --- a/seaweed-block/cmd/sw-block/cluster_format.go +++ b/seaweed-block/cmd/sw-block/cluster_format.go @@ -223,8 +223,22 @@ func finalizeHosts(md map[string]string) []finalizeHost { return hosts } +// retireAnswer is retire-host's --json answer, one shape for every outcome. +// Result is retired, refused, unavailable or failed; Reason the master's +// typed reason (or the gRPC code, "" on success); Volumes the volumes the +// host still holds when the retire is refused for them (empty otherwise). +type retireAnswer struct { + Result string `json:"result"` + Reason string `json:"reason"` + Server string `json:"server"` + Volumes []string `json:"volumes"` + Message string `json:"message"` +} + // runClusterRetireHost removes a registered host from the node inventory. -// The master refuses it while the host holds a lease or an assignment. +// The master refuses it while the host holds a lease or an assignment. Exit +// codes as finalize-format's: 0 retired, 2 refused, 75 the master could not +// be reached (EX_TEMPFAIL), 1 any other failure, a usage error included. func runClusterRetireHost(args []string, stdout, stderr io.Writer) int { fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError) fs.SetOutput(stderr) @@ -232,31 +246,67 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) int { server := fs.String("server", "", "the server id to retire (required)") confirm := fs.String("confirm", "", "the same server id again (required)") timeout := fs.Duration("timeout", 30*time.Second, "how long to wait for the master's answer") - if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" { - fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s]") - return ops.VolumeStatusExitInvalid + // Declared for parsing and help only; the mode is read from the + // arguments as a whole, so a bad option in any position cannot half-parse it. + fs.Bool("json", false, "print the typed answer as JSON: result, reason, server, volumes, message") + jsonMode := jsonRequested(args) + answer := retireAnswer{Volumes: []string{}} + defer func() { + if jsonMode { + if err := json.NewEncoder(stdout).Encode(answer); err != nil { + fmt.Fprintln(stderr, "sw-block: cluster retire-host: JSON output:", err) + } + } + }() + fail := func(result, reason, msg string, code int) int { + answer.Result, answer.Reason, answer.Message = result, reason, msg + fmt.Fprintln(stderr, "sw-block: cluster retire-host:", msg) + return code } + if err := fs.Parse(args); err != nil || fs.NArg() != 0 || *master == "" || *server == "" || *confirm == "" { + fmt.Fprintln(stderr, "usage: sw-block cluster retire-host --master host:port --server ID --confirm ID [--timeout 30s] [--json]") + answer.Result, answer.Reason, answer.Message = "failed", "usage", "--master, --server and --confirm are required" + return finalizeExitFailed + } + answer.Server = *server c, closeFn, err := clusterLifecycleDial(*master) if err != nil { - fmt.Fprintln(stderr, "sw-block: cluster retire-host:", err) - return ops.VolumeStatusExitUnhealthy + return fail("unavailable", codes.Unavailable.String(), err.Error(), finalizeExitTempFail) } defer closeFn() ctx, cancel := context.WithTimeout(context.Background(), *timeout) defer cancel() if _, err := c.RetireHost(ctx, &control.RetireHostRequest{ServerId: *server, Confirm: *confirm}); err != nil { - fmt.Fprintln(stderr, "sw-block: cluster retire-host:", status.Convert(err).Message()) - return clusterExit(err) + msg := status.Convert(err).Message() + reason, md := lifecycleclient.ReasonDetail(err) + if reason == "" { + reason = status.Code(err).String() + } + switch status.Code(err) { + case codes.FailedPrecondition: + answer.Volumes = retireVolumes(md) + return fail("refused", reason, msg, finalizeExitRefused) + case codes.Unavailable, codes.DeadlineExceeded: + return fail("unavailable", reason, msg, finalizeExitTempFail) + } + return fail("failed", reason, msg, finalizeExitFailed) } - fmt.Fprintf(stdout, "host %s retired\n", *server) - return ops.VolumeStatusExitOK + answer.Result, answer.Message = "retired", "host retired from the node inventory" + if !jsonMode { + fmt.Fprintf(stdout, "host %s retired\n", *server) + } + return finalizeExitOK } -// clusterExit maps a master error to the CLI's exit codes: a malformed -// request is 2 (as a usage error); a refusal or an unreachable master is 1. -func clusterExit(err error) int { - if status.Code(err) == codes.InvalidArgument { - return ops.VolumeStatusExitInvalid +// retireVolumes reads the held volumes from the refusal's typed metadata, +// sorted. +func retireVolumes(md map[string]string) []string { + vols := []string{} + for k := range md { + if v, ok := strings.CutPrefix(k, lifecycleclient.VolumeMetadataPrefix); ok { + vols = append(vols, v) + } } - return ops.VolumeStatusExitUnhealthy + sort.Strings(vols) + return vols } diff --git a/seaweed-block/cmd/sw-block/cluster_format_json_test.go b/seaweed-block/cmd/sw-block/cluster_format_json_test.go index a3ae03f470..e950d80df4 100644 --- a/seaweed-block/cmd/sw-block/cluster_format_json_test.go +++ b/seaweed-block/cmd/sw-block/cluster_format_json_test.go @@ -142,3 +142,83 @@ func TestClusterFinalizeFormatBadOptionAnswersJSONWithoutAnRPC(t *testing.T) { t.Fatalf("a malformed command sent %d finalize RPCs", calls) } } + +// retire-host's answer is typed like finalize-format's: exit 0 retired, 2 +// refused (the held volumes from the master's typed metadata, never its +// message text), 75 the master could not be reached, 1 any other failure or +// a usage error; --json prints the same keys for every outcome. +func TestClusterRetireHostTypedAnswer(t *testing.T) { + holds := lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, "message text a script must not parse"), + lifecycleclient.ReasonHostHoldsWork, map[string]string{ + lifecycleclient.VolumeMetadataPrefix + "v2": "busy", + lifecycleclient.VolumeMetadataPrefix + "v1": "busy", + }).Err() + for _, tc := range []struct { + name string + err error + dialErr error + args []string + exit int + result string + reason string + volumes []string + }{ + {name: "retired", exit: 0, result: "retired"}, + {name: "holds-work", err: holds, exit: 2, result: "refused", reason: lifecycleclient.ReasonHostHoldsWork, volumes: []string{"v1", "v2"}}, + {name: "not-registered", err: status.Error(codes.FailedPrecondition, "retire refused: host is not registered"), exit: 2, result: "refused", reason: "FailedPrecondition"}, + {name: "unreachable", err: status.Error(codes.Unavailable, "connection refused"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "deadline", err: status.Error(codes.DeadlineExceeded, "context deadline exceeded"), exit: 75, result: "unavailable", reason: "DeadlineExceeded"}, + {name: "dial", dialErr: errors.New("bad address"), exit: 75, result: "unavailable", reason: "Unavailable"}, + {name: "internal", err: status.Error(codes.Internal, "node inventory write failed"), exit: 1, result: "failed", reason: "Internal"}, + {name: "usage", args: []string{"cluster", "retire-host", "--json", "--bogus", "--master", "m:1"}, exit: 1, result: "failed", reason: "usage"}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) { + calls++ + if tc.err != nil { + return nil, tc.err + } + return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil + }} + withClusterMaster(t, f) + if tc.dialErr != nil { + clusterLifecycleDial = func(string) (control.LifecycleServiceClient, func() error, error) { return nil, nil, tc.dialErr } + } + args := tc.args + if args == nil { + args = []string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy", "--json"} + } + var out, errOut bytes.Buffer + code := run(args, &out, &errOut) + if code != tc.exit { + t.Fatalf("exit %d, want %d (stderr %q)", code, tc.exit, errOut.String()) + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(out.Bytes(), &keys); err != nil { + t.Fatalf("--json output %q: %v", out.String(), err) + } + var names []string + for k := range keys { + names = append(names, k) + } + sort.Strings(names) + if want := []string{"message", "reason", "result", "server", "volumes"}; !reflect.DeepEqual(names, want) { + t.Fatalf("--json keys %v, want %v for every outcome", names, want) + } + var a retireAnswer + if err := json.Unmarshal(out.Bytes(), &a); err != nil { + t.Fatal(err) + } + if a.Result != tc.result || a.Reason != tc.reason { + t.Fatalf("answer %+v, want result %q reason %q", a, tc.result, tc.reason) + } + if want := tc.volumes; want == nil && len(a.Volumes) != 0 || want != nil && !reflect.DeepEqual(a.Volumes, want) { + t.Fatalf("volumes %v, want %v", a.Volumes, want) + } + if tc.name == "usage" && calls != 0 { + t.Fatalf("a usage error sent %d retire RPCs", calls) + } + }) + } +} diff --git a/seaweed-block/cmd/sw-block/cluster_format_test.go b/seaweed-block/cmd/sw-block/cluster_format_test.go index a3c37e4515..00ca9ae047 100644 --- a/seaweed-block/cmd/sw-block/cluster_format_test.go +++ b/seaweed-block/cmd/sw-block/cluster_format_test.go @@ -76,7 +76,7 @@ func TestClusterFinalizeFormat(t *testing.T) { } } -// retire-host sends the server id and its confirm; a refusal exits 1. +// retire-host sends the server id and its confirm; a refusal exits 2. func TestClusterRetireHost(t *testing.T) { var got *control.RetireHostRequest f := &fakeClusterMaster{retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) { @@ -91,11 +91,11 @@ func TestClusterRetireHost(t *testing.T) { if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c"}, &out, &errOut); code != 0 || got.GetConfirm() != "node-c" || !strings.Contains(out.String(), "host node-c retired") { t.Fatalf("retire: exit %d, request %+v, stdout %q", code, got, out.String()) } - if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") { + if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "busy", "--confirm", "busy"}, &out, &errOut); code != 2 || !strings.Contains(errOut.String(), "holds a lease or an assignment for volumes v1") { t.Fatalf("refused retire: exit %d, stderr %q", code, errOut.String()) } - if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 2 { - t.Fatalf("retire without --confirm: exit %d, want 2", code) + if code := run([]string{"cluster", "retire-host", "--master", "m:1", "--server", "node-c"}, &out, &errOut); code != 1 { + t.Fatalf("retire without --confirm: exit %d, want 1", code) } } diff --git a/seaweed-block/cmd/sw-block/workspace.go b/seaweed-block/cmd/sw-block/workspace.go index c77e1e5968..48313acbeb 100644 --- a/seaweed-block/cmd/sw-block/workspace.go +++ b/seaweed-block/cmd/sw-block/workspace.go @@ -292,6 +292,7 @@ func workspacePreview(ctx context.Context, c *wsclient.Client, m wsclient.Forced if answer != nil { answer.Admitted, answer.Code = p.GetAdmitted(), p.GetCode() if !p.GetAdmitted() { + answer.Reason = p.GetReasonCode() if answer.Code == "" { answer.Code = "Unknown" } // older servers did not export a refusal code diff --git a/seaweed-block/cmd/sw-block/workspace_clean_test.go b/seaweed-block/cmd/sw-block/workspace_clean_test.go index faa8c15ea8..a884ebaaee 100644 --- a/seaweed-block/cmd/sw-block/workspace_clean_test.go +++ b/seaweed-block/cmd/sw-block/workspace_clean_test.go @@ -173,3 +173,27 @@ func TestWorkspaceForceMoveJSONCarriesOnlyTheTypedReason(t *testing.T) { }) } } + +// force-move --dry-run --json carries the preview's typed reason (the reason +// the move itself would carry); a refusal with only message text carries +// none. +func TestWorkspaceForceMovePreviewJSONCarriesTheTypedReason(t *testing.T) { + for _, tc := range []struct { + name string + preview *control.WorkspaceMovePreview + want string + }{ + {"typed", &control.WorkspaceMovePreview{Reason: "move target node \"node-b\" reads format level 0", Code: "FailedPrecondition", ReasonCode: lifecycleclient.ReasonBinaryTooOld}, lifecycleclient.ReasonBinaryTooOld}, + {"text-only", &control.WorkspaceMovePreview{Reason: "move target node \"node-b\" reads format level 0 (binary_too_old)", Code: "FailedPrecondition"}, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + f := &fakeWorkspace{status: wsHolder(), preview: tc.preview} + addr, _ := startFakeWorkspace(t, f) + code, out, errOut := runCLI(forceMoveArgs(addr, "--confirm-forced", "vol@3", "--dry-run", "--json")) + var a workspaceForceMoveAnswer + if json.Unmarshal([]byte(out), &a) != nil || a.Admitted || a.Code != "FailedPrecondition" || a.Reason != tc.want { + t.Fatalf("exit=%d out=%q err=%q answer=%+v; want reason %q", code, out, errOut, a, tc.want) + } + }) + } +} diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index 6538f04618..4c18ed5ce0 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -377,6 +377,15 @@ func (e errHostHoldsWork) Error() string { return fmt.Sprintf("retire refused: host %q holds a lease or an assignment for volumes %s; move them first", e.server, strings.Join(e.volumes, ", ")) } +// metadata keys each held volume for the refusal's typed detail. +func (e errHostHoldsWork) metadata() map[string]string { + md := make(map[string]string, len(e.volumes)) + for _, v := range e.volumes { + md[lifecycleclient.VolumeMetadataPrefix+v] = e.server + } + return md +} + // FinalizeFormat raises the cluster's format level to 1 (FormatGate: // Finalize; FormatGateMaster: the one durable step). It is refused while any // registered host has not reported reads_level >= 1 since this master @@ -480,7 +489,7 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques var holds errHostHoldsWork switch { case errors.As(err, &holds): - return nil, lifecycleclient.WithReason(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork).Err() + return nil, lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork, holds.metadata()).Err() case err != nil: return nil, status.Error(codes.FailedPrecondition, err.Error()) } diff --git a/seaweed-block/core/host/master/format_gate_test.go b/seaweed-block/core/host/master/format_gate_test.go index f509680559..41c60ecdf2 100644 --- a/seaweed-block/core/host/master/format_gate_test.go +++ b/seaweed-block/core/host/master/format_gate_test.go @@ -129,6 +129,12 @@ func TestFormatGateRefusesPlacementAndMoveOntoAnOldHost(t *testing.T) { if got := reasonOf(moveErr); got != wantReason { t.Fatalf("level 1: MoveWorkspace onto node-b: reason %q, want %q", got, wantReason) } + // The forced move's preview answers the same typed reason. + pv, err := r.ws.PreviewWorkspaceMove(r.ctx, &control.WorkspaceMove{RequestId: "p1", VolumeId: "placed", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: "127.0.0.1:19301", TargetCtrlAddr: "127.0.0.1:19302", Kind: "forced", Force: true}) + if err != nil || pv.GetAdmitted() || pv.GetReasonCode() != wantReason { + t.Fatalf("level 1: preview of a forced move onto node-b: %+v %v, want reason_code %q", pv, err, wantReason) + } }) } } @@ -278,6 +284,10 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) { if status.Code(err) != codes.FailedPrecondition || reasonOf(err) != lifecycleclient.ReasonHostHoldsWork || !strings.Contains(status.Convert(err).Message(), "held") { t.Fatalf("retire of a host holding a placement: %v (reason %q)", err, reasonOf(err)) } + // The held volumes are typed too: one metadata entry per volume. + if _, md := lifecycleclient.ReasonDetail(err); len(md) != 1 || md[lifecycleclient.VolumeMetadataPrefix+"held"] != "node-b" { + t.Fatalf("retire refusal metadata %v, want volume.held = node-b", md) + } if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-b"}); status.Code(err) != codes.FailedPrecondition { t.Fatalf("retire with a confirm that does not match: %v", err) } diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index 488f1c121c..eded2a3683 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -583,6 +583,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac if err := s.workspaceVolume(q.GetVolumeId()); err != nil { out.Reason = status.Convert(err).Message() out.Code = status.Code(err).String() + out.ReasonCode = lifecycleclient.Reason(err) return nil } r, target, _, why, err := s.workspaceMoveCheckLocked(q) @@ -594,7 +595,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac out.Admitted, out.LostUntilNs, out.MasterTimeNs = pv.Admitted, pv.LostUntilNS, pv.NowNS switch { case why.text != "": - out.Admitted, out.Reason = false, why.text + out.Admitted, out.Reason, out.ReasonCode = false, why.text, why.reason case !pv.Admitted: out.Reason = pv.Reason case pv.Replay: @@ -603,6 +604,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac if err := s.host.workspaceEndpointsAvailable(lifecycle.WorkspaceBinding{VolumeID: q.GetVolumeId(), ServerID: target.ServerID, DataAddr: q.GetTargetDataAddr(), CtrlAddr: q.GetTargetCtrlAddr()}); err != nil { out.Admitted, out.Reason = false, err.Error() out.Code = status.Code(workspaceError(err)).String() + out.ReasonCode = lifecycleclient.Reason(workspaceError(err)) } } return nil @@ -623,6 +625,7 @@ func (s *services) PreviewWorkspaceMove(ctx context.Context, q *control.Workspac if err != nil { out.Admitted, out.HeadError = false, err.Error() out.Code = status.Code(workspaceError(err)).String() + out.ReasonCode = lifecycleclient.Reason(workspaceError(err)) out.Reason = "workspace move: HEAD read failed: " + err.Error() return out, nil } diff --git a/seaweed-block/core/rpc/control/workspace.pb.go b/seaweed-block/core/rpc/control/workspace.pb.go index f2a59c7951..e65473ab96 100644 --- a/seaweed-block/core/rpc/control/workspace.pb.go +++ b/seaweed-block/core/rpc/control/workspace.pb.go @@ -932,7 +932,11 @@ type WorkspaceMovePreview struct { HeadTimeNs int64 `protobuf:"varint,11,opt,name=head_time_ns,json=headTimeNs,proto3" json:"head_time_ns,omitempty"` HeadTimeKnown bool `protobuf:"varint,12,opt,name=head_time_known,json=headTimeKnown,proto3" json:"head_time_known,omitempty"` // gRPC status code name for a refusal; empty when admitted. Additive output only. - Code string `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"` + Code string `protobuf:"bytes,13,opt,name=code,proto3" json:"code,omitempty"` + // The refusal's typed reason (the reason a MoveWorkspace refusal would carry + // in its ErrorInfo detail, e.g. BINARY_TOO_OLD); empty when admitted or + // when the refusal has none. Additive output only. + ReasonCode string `protobuf:"bytes,14,opt,name=reason_code,json=reasonCode,proto3" json:"reason_code,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1058,6 +1062,13 @@ func (x *WorkspaceMovePreview) GetCode() string { return "" } +func (x *WorkspaceMovePreview) GetReasonCode() string { + if x != nil { + return x.ReasonCode + } + return "" +} + type WorkspaceStatus struct { state protoimpl.MessageState `protogen:"open.v1"` Lease *WorkspaceLeaseFact `protobuf:"bytes,1,opt,name=lease,proto3" json:"lease,omitempty"` @@ -1350,7 +1361,7 @@ const file_workspace_proto_rawDesc = "" + "\n" + "request_id\x18\x02 \x01(\tR\trequestId\"Z\n" + "\x13WorkspaceLostRanges\x12C\n" + - "\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\xb1\x03\n" + + "\x06ranges\x18\x01 \x03(\v2+.seaweedfs.block.control.WorkspaceLostRangeR\x06ranges\"\xd2\x03\n" + "\x14WorkspaceMovePreview\x12\x1a\n" + "\badmitted\x18\x01 \x01(\bR\badmitted\x12\x16\n" + "\x06reason\x18\x02 \x01(\tR\x06reason\x12\"\n" + @@ -1369,7 +1380,9 @@ const file_workspace_proto_rawDesc = "" + "\fhead_time_ns\x18\v \x01(\x03R\n" + "headTimeNs\x12&\n" + "\x0fhead_time_known\x18\f \x01(\bR\rheadTimeKnown\x12\x12\n" + - "\x04code\x18\r \x01(\tR\x04code\"\xb2\x02\n" + + "\x04code\x18\r \x01(\tR\x04code\x12\x1f\n" + + "\vreason_code\x18\x0e \x01(\tR\n" + + "reasonCode\"\xb2\x02\n" + "\x0fWorkspaceStatus\x12A\n" + "\x05lease\x18\x01 \x01(\v2+.seaweedfs.block.control.WorkspaceLeaseFactR\x05lease\x12V\n" + "\x0erevocation_ack\x18\x02 \x01(\v2/.seaweedfs.block.control.WorkspaceRevocationAckR\rrevocationAck\x12=\n" + diff --git a/seaweed-block/core/rpc/lifecycleclient/reason.go b/seaweed-block/core/rpc/lifecycleclient/reason.go index 903458b8de..7f2b60ff9e 100644 --- a/seaweed-block/core/rpc/lifecycleclient/reason.go +++ b/seaweed-block/core/rpc/lifecycleclient/reason.go @@ -67,3 +67,7 @@ func ReasonDetail(err error) (string, map[string]string) { // HostMetadataPrefix keys one refused host in a reason's metadata: // "host." maps to what that host reported. const HostMetadataPrefix = "host." + +// VolumeMetadataPrefix keys one volume in a reason's metadata: +// "volume." maps to the host that holds it. +const VolumeMetadataPrefix = "volume." diff --git a/seaweed-block/core/rpc/proto/workspace.proto b/seaweed-block/core/rpc/proto/workspace.proto index 3c8bab1174..e973988872 100644 --- a/seaweed-block/core/rpc/proto/workspace.proto +++ b/seaweed-block/core/rpc/proto/workspace.proto @@ -84,6 +84,10 @@ message WorkspaceMovePreview { int64 head_time_ns = 11; bool head_time_known = 12; // gRPC status code name for a refusal; empty when admitted. Additive output only. string code = 13; + // The refusal's typed reason (the reason a MoveWorkspace refusal would carry + // in its ErrorInfo detail, e.g. BINARY_TOO_OLD); empty when admitted or + // when the refusal has none. Additive output only. + string reason_code = 14; } message WorkspaceStatus { WorkspaceLeaseFact lease = 1; WorkspaceRevocationAck revocation_ack = 2; From a13f2d6fdfa6bd2e53d534c669fc71e10488219a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 2 Dec 2026 07:31:45 -0800 Subject: [PATCH 6/6] sw-block, master: a failed --json answer fails the command; a retire's storage failure is Internal Review fixes. When the --json answer cannot be written, retire-host and finalize-format exit 1 instead of 0. A retire whose record removal failed answers Internal (the CLI's failed, exit 1), not FailedPrecondition (refused, exit 2); the node store's test hook can fail a removal for the control. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/cluster_format.go | 10 +++++-- .../cmd/sw-block/cluster_format_json_test.go | 28 +++++++++++++++++++ seaweed-block/core/host/master/format_gate.go | 12 +++++++- .../core/host/master/format_gate_test.go | 7 +++++ .../core/lifecycle/node_inventory.go | 17 ++++++++++- 5 files changed, 70 insertions(+), 4 deletions(-) diff --git a/seaweed-block/cmd/sw-block/cluster_format.go b/seaweed-block/cmd/sw-block/cluster_format.go index c92a8b9471..812faf9628 100644 --- a/seaweed-block/cmd/sw-block/cluster_format.go +++ b/seaweed-block/cmd/sw-block/cluster_format.go @@ -113,7 +113,7 @@ type finalizeHost struct { // back to v1.0.x works only before it: afterwards a v1.0.x master or holder // refuses the store (an expected refusal, not damage). The master refuses // it while any registered host does not read level 1, naming each one. -func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int { +func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) (code int) { fs := flag.NewFlagSet("sw-block cluster finalize-format", flag.ContinueOnError) fs.SetOutput(stderr) master := fs.String("master", "", "blockmaster gRPC address (required)") @@ -129,6 +129,9 @@ func runClusterFinalizeFormat(args []string, stdout, stderr io.Writer) int { if *jsonOut { if err := json.NewEncoder(stdout).Encode(answer); err != nil { fmt.Fprintln(stderr, "sw-block: cluster finalize-format: JSON output:", err) + if code == finalizeExitOK { + code = finalizeExitFailed // the answer a script reads was not written + } } } }() @@ -239,7 +242,7 @@ type retireAnswer struct { // The master refuses it while the host holds a lease or an assignment. Exit // codes as finalize-format's: 0 retired, 2 refused, 75 the master could not // be reached (EX_TEMPFAIL), 1 any other failure, a usage error included. -func runClusterRetireHost(args []string, stdout, stderr io.Writer) int { +func runClusterRetireHost(args []string, stdout, stderr io.Writer) (code int) { fs := flag.NewFlagSet("sw-block cluster retire-host", flag.ContinueOnError) fs.SetOutput(stderr) master := fs.String("master", "", "blockmaster gRPC address (required)") @@ -255,6 +258,9 @@ func runClusterRetireHost(args []string, stdout, stderr io.Writer) int { if jsonMode { if err := json.NewEncoder(stdout).Encode(answer); err != nil { fmt.Fprintln(stderr, "sw-block: cluster retire-host: JSON output:", err) + if code == finalizeExitOK { + code = finalizeExitFailed // the answer a script reads was not written + } } } }() diff --git a/seaweed-block/cmd/sw-block/cluster_format_json_test.go b/seaweed-block/cmd/sw-block/cluster_format_json_test.go index e950d80df4..7ff1e41b14 100644 --- a/seaweed-block/cmd/sw-block/cluster_format_json_test.go +++ b/seaweed-block/cmd/sw-block/cluster_format_json_test.go @@ -222,3 +222,31 @@ func TestClusterRetireHostTypedAnswer(t *testing.T) { }) } } + +// failingWriter refuses every write: a stdout the JSON answer cannot reach. +type failingWriter struct{} + +func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("stdout closed") } + +// A --json answer that cannot be written fails the command: a script that +// reads it must not see a successful exit without an answer. +func TestClusterJSONOutputFailureFailsTheCommand(t *testing.T) { + f := &fakeClusterMaster{ + finalize: func(*control.FinalizeFormatRequest) (*control.FinalizeFormatResponse, error) { + return &control.FinalizeFormatResponse{FormatLevel: 1}, nil + }, + retire: func(r *control.RetireHostRequest) (*control.RetireHostResponse, error) { + return &control.RetireHostResponse{ServerId: r.GetServerId()}, nil + }, + } + withClusterMaster(t, f) + for _, args := range [][]string{ + {"cluster", "finalize-format", "--master", "m:1", "--json"}, + {"cluster", "retire-host", "--master", "m:1", "--server", "node-c", "--confirm", "node-c", "--json"}, + } { + var errOut bytes.Buffer + if code := run(args, failingWriter{}, &errOut); code != 1 { + t.Fatalf("%v with an unwritable stdout: exit %d, want 1 (stderr %q)", args, code, errOut.String()) + } + } +} diff --git a/seaweed-block/core/host/master/format_gate.go b/seaweed-block/core/host/master/format_gate.go index 4c18ed5ce0..a1f53c81b7 100644 --- a/seaweed-block/core/host/master/format_gate.go +++ b/seaweed-block/core/host/master/format_gate.go @@ -377,6 +377,13 @@ func (e errHostHoldsWork) Error() string { return fmt.Sprintf("retire refused: host %q holds a lease or an assignment for volumes %s; move them first", e.server, strings.Join(e.volumes, ", ")) } +// errRetireStorage is a retire that failed to remove the host's record: a +// storage failure, not a refusal (the host may still be registered). +type errRetireStorage struct{ err error } + +func (e errRetireStorage) Error() string { return "retire: " + e.err.Error() } +func (e errRetireStorage) Unwrap() error { return e.err } + // metadata keys each held volume for the refusal's typed detail. func (e errHostHoldsWork) metadata() map[string]string { md := make(map[string]string, len(e.volumes)) @@ -441,7 +448,7 @@ func (h *Host) RetireHost(server, confirm string) error { return errHostHoldsWork{server: server, volumes: vols} } if err := h.lifecycle.Nodes.RemoveNode(server); err != nil { - return fmt.Errorf("retire: %w", err) + return errRetireStorage{err} } h.reads.forget(server) h.log.Printf("blockmaster: host %s retired from the node inventory", server) @@ -487,9 +494,12 @@ func (s *services) RetireHost(ctx context.Context, req *control.RetireHostReques defer s.host.workspaceMu.Unlock() err := s.host.RetireHost(req.GetServerId(), req.GetConfirm()) var holds errHostHoldsWork + var storage errRetireStorage switch { case errors.As(err, &holds): return nil, lifecycleclient.WithReasonMetadata(status.New(codes.FailedPrecondition, err.Error()), lifecycleclient.ReasonHostHoldsWork, holds.metadata()).Err() + case errors.As(err, &storage): + return nil, status.Error(codes.Internal, err.Error()) case err != nil: return nil, status.Error(codes.FailedPrecondition, err.Error()) } diff --git a/seaweed-block/core/host/master/format_gate_test.go b/seaweed-block/core/host/master/format_gate_test.go index 41c60ecdf2..acffac25f6 100644 --- a/seaweed-block/core/host/master/format_gate_test.go +++ b/seaweed-block/core/host/master/format_gate_test.go @@ -291,6 +291,13 @@ func TestRetireHostRefusesAHostThatHoldsWork(t *testing.T) { if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-b"}); status.Code(err) != codes.FailedPrecondition { t.Fatalf("retire with a confirm that does not match: %v", err) } + // A failure to remove the host's record is a storage failure (Internal), + // not a refusal: the CLI then answers "failed", exit 1. + r.m.Lifecycle().Nodes.SetPersistHookForTest(func() error { return errors.New("injected record removal failure") }) + if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); status.Code(err) != codes.Internal { + t.Fatalf("retire whose record removal failed: %v, want Internal", err) + } + r.m.Lifecycle().Nodes.SetPersistHookForTest(nil) if _, err := r.lc.RetireHost(r.ctx, &control.RetireHostRequest{ServerId: "node-a", Confirm: "node-a"}); err != nil { t.Fatalf("retire of a host holding nothing: %v", err) } diff --git a/seaweed-block/core/lifecycle/node_inventory.go b/seaweed-block/core/lifecycle/node_inventory.go index 798569ef4b..20027f6e09 100644 --- a/seaweed-block/core/lifecycle/node_inventory.go +++ b/seaweed-block/core/lifecycle/node_inventory.go @@ -68,7 +68,17 @@ type NodeInventoryStore struct { mu sync.Mutex dir string records map[string]NodeRegistration - published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + published sync.Map // committed NodeRegistration values; holder host checks never take mu (INV-WS-RENEW-NONBLOCKING-001) + failWrite func() error // tests: a non-nil error fails the next record write or removal +} + +// SetPersistHookForTest installs (nil clears) a callback that each later +// record write or removal of this store runs under the store mutex first. A +// non-nil error fails that change with nothing changed. Tests only. +func (s *NodeInventoryStore) SetPersistHookForTest(hook func() error) { + s.mu.Lock() + defer s.mu.Unlock() + s.failWrite = hook } // OpenNodeInventoryStore opens or creates a node inventory store. @@ -155,6 +165,11 @@ func (s *NodeInventoryStore) RemoveNode(serverID string) error { } s.mu.Lock() defer s.mu.Unlock() + if s.failWrite != nil { + if err := s.failWrite(); err != nil { + return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err) + } + } delete(s.records, serverID) if err := os.Remove(s.path(serverID)); err != nil && !errors.Is(err, os.ErrNotExist) { return fmt.Errorf("lifecycle: remove node %s: %w", serverID, err)