storage: the attach runs the upgrade compare pass; sealing requests wait

After a v1.0 store's upgrade with no clean-stop seed every whole local
chunk is unknown. The v1.1 attach now runs the compare pass (resuming at a
persisted cursor, or starting when the record holds an unknown chunk); it
compares each unknown chunk with HEAD by the cut's own transitions. A stop
never waits for it: the pages and cursor of the work done are persisted
and the next attach resumes. Until it ends, a cut, snapshot, backup or
sealing detach is refused typed (ErrUpgradePassInProgress, HTTP code
in_progress) and the pass runs at full rate. Holder status reports
Stats.UpgradePass {State, Compared, Total, Outcome}.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
pingqiuandClaude Opus 5.5 committed 2026-12-01 17:15:16 -08:00
1 parent ccb9215f75
commit 812fcffb35
8 files changed
+436

No files matched your search

@@ -268,6 +268,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)
@@ -302,7 +307,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):
@@ -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)
}
}
}
+22
View File
@@ -232,6 +232,14 @@ 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
// testShadowCheck receives each barrier's misses and extra record
// candidates; set, it also makes the barrier collect the extras.
testShadowCheck func(miss, extra []uint64)
@@ -378,7 +386,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)
@@ -406,6 +417,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig)
l.wg.Add(1)
go l.writeDueLoop(l.ctx, sh)
}
if err := l.startUpgradePass(upgradedNow); err != nil {
s.chunk.CompareAndSwap(hooks, nil)
l.cancel()
return nil, fmt.Errorf("storage: chunk layer attach: upgrade compare pass: %w", err)
}
// Every later drain reaches OnExtentWrite: release a held drain.
s.drainHeld.Store(false)
if s.flusher != nil {
@@ -1128,6 +1144,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()
@@ -2383,6 +2404,7 @@ func (l *chunkLayerImpl) Stats() chunkLayerStats {
current := *l.currentCut
out.CurrentCut = &current
}
out.UpgradePass = l.upgradePassStatusLocked()
out.Hydration.WorkerLimit = l.cfg.HydrationWorkers
out.Hydration.QueueDepth = l.cfg.HydrationQueueDepth
for _, f := range l.hydration {
+1
View File
@@ -525,6 +525,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
@@ -164,6 +164,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 {
@@ -0,0 +1,183 @@
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
Compared uint64
Total uint64
Outcome string `json:",omitempty"`
}
// 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.
func (l *chunkLayerImpl) startUpgradePass(upgradedNow bool) error {
sh := l.shadow
if sh == nil || !sh.v11 {
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
}
if os.IsNotExist(statErr) && !sh.anyUnknown() {
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
}
l.stMu.Lock()
l.pass = p
l.stMu.Unlock()
if p.Admit() == nil {
return nil // ended before this attach
}
if d := upgradePassTestInterval; d > 0 {
p.interval = d
}
if n := upgradePassTestPersistEvery; n > 0 {
p.persistEvery = n
}
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)
}
}()
return nil
}
// 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 (
upgradePassTestInterval time.Duration
upgradePassTestPersistEvery uint64
upgradeCompareTestHook 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(_ 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(idx)
}
data, err := l.readChunk(idx)
if err != nil {
return false, err
}
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)
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}
switch {
case l.passErr != nil:
st.State, st.Outcome = "failed", l.passErr.Error()
case done:
st.State = "done"
}
return st
}
// anyUnknown reports whether the record holds an unknown chunk (O(S), once
// at attach).
func (s *chunkRecordShadow) anyUnknown() bool {
s.rec.mu.Lock()
defer s.rec.mu.Unlock()
for _, code := range s.rec.kinds {
if kindByCode[code] == chunkkernel.Unknown {
return true
}
}
return false
}
@@ -0,0 +1,198 @@
package storage
import (
"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)
}
}
}
func slowPass(t *testing.T) {
t.Helper()
upgradePassTestInterval, upgradePassTestPersistEvery = 40*time.Millisecond, 2
t.Cleanup(func() { upgradePassTestInterval, upgradePassTestPersistEvery, upgradeCompareTestHook = 0, 0, nil })
}
// 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)
slowPass(t)
s, path, f := uncleanUpgradeStore(t)
l := uncleanAttach(t, s, f)
if st := waitPass(t, l, "the pass never ran", func(st UpgradePassStatus) bool { return st.State == "running" && st.Compared >= 4 }); st.Total != l.numChunks {
t.Fatalf("running status %+v, want total %d", st, l.numChunks)
}
start := time.Now()
if err := l.Close(); err != nil {
t.Fatal(err)
}
if took := time.Since(start); took > 2*time.Second {
t.Fatalf("Close waited %s for the pass", took)
}
_, epoch := s.ChunkStateMarker()
cur, err := readUpgradePassCursor(chunkRecordDir(path), epoch)
if err != nil || cur.Next == 0 || cur.Next >= l.numChunks || cur.Compared != cur.Next {
t.Fatalf("the cursor at the stop: %+v %v; want mid-pass, every chunk below it compared", cur, err)
}
crashStore(t, s)
r := reopenRecovered(t, path)
r.HoldExtentDrainUntilChunkLayer()
var mu sync.Mutex
var again []uint64
upgradeCompareTestHook = func(idx uint64) {
mu.Lock()
again = append(again, idx)
mu.Unlock()
}
upgradePassTestInterval = 0
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)
slowPass(t)
s, _, f := uncleanUpgradeStore(t)
l := uncleanAttach(t, s, f)
waitPass(t, l, "the pass never ran", func(st UpgradePassStatus) bool { return st.State == "running" })
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")
}
upgradePassTestInterval = 0
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)
}
}
// 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)
}
}
+4
View File
@@ -314,6 +314,10 @@ 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.State` | string | the upgrade compare pass after a v1.0 store's upgrade (v1.1 format): `none` (no pass needed), `seeded` (a clean-stop seed made every chunk known at the upgrade), `running`, `done`, or `failed`; carried across a stop by the pass's own cursor (read the status, never the 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.Outcome` | string | why a `failed` pass stopped; absent otherwise. While the pass has not ended, a cut, snapshot, backup or sealing detach is refused with code `in_progress` (retryable) |
| `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). |