diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index b6ffd7f332..6da3c87084 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -255,6 +255,9 @@ jobs: KZ_SIZE: 1G F1_RUN: "1" TEST_TIMEOUT: 15m + # A failed test copies each daemon's whole log here (keepFullLog); + # the step below keeps them as the run's artifact. + SWBLOCK_TEST_LOG_DIR: ${{ runner.temp }}/process-level-logs run: | set -euo pipefail # SHARDS parallel shards, balanced by their last measured times @@ -290,3 +293,18 @@ jobs: cat "$RUNNER_TEMP"/process-level-*.status >"$RUNNER_TEMP/process-level.status" python3 -I .github/scripts/required-tests-check.py --status "$RUNNER_TEMP/process-level.status" \ "$names" "$RUNNER_TEMP"/process-level-*.json + + - name: Keep the process-level logs and shard results + # A failure's evidence outlives the runner's temp directory: each + # failed test's full daemon logs and every shard's raw JSON and log. + if: failure() && matrix.suite == 'process' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: process-level-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/process-level-logs + ${{ runner.temp }}/process-level-*.json + ${{ runner.temp }}/process-level-*.log + ${{ runner.temp }}/process-level-*.status + retention-days: 14 + if-no-files-found: warn diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 99da1827cb..a2760d7ff1 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -274,6 +274,11 @@ func (s *StatusServer) chunkMux() http.Handler { // cut slot is held (retryable). const codeHostSlotBusy = "host_slot_busy" +// codeInProgress: the upgrade compare pass after a v1.0 store's upgrade has +// not ended; the request is repeated later (the message carries the pass's +// progress; status reports it as Chunk.Stats.UpgradePass). +const codeInProgress = "in_progress" + func writeChunkJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) @@ -308,7 +313,10 @@ func writeChunkFailure(w http.ResponseWriter, err error) { // a refused capture reports why it was refused. func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError + var pass *storage.ErrUpgradePassInProgress switch { + case errors.As(err, &pass): + return http.StatusConflict, codeInProgress, true case errors.Is(err, durable.ErrPlainDetachBusy): return http.StatusConflict, "plain_detach_busy", true case errors.Is(err, storage.ErrPrecopyUnknown): diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 46652f2fd6..47200befcd 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -338,3 +338,15 @@ func TestStatusServer_ChunkBodyIsOneJSONObject(t *testing.T) { t.Fatalf("one object and a newline: %d %s", w.Code, w.Body) } } + +// A request refused while the upgrade compare pass runs answers its own +// code, in_progress, retryable, also when wrapped. +func TestChunkErrorCodeUpgradePassInProgress(t *testing.T) { + refusal := &storage.ErrUpgradePassInProgress{Compared: 3, Total: 16, Cursor: 2} + for _, err := range []error{refusal, fmt.Errorf("cut: %w", refusal)} { + status, code, retryable := chunkErrorCode(err) + if status != http.StatusConflict || code != "in_progress" || !retryable { + t.Fatalf("%v: %d %q %v, want 409 in_progress retryable", err, status, code, retryable) + } + } +} diff --git a/seaweed-block/core/hostlimit/tickets_test.go b/seaweed-block/core/hostlimit/tickets_test.go index 1aac20bffe..ead72c3545 100644 --- a/seaweed-block/core/hostlimit/tickets_test.go +++ b/seaweed-block/core/hostlimit/tickets_test.go @@ -3,6 +3,7 @@ package hostlimit import ( "context" "errors" + "fmt" "os" "path/filepath" "runtime" @@ -468,6 +469,7 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) { defer stalled.Close() const skip, cut, poll = 500 * time.Millisecond, 50 * time.Millisecond, 20 * time.Millisecond type admission struct { + worker int due int64 at, done time.Time } @@ -518,7 +520,7 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) { time.Sleep(cut) l.Release(id) mu.Lock() - log = append(log, admission{tk.Due(), at, time.Now()}) + log = append(log, admission{i, tk.Due(), at, time.Now()}) mu.Unlock() if tk, err = l.TakeTicket(HostNow()); err != nil { // the next cycle's cut t.Error(err) @@ -541,21 +543,33 @@ func TestOneStalledTicketCostsOneSkipNotEveryHandoff(t *testing.T) { if len(log) < 6 { t.Fatalf("only %d admissions in 10 s", len(log)) } - // A hand-off that paid the stalled ticket's skip idles at least the skip - // window after the release; scheduling and the workers' poll idle far less, - // even on a loaded host. So the bound is the skip window itself, not a - // fixed fraction of it. - gaps := make([]time.Duration, 0, len(log)) + // Each worker is its own limiter (its own process): it judges the stalled + // ticket on its own clock, which runs only while the slot is free, so a + // worker's FIRST admission may pay up to one skip window (a loaded host + // can start its clock late). The property is that no worker pays the skip + // again: a hand-off to a worker's later admission idles less than the skip + // window. The gaps are printed with the worker that took each slot. + gaps := make([]string, 0, len(log)) for i := 1; i < len(log); i++ { - gaps = append(gaps, log[i].at.Sub(log[i-1].done).Round(time.Millisecond)) + gaps = append(gaps, fmt.Sprintf("w%d:%s", log[i].worker, log[i].at.Sub(log[i-1].done).Round(time.Millisecond))) } + admitted := map[int]bool{log[0].worker: true} + later := 0 // hand-offs to a worker's later admission: the ones the bound checks for i := 1; i < len(log); i++ { if log[i].due <= log[i-1].due { t.Fatalf("admissions out of due order at %d", i) } - if gap := log[i].at.Sub(log[i-1].done); gap >= skip { - t.Fatalf("hand-off %d idled %s after the release, at least the skip window (%s): one stalled ticket must not cost every hand-off a skip (hand-off gaps %v)", i, gap.Round(time.Millisecond), skip, gaps) + first := !admitted[log[i].worker] + admitted[log[i].worker] = true + if !first { + later++ } + if gap := log[i].at.Sub(log[i-1].done); gap >= skip && !first { + t.Fatalf("hand-off %d to worker %d's later admission idled %s after the release, at least the skip window (%s): one stalled ticket must cost each worker one skip at most (hand-off gaps %v)", i, log[i].worker, gap.Round(time.Millisecond), skip, gaps) + } + } + if later == 0 { + t.Fatalf("no hand-off went to a worker's later admission, so the bound checked nothing (hand-off gaps %v)", gaps) } } diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 063fa98807..d7b1c1ef59 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -1130,6 +1130,33 @@ func waitReconciledForTest(t *testing.T, layer chunkLayer) { } time.Sleep(time.Millisecond) } + // An attach after an unclean v1.0 upgrade runs the compare pass, and + // cuts are refused until it ends; contract tests start after it, unless + // the test acts while it runs (withoutPassWait). + if skipPassWaitForTest { + return + } + // The pass reads every unknown chunk: a large test volume (262,144 + // chunks) takes seconds, so its bound is its own. + passDeadline := time.Now().Add(2 * time.Minute) + for layer.Stats().UpgradePass.State == "running" { + if time.Now().After(passDeadline) { + t.Fatalf("upgrade compare pass still running after 2m: %+v", layer.Stats().UpgradePass) + } + time.Sleep(time.Millisecond) + } +} + +// skipPassWaitForTest: the test attaches and acts while the upgrade compare +// pass runs (withoutPassWait). +var skipPassWaitForTest bool + +// withoutPassWait makes the attach helpers return without waiting for the +// upgrade compare pass, for a test that acts while it runs. +func withoutPassWait(t *testing.T) { + t.Helper() + skipPassWaitForTest = true + t.Cleanup(func() { skipPassWaitForTest = false }) } // crashOwnedMap closes the owned-map file of a crashed store without diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 4c3eb02b6c..9861a990a2 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -255,6 +255,16 @@ type chunkLayerImpl struct { // shadow is the chunk record driven beside the maps above (set at // attach, before the hooks publish; nil only in a layer built by hand). shadow *chunkRecordShadow + // pass is the upgrade compare pass when the store needs one (nil: none); + // passStatus is the state reported without one; passErr latches a pass + // that stopped on an error; passHurry hurries it once a request waits. + // pass, passStatus and passErr are guarded by stMu. + pass *upgradePass + passStatus UpgradePassStatus + passErr error + passHurry sync.Once + // passSuperseded counts chunks written during their own compare. + passSuperseded atomic.Uint64 // testShadowCheck receives each barrier's misses and extra record // candidates; set, it also makes the barrier collect the extras. testShadowCheck func(miss, extra []uint64) @@ -401,7 +411,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, err } + upgradedNow := false if chunkV11Format { + marked, _ := s.ChunkStateMarker() + upgradedNow = !marked l.shadow, err = l.openChunkRecordV11() } else { l.shadow, err = newChunkRecordShadow(l) @@ -410,6 +423,10 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, err } + if err := l.prepareUpgradePass(upgradedNow); err != nil { + l.cancel() + return nil, fmt.Errorf("storage: chunk layer attach: upgrade compare pass: %w", err) + } hooks := &chunkHooks{sink: l, closer: l.Close, mutated: l.noteMutation, recovered: l.noteAllMutated} hooks.baseTransitionV3 = l.holdBaseTransitionV3 @@ -426,9 +443,13 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) return nil, err } if sh := l.shadow; sh != nil && sh.v11 { + if h := dueLoopStartTestHook; h != nil { + h() + } l.wg.Add(1) go l.writeDueLoop(l.ctx, sh) } + l.runUpgradePass() // Every later drain reaches OnExtentWrite: release a held drain. s.drainHeld.Store(false) if s.flusher != nil { @@ -1445,6 +1466,11 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch return chunkCutResult{}, err } defer done() + // A cut seals and publishes: refused while the upgrade compare pass has + // not ended (every chunk's hash must be known), typed, with its progress. + if err := l.admitUpgradePass(); err != nil { + return chunkCutResult{}, err + } l.startCutStatus() defer l.clearCutStatus() start := time.Now() @@ -2785,6 +2811,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats { current := *l.currentCut out.CurrentCut = ¤t } + out.UpgradePass = l.upgradePassStatusLocked() out.Hydration.WorkerLimit = l.cfg.HydrationWorkers out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth for _, f := range l.hydration { diff --git a/seaweed-block/core/storage/chunk_record_open.go b/seaweed-block/core/storage/chunk_record_open.go index 803235fef6..e798ff3e1c 100644 --- a/seaweed-block/core/storage/chunk_record_open.go +++ b/seaweed-block/core/storage/chunk_record_open.go @@ -173,6 +173,11 @@ func (l *chunkLayerImpl) loadChunkRecordV11(dir string, epoch uint64) (*chunkRec valid[seg] = 0 } sh := &chunkRecordShadow{zeroSum: l.zeroChunkSum(), version: l.chunkVersion, v11: true} + for seg := range rebuilt { + if first := seg * chunkRecordSegment; !sh.rebuilt || first < sh.cursorBack { + sh.cursorBack, sh.rebuilt = first, true + } + } sh.applied.Store(storePos) rec, err := newChunkRecordRuntime(dir, l.numChunks, epoch, sh.applied.Load, kinds, hashes, valid, ld.Header.G, changedAtOpen) if err != nil { diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index 7d6fab4b86..214a4e9625 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -30,6 +30,11 @@ import ( type chunkRecordShadow struct { rec *chunkRecordRuntime zeroSum [32]byte + // cursorBack is the first chunk of the earliest page rebuilt at open + // (rebuilt says one was): the kernel's Rebuilt rows move the upgrade + // pass's cursor back there (cursor_back). Set once at open. + cursorBack uint64 + rebuilt bool mu sync.Mutex defects int // kernel refusals and evidence refusals of shell events diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 0252b6538e..2f7d3dacc0 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -204,6 +204,7 @@ func TestShadowCutOfAPartialChunkKeepsItPartial(t *testing.T) { // E8: with no HEAD, a write checkpointed out of the WAL before attach stays // a candidate (the map's dirt), so the record starts it U, never HP. func TestShadowAttachKeepsACheckpointedWriteACandidate(t *testing.T) { + withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows s, _ := newMappedCheckpointStoreV3(t) writeSynced(t, s, 5, 5) if err := s.flusher.flushOnce(); err != nil { diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go index e1f974b509..e1d75b3c76 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade.go +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -125,7 +125,17 @@ func upgradeChunkRecordSeeded(ctx context.Context, s *WALStore, epoch uint64, se if seeding { hashOf = cleanStopHashes(seed, pos) } - return writeChunkRecordPagesFrom(dir, chunks, pos, r, hashOf, progress) + if err := writeChunkRecordPagesFrom(dir, chunks, pos, r, hashOf, progress); err != nil { + return err + } + // An unseeded upgrade leaves its whole local chunks unknown: the + // compare pass's first cursor is written here, before the store's + // marker, so a crash anywhere after the marker still finds the pass + // to run (the attach resumes a cursor; it never infers one). + if !seeding { + return writeInitialUpgradePassCursor(dir, epoch) + } + return nil } if marked, e := s.ChunkStateMarker(); marked { if e != epoch { diff --git a/seaweed-block/core/storage/chunk_record_v11_hold_test.go b/seaweed-block/core/storage/chunk_record_v11_hold_test.go index 7ad96406a1..54b81fcf60 100644 --- a/seaweed-block/core/storage/chunk_record_v11_hold_test.go +++ b/seaweed-block/core/storage/chunk_record_v11_hold_test.go @@ -13,6 +13,7 @@ import ( // in the store's bits. Mutant (holds only on Fill to HP): the page says U // while the bits say some. func TestV11PartialFillWaitsForTheDurableMark(t *testing.T) { + withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows s, path, l, f := v11LazyVolume(t) const idx = 2 if _, err := s.Write(uint32(idx*ctChunkBlocks), makeBlock(ctBlockSize, 0x77)); err != nil { diff --git a/seaweed-block/core/storage/chunk_record_v11_seed_test.go b/seaweed-block/core/storage/chunk_record_v11_seed_test.go index 464ba35cd2..b8fad1a794 100644 --- a/seaweed-block/core/storage/chunk_record_v11_seed_test.go +++ b/seaweed-block/core/storage/chunk_record_v11_seed_test.go @@ -12,6 +12,7 @@ import ( // in HEAD), synced at HEAD's position, upgrades with every chunk hash-known and published with its // content's hash; without the proof every chunk is unknown, for the pass. func TestV11AttachSeedsFromTheCleanStopInItsConfig(t *testing.T) { + withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows for _, tc := range []struct { name string proof bool diff --git a/seaweed-block/core/storage/chunk_record_v11_test.go b/seaweed-block/core/storage/chunk_record_v11_test.go index aa6d36c7a2..b05ee7a4be 100644 --- a/seaweed-block/core/storage/chunk_record_v11_test.go +++ b/seaweed-block/core/storage/chunk_record_v11_test.go @@ -51,6 +51,7 @@ func v11Attach(t *testing.T, s *WALStore, f *fakeChunkRemote) *chunkLayerImpl { // .chunkpresence is gone, and the record's pages are written (page I/O on). // A store without the format build keeps the v1.0 path: no marker, no record. func TestV11AttachUpgradesTheStoreOnce(t *testing.T) { + withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows t.Run("v1.0 build", func(t *testing.T) { v10Only(t) s, path := v11Store(t) @@ -199,6 +200,7 @@ func v11Reopen(t *testing.T, s *WALStore, path string, f *fakeChunkRemote) *chun // - a .chunkpresence left after the record completed is removed, and its // content is not read (the record holds presence). func TestV11UpgradeRecoversFromACrashAtEachStep(t *testing.T) { + withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows t.Run("stale pages before the marker", func(t *testing.T) { withV11Format(t) s, path := v11Store(t) @@ -261,6 +263,7 @@ func TestV11UpgradeRecoversFromACrashAtEachStep(t *testing.T) { // blocks are all local reopens U, never the damaged page's word for it. func TestV11DamagedPageIsRebuiltFromTheStoreBits(t *testing.T) { withV11Format(t) + withoutUpgradePass(t) // the rebuild's own state (the pass after it: TestV11UpgradePassRewindsBelowItsCursorAfterARebuiltPage) s, path := v11Store(t) f := newFakeChunkRemote() l := v11Attach(t, s, f) diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index d4592a749c..389954e237 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -540,6 +540,7 @@ type chunkLayerStats struct { LastCutH uint64 // the LSN the last successful cut published LastCutNs int64 // when it completed (wall clock, Unix ns) CutSeq uint64 // successful cuts of this layer so far (in-process); the latest cut's identity + UpgradePass UpgradePassStatus // the upgrade compare pass after a v1.0 store's upgrade (v1.1): none, seeded, running, done or failed // BarrierOverBound counts cuts whose barrier copied more than the // bound after the staging rounds. BarrierOverBound uint64 diff --git a/seaweed-block/core/storage/chunk_space_baseline_test.go b/seaweed-block/core/storage/chunk_space_baseline_test.go index 03c493a2eb..68f2f73d6b 100644 --- a/seaweed-block/core/storage/chunk_space_baseline_test.go +++ b/seaweed-block/core/storage/chunk_space_baseline_test.go @@ -66,6 +66,7 @@ func (r ownedHeadRemote) CASHeadDelta(ctx context.Context, e chunkHeadVersion, n // fake's own HEAD exists before the first reading; the layer's copy has its // own keys (ownedHeadRemote). func heldPerChunk(t *testing.T, chunks uint64, chunkBlocks int, owner string) float64 { + withoutUpgradePass(t) // the upgrade's own state, or a measurement the pass only slows t.Helper() f := newFakeChunkRemote() f.mu.Lock() diff --git a/seaweed-block/core/storage/chunk_upgrade_pass.go b/seaweed-block/core/storage/chunk_upgrade_pass.go index efd68a5d7a..a3d5c16673 100644 --- a/seaweed-block/core/storage/chunk_upgrade_pass.go +++ b/seaweed-block/core/storage/chunk_upgrade_pass.go @@ -78,6 +78,18 @@ func decodeUpgradePassCursor(b []byte) (upgradePassCursor, error) { // readUpgradePassCursor reads the persisted cursor for epoch. A missing or // damaged cursor, or one of another epoch, starts the pass at chunk 0: that // repeats work, never skips it. +// writeInitialUpgradePassCursor writes the pass's first cursor (nothing +// compared yet) for epoch, unless a cursor is already there (a re-run of the +// upgrade keeps the progress it finds). +func writeInitialUpgradePassCursor(dir string, epoch uint64) error { + if _, err := os.Stat(filepath.Join(dir, upgradePassCursorName)); err == nil { + return nil + } else if !os.IsNotExist(err) { + return err + } + return writeChunkRecordFile(dir, upgradePassCursorName, encodeUpgradePassCursor(upgradePassCursor{Epoch: epoch})) +} + func readUpgradePassCursor(dir string, epoch uint64) (upgradePassCursor, error) { b, err := os.ReadFile(filepath.Join(dir, upgradePassCursorName)) if errors.Is(err, os.ErrNotExist) { @@ -164,6 +176,14 @@ func newUpgradePass(dir string, epoch, chunks uint64, pages upgradePassPages, co cur: c, next: c.Next, wt: c.Next, rew: noRewind, done: c.Next == chunks}, nil } +// progress is the pass's work and whether it has ended: the chunks compared +// (persisted, plus those since the persisted cursor), and the chunks it walks. +func (p *upgradePass) progress() (compared, total uint64, done bool) { + p.mu.Lock() + defer p.mu.Unlock() + return p.cur.Compared + p.pending, p.chunks, p.done +} + // Admit answers a request that needs every chunk's hash known: nil once the // pass has ended, else the typed refusal with its progress. func (p *upgradePass) Admit() error { diff --git a/seaweed-block/core/storage/chunk_upgrade_pass_attach_test.go b/seaweed-block/core/storage/chunk_upgrade_pass_attach_test.go new file mode 100644 index 0000000000..217f4c4de7 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upgrade_pass_attach_test.go @@ -0,0 +1,87 @@ +package storage + +import ( + "crypto/sha256" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// After an unclean stop there is no clean-stop proof, so the v1.0.x upgrade +// leaves every whole local chunk unknown (U). The attach then runs the +// compare pass, which leaves none unknown: a chunk equal to HEAD becomes +// hash-known and published with HEAD's hash; a chunk that differs from HEAD +// stays a candidate, never with HEAD's hash. +// +// HEAD names chunks 1, 2 and 3; the store holds chunks 1 and 2 as HEAD has +// them and chunk 3 with other bytes; every other chunk is zero on both sides. +// +// The wait below is a bound on a pass over 16 chunks; once the pass reports +// its completion, that signal can replace it. +func TestV11UncleanUpgradeLeavesNoUnknownAfterThePass(t *testing.T) { + withV11Format(t) + withoutPassWait(t) // the test watches the pass from the attach on + s, _ := v11Store(t) + if err := s.SetLayoutIdentity("claim-a", false); err != nil { + t.Fatal(err) + } + n := int(s.NumBlocks()) + head := make([]byte, n*ctBlockSize) + for lba := ctChunkBlocks; lba < 4*ctChunkBlocks; lba++ { // chunks 1, 2, 3 in HEAD + copy(head[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba))) + } + for lba := ctChunkBlocks; lba < 4*ctChunkBlocks; lba++ { + b := head[lba*ctBlockSize : (lba+1)*ctBlockSize] + if lba >= 3*ctChunkBlocks { // chunk 3 differs locally + b = makeBlock(ctBlockSize, byte(0x90+lba)) + } + if _, err := s.Write(uint32(lba), b); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + f.seedHead(t, head, syncedPos(s), 1) + cfg := ctConfig(2) + cfg.Bitmap = nil // and no CleanStop: an unclean stop + l := mustAttach(t, s, f, cfg).(*chunkLayerImpl) + + if k := shadowKind(l, 1); k != chunkkernel.Unknown { + t.Fatalf("the control needs an upgrade without a seed: chunk 1 opened %s, want U", k) + } + bound := 20 * time.Second + for deadline := time.Now().Add(bound); ; time.Sleep(50 * time.Millisecond) { + var unknown []uint64 + for c := uint64(0); c < l.numChunks; c++ { + if shadowKind(l, c) == chunkkernel.Unknown { + unknown = append(unknown, c) + } + } + if len(unknown) == 0 { + break + } + if time.Now().After(deadline) { + t.Fatalf("after %s chunks %v are still unknown: no compare pass ran over the upgraded store", bound, unknown) + } + } + hashOf := func(c uint64) [32]byte { + l.shadow.rec.mu.Lock() + defer l.shadow.rec.mu.Unlock() + return l.shadow.rec.hashes[c] + } + for _, c := range []uint64{1, 2} { + first := int(c) * ctChunkBlocks * ctBlockSize + want := sha256.Sum256(head[first : first+ctChunkBlocks*ctBlockSize]) + if k, h := shadowKind(l, c), hashOf(c); k != chunkkernel.HashPublished || h != want { + t.Fatalf("chunk %d equal to HEAD ended %s with hash %x, want HP with HEAD's %x", c, k, h[:4], want[:4]) + } + } + first := 3 * ctChunkBlocks * ctBlockSize + headSum := sha256.Sum256(head[first : first+ctChunkBlocks*ctBlockSize]) + if k, h := shadowKind(l, 3), hashOf(3); k == chunkkernel.HashPublished && h == headSum { + t.Fatal("chunk 3, which differs from HEAD, ended published with HEAD's hash") + } +} diff --git a/seaweed-block/core/storage/chunk_upgrade_wire.go b/seaweed-block/core/storage/chunk_upgrade_wire.go new file mode 100644 index 0000000000..37fcab4833 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upgrade_wire.go @@ -0,0 +1,233 @@ +package storage + +import ( + "context" + "crypto/sha256" + "log" + "os" + "path/filepath" + "time" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// The upgrade compare pass in a running layer. After a v1.0 store's upgrade +// with no clean-stop seed every whole local chunk is unknown; the attach runs +// the pass (chunk_upgrade_pass.go), which compares each with HEAD and +// persists its cursor as it goes. A stop never waits for it: the next attach +// resumes at the persisted cursor. Until it has ended, every request that +// seals or publishes (a cut, a snapshot, a backup, a sealing detach) is +// refused with ErrUpgradePassInProgress, which carries the progress, and the +// pass runs at full rate from then on. + +// UpgradePassStatus is the pass's state as holder status reports it: none +// (the store needs no pass), seeded (a clean-stop seed made every chunk +// known at the upgrade), running, done, or failed (Outcome says why). +// Compared counts the chunks the pass found unknown and compared; Total is +// the chunks it walks. It is carried across a stop by the pass's cursor. +type UpgradePassStatus struct { + State string // none, seeded, running, done or failed; carried across a stop (read the status, never the pass's cursor file) + Compared uint64 // chunks the pass found unknown and compared, across stops + Total uint64 // chunks the pass walks + // Superseded counts chunks written during their own compare (in this + // process): not hashed, not counted as compared; each is dirty and the + // next cut takes it as any written chunk. + Superseded uint64 + Outcome string `json:",omitempty"` // why a failed pass stopped; while the pass has not ended a cut, snapshot, backup or sealing detach is refused with code in_progress +} + +// startUpgradePass decides the pass at attach and starts it when work +// remains: a persisted cursor resumes it (or reports it done); with no cursor +// it starts only if the record holds an unknown chunk. upgradedNow says the +// store was upgraded by this attach (for the seeded state). Owner: the +// layer's attach; the pass runs on the layer's context and wait group. +// prepareUpgradePass decides whether a compare pass runs and, for a page +// rebuilt at open, rewinds its cursor durably. The attach calls it before +// anything can write the record's pages (the hooks, the due loop): a rebuilt +// page republished as valid before the rewind is durable would hide the +// damage from the next open after a crash, and the rewind with it. +func (l *chunkLayerImpl) prepareUpgradePass(upgradedNow bool) error { + sh := l.shadow + if sh == nil || !sh.v11 || upgradePassTestDisabled { + return nil + } + dir := chunkRecordDir(l.s.path) + _, epoch := l.s.ChunkStateMarker() + _, statErr := os.Stat(filepath.Join(dir, upgradePassCursorName)) + if statErr != nil && !os.IsNotExist(statErr) { + return statErr + } + // No cursor: a pass starts only after an unseeded upgrade by this attach + // (its chunks are unknown) or when a page was rebuilt at open. Chunks + // unknown only because they were written are dirty: cuts take them. + _, anyU := sh.firstUnknown() + if os.IsNotExist(statErr) && !(upgradedNow && anyU) && !sh.rebuilt { + state := "none" + if upgradedNow && l.cfg.CleanStop != nil { + state = "seeded" + } + l.stMu.Lock() + l.passStatus = UpgradePassStatus{State: state, Total: l.numChunks} + l.stMu.Unlock() + return nil + } + p, err := newUpgradePass(dir, epoch, l.numChunks, sh.rec, l.upgradeCompare) + if err != nil { + return err + } + // A page rebuilt at open (damage, a stale page) left its chunks unknown + // again, possibly behind the persisted cursor or a pass that had ended: + // the cursor goes back, durably, to the first chunk of the earliest + // rebuilt page (the kernel's cursor_back) before any request is admitted. + if sh.rebuilt { + if h := upgradeRewindTestHook; h != nil { + h() + } + if err := p.Rewind(sh.cursorBack); err != nil { + return err + } + } + if d := upgradePassTestInterval; d > 0 { + p.interval = d + } + if n := upgradePassTestPersistEvery; n > 0 { + p.persistEvery = n + } + l.stMu.Lock() + l.pass = p + l.stMu.Unlock() + return nil +} + +// runUpgradePass starts the pass prepareUpgradePass set up, once the attach +// has started the record's publisher. +func (l *chunkLayerImpl) runUpgradePass() { + l.stMu.Lock() + p := l.pass + l.stMu.Unlock() + if p == nil || p.Admit() == nil { + return // no pass, or it ended before this attach + } + l.wg.Add(1) + go func() { + defer l.wg.Done() + err := p.Run(l.ctx) + if err != nil && l.ctx.Err() != nil { + // A stop: the pages of every chunk compared so far are written + // through and the cursor persisted (at most persistEvery chunks + // of work), so the next attach resumes there. The stop waits + // for this, never for the rest of the pass. + if err := p.advance(); err != nil { + log.Printf("level=WARN storage: upgrade compare pass: cursor at stop: %v", err) + } + return + } + if err != nil { + l.stMu.Lock() + l.passErr = err + l.stMu.Unlock() + log.Printf("level=WARN storage: upgrade compare pass stopped: %v", err) + } + }() +} + +// upgradePassTestInterval, set by tests only, slows the pass (a pause between +// chunks) so a test can act while it runs; upgradePassTestPersistEvery +// persists its cursor more often; upgradeCompareTestHook sees each chunk the +// pass compares. +var ( + upgradePassTestDisabled bool // tests of the upgrade itself: the state it leaves, no pass after it + upgradePassTestInterval time.Duration + upgradePassTestPersistEvery uint64 + upgradeCompareTestHook func(ctx context.Context, idx uint64) + upgradeRewindTestHook func() + dueLoopStartTestHook func() // the attach is about to start the record's due loop + upgradeAfterReadTestHook func(idx uint64) +) + +// upgradeCompare compares one chunk with HEAD for the pass: an unknown local +// chunk is read and hashed, and its record takes the hash (and HEAD's +// publication when HEAD names that hash), the same transitions a cut's +// compare makes. It reports whether the chunk was unknown. +func (l *chunkLayerImpl) upgradeCompare(ctx context.Context, idx uint64) (bool, error) { + sh := l.shadow + if sh == nil || sh.rec.Kind(idx) != chunkkernel.Unknown { + return false, nil + } + l.stMu.Lock() + absent := l.absent[idx] + version := l.chunkVersion(idx) + base := l.cutBaseLocked(map[uint64]bool{idx: true}) + l.stMu.Unlock() + if absent { + return false, nil // not local: nothing to compare + } + if h := upgradeCompareTestHook; h != nil { + h(ctx, idx) + } + data, err := l.readChunk(idx) + if err != nil { + return false, err + } + if h := upgradeAfterReadTestHook; h != nil { + h(idx) + } + c := capturedChunk{idx: idx, version: version, data: data, sum: sha256.Sum256(data), zero: isAllZero(data)} + sh.hashed(c, func() uint64 { return l.chunkVersion(idx) }, base) + // Superseded by a write: a write since the read leaves the chunk unknown + // (the record refused the stale version's hash). The premise: during the + // pass only the write path moves a chunk's version, and a write marks the + // chunk dirty (chunkMut), so the next cut takes it as any written chunk, + // also after a restart (the write is in the WAL). It is not counted as + // compared. + if sh.rec.Kind(idx) == chunkkernel.Unknown { + l.passSuperseded.Add(1) + return false, nil + } + return true, nil +} + +// admitUpgradePass refuses a request that seals or publishes while the pass +// has not ended (typed, with its progress) and hurries the pass from then on. +func (l *chunkLayerImpl) admitUpgradePass() error { + l.stMu.Lock() + p := l.pass + l.stMu.Unlock() + if p == nil { + return nil + } + err := p.Admit() + if err != nil { + l.passHurry.Do(func() { _ = p.Hurry() }) // released never: the pass ends + } + return err +} + +// upgradePassStatusLocked is the pass's status for Stats. Caller holds stMu. +func (l *chunkLayerImpl) upgradePassStatusLocked() UpgradePassStatus { + if l.pass == nil { + return l.passStatus + } + compared, total, done := l.pass.progress() + st := UpgradePassStatus{State: "running", Compared: compared, Total: total, Superseded: l.passSuperseded.Load()} + switch { + case l.passErr != nil: + st.State, st.Outcome = "failed", l.passErr.Error() + case done: + st.State = "done" + } + return st +} + +// firstUnknown is the record's first unknown chunk, if any (O(S), once at +// attach). +func (s *chunkRecordShadow) firstUnknown() (uint64, bool) { + s.rec.mu.Lock() + defer s.rec.mu.Unlock() + for i, code := range s.rec.kinds { + if kindByCode[code] == chunkkernel.Unknown { + return uint64(i), true + } + } + return 0, false +} diff --git a/seaweed-block/core/storage/chunk_upgrade_wire_test.go b/seaweed-block/core/storage/chunk_upgrade_wire_test.go new file mode 100644 index 0000000000..4dcad2fa73 --- /dev/null +++ b/seaweed-block/core/storage/chunk_upgrade_wire_test.go @@ -0,0 +1,450 @@ +package storage + +import ( + "bytes" + "context" + "errors" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/chunkkernel" +) + +// uncleanUpgradeStore is a v1.0 store of 16 chunks written as HEAD has them +// (chunks 1-3 nonzero), and a fake remote holding that HEAD: attached on the +// v1.1 format with no clean-stop proof, every chunk opens unknown. +func uncleanUpgradeStore(t *testing.T) (*WALStore, string, *fakeChunkRemote) { + t.Helper() + s, path := v11Store(t) + if err := s.SetLayoutIdentity("claim-a", false); err != nil { + t.Fatal(err) + } + head := make([]byte, int(s.NumBlocks())*ctBlockSize) + for lba := ctChunkBlocks; lba < 4*ctChunkBlocks; lba++ { + copy(head[lba*ctBlockSize:], makeBlock(ctBlockSize, byte(0x40+lba))) + if _, err := s.Write(uint32(lba), head[lba*ctBlockSize:(lba+1)*ctBlockSize]); err != nil { + t.Fatal(err) + } + } + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + f := newFakeChunkRemote() + f.seedHead(t, head, syncedPos(s), 1) + return s, path, f +} + +func uncleanAttach(t *testing.T, s *WALStore, f *fakeChunkRemote) *chunkLayerImpl { + t.Helper() + cfg := ctConfig(2) + cfg.Bitmap = nil + return mustAttach(t, s, f, cfg).(*chunkLayerImpl) +} + +func waitPass(t *testing.T, l *chunkLayerImpl, what string, ok func(UpgradePassStatus) bool) UpgradePassStatus { + t.Helper() + for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(10 * time.Millisecond) { + st := l.Stats().UpgradePass + if ok(st) { + return st + } + if time.Now().After(deadline) { + t.Fatalf("%s: pass status %+v", what, st) + } + } +} + +// withoutUpgradePass attaches with no compare pass after the upgrade, for a +// test of the upgrade itself (the record state it leaves) or of something +// the pass would only slow down. +func withoutUpgradePass(t *testing.T) { + t.Helper() + upgradePassTestDisabled = true + t.Cleanup(func() { upgradePassTestDisabled = false }) +} + +// blockPassAt makes the pass stop at chunk at (inside its compare) until the +// returned release is called or the pass is stopped (Close); reached is +// closed when it gets there. The test acts while the pass is held there, with +// no timing, and no cleanup order can join a held pass. +func blockPassAt(t *testing.T, at uint64) (reached <-chan struct{}, release func()) { + t.Helper() + withoutPassWait(t) + r, rel := make(chan struct{}), make(chan struct{}) + var once, relOnce sync.Once + upgradeCompareTestHook = func(ctx context.Context, idx uint64) { + if idx == at { + once.Do(func() { close(r) }) + select { + case <-rel: + case <-ctx.Done(): + } + } + } + release = func() { relOnce.Do(func() { close(rel) }) } + t.Cleanup(func() { release(); upgradeCompareTestHook, upgradePassTestPersistEvery = nil, 0 }) + return r, release +} + +func waitReached(t *testing.T, reached <-chan struct{}) { + t.Helper() + select { + case <-reached: + case <-time.After(20 * time.Second): + t.Fatal("the pass never reached its barrier") + } +} + +// A stop mid-pass never waits for the pass: Close returns at once, with the +// pages of the chunks compared so far written and the cursor persisted. The +// next attach resumes at that cursor (no chunk below it is compared again), +// the status carries the count across the stop, and the pass ends with no +// chunk unknown. +func TestV11UpgradePassStopResumesAtTheCursor(t *testing.T) { + withV11Format(t) + const at = 5 + reached, _ := blockPassAt(t, at) + upgradePassTestPersistEvery = 2 + s, path, f := uncleanUpgradeStore(t) + l := uncleanAttach(t, s, f) + waitReached(t, reached) // chunks 0-4 compared, the pass held inside chunk 5 + if st := l.Stats().UpgradePass; st.State != "running" || st.Total != l.numChunks { + t.Fatalf("status while held: %+v", st) + } + closed := make(chan error, 1) + go func() { closed <- l.Close() }() // the stop releases the held compare: no release() can win before it + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("Close waited for the rest of the pass") + } + _, epoch := s.ChunkStateMarker() + cur, err := readUpgradePassCursor(chunkRecordDir(path), epoch) + // The stop lands inside chunk at's compare: the cursor is at+1 when that + // compare completed, at when it was cut short; every chunk below it is + // compared either way. + if err != nil || (cur.Next != at && cur.Next != at+1) || cur.Compared != cur.Next { + t.Fatalf("the cursor at the stop: %+v %v; want next %d or %d with every chunk below it compared", cur, err, at, at+1) + } + crashStore(t, s) + r := reopenRecovered(t, path) + r.HoldExtentDrainUntilChunkLayer() + var mu sync.Mutex + var again []uint64 + upgradeCompareTestHook = func(_ context.Context, idx uint64) { + mu.Lock() + again = append(again, idx) + mu.Unlock() + } + l2 := uncleanAttach(t, r, f) + st := waitPass(t, l2, "the resumed pass never ended", func(st UpgradePassStatus) bool { return st.State == "done" }) + mu.Lock() + defer mu.Unlock() + for _, idx := range again { + if idx < cur.Next { + t.Fatalf("the resumed pass compared chunk %d again, below its cursor %d", idx, cur.Next) + } + } + if st.Compared != l2.numChunks { + t.Fatalf("done status %+v; want every one of %d chunks compared across the stop", st, l2.numChunks) + } + for c := uint64(0); c < l2.numChunks; c++ { + if k := shadowKind(l2, c); k == chunkkernel.Unknown { + t.Fatalf("chunk %d still unknown after the resumed pass", c) + } + } +} + +// Every request that seals or publishes waits for the pass: while it runs, a +// cut and a sealing detach are refused with ErrUpgradePassInProgress (its +// progress, nothing published, HEAD still active); once it is done the same +// cut and detach succeed. A sealing detach never degrades to an unsealed one. +func TestV11SealingRequestsWaitForTheUpgradePass(t *testing.T) { + withV11Format(t) + reached, release := blockPassAt(t, 3) + s, _, f := uncleanUpgradeStore(t) + l := uncleanAttach(t, s, f) + waitReached(t, reached) // the pass is running, held inside chunk 3 + casBefore := f.stats().cas + for name, op := range map[string]func() error{ + "cut": func() error { _, err := l.Cut(ctTimeout(t)); return err }, + "detach": func() error { _, err := l.Detach(ctTimeout(t)); return err }, + } { + var refusal *ErrUpgradePassInProgress + if err := op(); !errors.As(err, &refusal) || refusal.Total != l.numChunks { + t.Fatalf("%s during the pass: %v, want ErrUpgradePassInProgress with the progress", name, err) + } + } + if f.stats().cas != casBefore || chunkHeadIsDetached(f.stats().head) { + t.Fatal("a refused request published or detached HEAD") + } + release() + waitPass(t, l, "the pass never ended", func(st UpgradePassStatus) bool { return st.State == "done" }) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatalf("cut after the pass: %v", err) + } + r, err := l.Detach(ctTimeout(t)) + if err != nil || r.Head.State != chunkHeadDetached { + t.Fatalf("sealing detach after the pass: %+v %v, want a sealed (detached) HEAD", r.Head, err) + } +} + +// A page rebuilt at open (damage) leaves its chunks unknown again behind the +// pass's cursor: the attach rewinds the cursor, durably and before any +// request is admitted, to the first of them and compares them again, so none +// stays unknown. Both a pass that had ended (a completed cursor) and one +// stopped midway (a partial cursor) rewind. +func TestV11UpgradePassRewindsBelowItsCursorAfterARebuiltPage(t *testing.T) { + for _, partial := range []bool{false, true} { + t.Run(map[bool]string{false: "completed cursor", true: "partial cursor"}[partial], func(t *testing.T) { + withV11Format(t) + s, path, f := uncleanUpgradeStore(t) + var l *chunkLayerImpl + if partial { + reached, _ := blockPassAt(t, 8) + upgradePassTestPersistEvery = 2 + l = uncleanAttach(t, s, f) + waitReached(t, reached) + closed := make(chan error, 1) + go func() { closed <- l.Close() }() // the stop, not a release, lets the held compare go + select { + case err := <-closed: + if err != nil { + t.Fatal(err) + } + case <-time.After(10 * time.Second): + t.Fatal("Close waited for the rest of the pass") + } + upgradeCompareTestHook = nil + } else { + l = uncleanAttach(t, s, f) // waits for the pass: it ends + if st := l.Stats().UpgradePass; st.State != "done" { + t.Fatalf("setup: pass %+v, want done", st) + } + if err := l.shadow.rec.Flush(); err != nil { + t.Fatal(err) + } + } + _, epoch := s.ChunkStateMarker() + before, err := readUpgradePassCursor(chunkRecordDir(path), epoch) + if err != nil || before.Next == 0 { + t.Fatalf("setup: cursor %+v %v", before, err) + } + if err := os.WriteFile(filepath.Join(chunkRecordDir(path), chunkRecordPageName(0)), []byte("damaged"), 0o644); err != nil { + t.Fatal(err) + } + crashStore(t, s) + r := reopenRecovered(t, path) + r.HoldExtentDrainUntilChunkLayer() + reached, release := blockPassAt(t, 1) + l2 := uncleanAttach(t, r, f) + waitReached(t, reached) // chunk 0 compared, chunk 1 held: nothing persisted by the pass yet + if cur, err := readUpgradePassCursor(chunkRecordDir(path), epoch); err != nil || cur.Next != 0 { + t.Fatalf("the cursor on disk while the rewound pass runs: %+v %v; want rewound to chunk 0 before any compare", cur, err) + } + release() + waitPass(t, l2, "the rewound pass never ended", func(st UpgradePassStatus) bool { return st.State == "done" }) + for c := uint64(0); c < l2.numChunks; c++ { + if k := shadowKind(l2, c); k == chunkkernel.Unknown { + t.Fatalf("chunk %d stayed unknown after the rebuilt page: the pass did not rewind (cursor was %d)", c, before.Next) + } + } + if st := l2.Stats().UpgradePass; st.State != "done" { + t.Fatalf("pass after the rewind: %+v", st) + } + if _, err := l2.Cut(ctTimeout(t)); err != nil { + t.Fatalf("cut after the rewound pass: %v", err) + } + }) + } +} + +// A chunk written between the pass's read and its hash is superseded by the +// write: not hashed (the record refuses the stale version), not counted as +// compared, reported as superseded. It is dirty, so the next cut publishes it +// as any written chunk; after a crash before that cut it is still a +// candidate, and the cut after the restart publishes it. +func TestV11AChunkWrittenDuringItsCompareGoesToTheNextCut(t *testing.T) { + for _, crash := range []bool{false, true} { + t.Run(map[bool]string{false: "next cut", true: "crash before the next cut"}[crash], func(t *testing.T) { + withV11Format(t) + s, path, f := uncleanUpgradeStore(t) + const hot = 2 + var once sync.Once + upgradeAfterReadTestHook = func(idx uint64) { + if idx == hot { + once.Do(func() { + if _, err := s.Write(uint32(hot*ctChunkBlocks), makeBlock(ctBlockSize, 0xEE)); err != nil { + t.Error(err) + } + }) + } + } + t.Cleanup(func() { upgradeAfterReadTestHook = nil }) + l := uncleanAttach(t, s, f) + upgradeAfterReadTestHook = nil + st := l.Stats().UpgradePass + if st.State != "done" || st.Compared != l.numChunks-1 || st.Superseded != 1 { + t.Fatalf("pass %+v; want done, every chunk but the written one compared, one superseded", st) + } + if k := shadowKind(l, hot); k != chunkkernel.Unknown { + t.Fatalf("the chunk written during its compare is %s, want still unknown (not hashed with a stale version)", k) + } + if crash { + if _, err := s.Sync(); err != nil { + t.Fatal(err) + } + crashStore(t, s) + r := reopenRecovered(t, path) + r.HoldExtentDrainUntilChunkLayer() + l = uncleanAttach(t, r, f) + } + before := f.stats().cas + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if k := shadowKind(l, hot); k == chunkkernel.Unknown { + t.Fatal("the next cut left the written chunk unknown") + } + if f.stats().cas == before { + t.Fatal("the next cut published nothing: the written chunk was not a candidate") + } + img := f.imageOf(t, f.stats().head) + if got := img[hot*ctChunkBytes : hot*ctChunkBytes+ctBlockSize]; !bytes.Equal(got, makeBlock(ctBlockSize, 0xEE)) { + t.Fatalf("the published chunk %d starts %x, want the bytes written during its compare", hot, got[:8]) + } + }) + } +} + +// The pass's cursor file is the storage package's own: no production code +// outside it names the file (status reports the pass; nothing else reads the +// cursor). The control: the scan finds the name in the pass's own file. +func TestUpgradePassCursorIsReadOnlyByStorage(t *testing.T) { + root := filepath.Join("..", "..") + var found []string + ownSeen := false + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + if n := d.Name(); n == ".git" || n == "vendor" || n == "testdata" { + return filepath.SkipDir + } + return nil + } + if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") { + return nil + } + b, err := os.ReadFile(p) + if err != nil { + return err + } + if !strings.Contains(string(b), "pass-cursor") { + return nil + } + if filepath.ToSlash(filepath.Dir(p)) == filepath.ToSlash(filepath.Join(root, "core", "storage")) { + ownSeen = true + return nil + } + found = append(found, p) + return nil + }) + if err != nil { + t.Fatal(err) + } + if !ownSeen { + t.Fatal("control: the scan did not find the cursor file's name in the storage package") + } + if len(found) > 0 { + t.Fatalf("production code outside storage names the pass cursor file: %v", found) + } +} + +// An unseeded upgrade writes the pass's first cursor before the store's +// marker: a crash right after the upgrade, before the pass persisted anything +// (here, the first attach ran no pass at all), restarts with that cursor, so +// the pass runs, cuts are refused until it ends, and no chunk stays unknown. +func TestV11ACrashBeforeThePassFirstPersistsStillRunsThePass(t *testing.T) { + withV11Format(t) + s, path, f := uncleanUpgradeStore(t) + upgradePassTestDisabled = true // the attach after the upgrade starts no pass: as if killed at once + l := uncleanAttach(t, s, f) + upgradePassTestDisabled = false + if k := shadowKind(l, 1); k != chunkkernel.Unknown { + t.Fatalf("setup: chunk 1 after the unseeded upgrade is %s, want U", k) + } + crashStore(t, s) + r := reopenRecovered(t, path) + r.HoldExtentDrainUntilChunkLayer() + reached, release := blockPassAt(t, 3) + l2 := uncleanAttach(t, r, f) + if st := l2.Stats().UpgradePass; st.State != "running" { + t.Fatalf("the attach after the restart: pass %+v, want running (the cursor written before the marker)", st) + } + waitReached(t, reached) + var refusal *ErrUpgradePassInProgress + if _, err := l2.Cut(ctTimeout(t)); !errors.As(err, &refusal) { + t.Fatalf("a cut after the restart, during the pass: %v, want in_progress", err) + } + release() + waitPass(t, l2, "the pass after the restart never ended", func(st UpgradePassStatus) bool { return st.State == "done" }) + for c := uint64(0); c < l2.numChunks; c++ { + if k := shadowKind(l2, c); k == chunkkernel.Unknown { + t.Fatalf("chunk %d still unknown after the restart's pass", c) + } + } +} + +// A page rebuilt at open is republished (the record's due loop) only after +// the pass's rewind is durable: otherwise a crash between the two leaves the +// page valid on disk under the old cursor, the next open sees no damage, and +// the chunks the page had stay unknown with no pass to compare them. +func TestV11ARebuiltPageIsNotRepublishedBeforeTheRewindIsDurable(t *testing.T) { + withV11Format(t) + s, path, f := uncleanUpgradeStore(t) + l := uncleanAttach(t, s, f) // waits for the pass: it ends + if err := l.shadow.rec.Flush(); err != nil { + t.Fatal(err) + } + page := filepath.Join(chunkRecordDir(path), chunkRecordPageName(0)) + if err := os.WriteFile(page, []byte("damaged"), 0o644); err != nil { + t.Fatal(err) + } + crashStore(t, s) + r := reopenRecovered(t, path) + r.HoldExtentDrainUntilChunkLayer() + var dueStarted, rewound bool + dueLoopStartTestHook = func() { dueStarted = true } + upgradeRewindTestHook = func() { + rewound = true + if dueStarted { + t.Error("the record's due loop started before the rewind was durable") + } + if r.chunk.Load() != nil { + t.Error("the layer's hooks were attached (writes publish pages) before the rewind was durable") + } + if b, err := os.ReadFile(page); err != nil || string(b) != "damaged" { + t.Errorf("the rebuilt page was rewritten before the rewind was durable: %v", err) + } + } + t.Cleanup(func() { dueLoopStartTestHook, upgradeRewindTestHook = nil, nil }) + l2 := uncleanAttach(t, r, f) + if !rewound || !dueStarted { + t.Fatalf("setup: rewound %v, due loop started %v; want both", rewound, dueStarted) + } + for c := uint64(0); c < l2.numChunks; c++ { + if k := shadowKind(l2, c); k == chunkkernel.Unknown { + t.Fatalf("chunk %d stayed unknown after the rebuilt page", c) + } + } +} diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 9cce39b345..c3479c2795 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -318,6 +318,12 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published | | `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | | `Volumes[].Chunk.Stats.CutSeq` | uint64 | successful cuts of this layer so far (in-process); the latest cut's identity | +| `Volumes[].Chunk.Stats.UpgradePass` | object | the upgrade compare pass after a v1.0 store's upgrade (v1.1): none, seeded, running, done or failed | +| `Volumes[].Chunk.Stats.UpgradePass.State` | string | none, seeded, running, done or failed; carried across a stop (read the status, never the pass's cursor file) | +| `Volumes[].Chunk.Stats.UpgradePass.Compared` | uint64 | chunks the pass found unknown and compared, across stops | +| `Volumes[].Chunk.Stats.UpgradePass.Total` | uint64 | chunks the pass walks | +| `Volumes[].Chunk.Stats.UpgradePass.Superseded` | uint64 | Superseded counts chunks written during their own compare (in this process): not hashed, not counted as compared; each is dirty and the next cut takes it as any written chunk. | +| `Volumes[].Chunk.Stats.UpgradePass.Outcome` | string | why a failed pass stopped; while the pass has not ended a cut, snapshot, backup or sealing detach is refused with code in_progress (omitted when empty) | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | | `Volumes[].Chunk.Stats.COWSpillCap` | int64 | COWSpillCap is the last cut's side-file cap in bytes, read once per cut; COWSpillCapReason is why it is 0, when the free space made it so: no_room_to_cut (half the free space is within the 1 GiB reserve) or free_space_unreadable (the free space could not be read). |