From 45f7d71607749a6baaf833f9670ab5e618eac150 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 05:54:04 -0800 Subject: [PATCH 01/51] storage: the chunk record keeps each chunk's state in one byte The record runtime held every chunk's kernel state as the kernel's string kind (16 B a chunk); it now keeps the one-byte page code it already writes (r2.735) and converts at its boundary through a fixed table. The kernel's types and table are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_record_runtime.go | 38 ++++++++++++++----- .../core/storage/chunk_record_shadow.go | 7 ++-- .../core/storage/chunk_record_shadow_test.go | 2 +- 3 files changed, 33 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/storage/chunk_record_runtime.go b/seaweed-block/core/storage/chunk_record_runtime.go index 2515bcc789..f473f5d144 100644 --- a/seaweed-block/core/storage/chunk_record_runtime.go +++ b/seaweed-block/core/storage/chunk_record_runtime.go @@ -26,6 +26,11 @@ func chunkRecordStateCode(k chunkkernel.Kind) (uint8, error) { return 0, fmt.Errorf("storage: chunk record: no code for kernel state %q", k) } +// kindByCode is chunkRecordKind for a code the runtime itself stored (every +// one valid): the record keeps each chunk's state as its one-byte page code, +// not the kernel's string (16 B a chunk; r2.735). +var kindByCode = [6]chunkkernel.Kind{1: chunkkernel.Absent, 2: chunkkernel.Partial, 3: chunkkernel.Unknown, 4: chunkkernel.HashUnpublished, 5: chunkkernel.HashPublished} + func chunkRecordKind(code uint8) (chunkkernel.Kind, error) { switch code { case 1: @@ -124,7 +129,7 @@ type chunkRecordRuntime struct { pubMu sync.Mutex // see PAGES ARE PUBLISHED IN ORDER mu sync.Mutex - kinds []chunkkernel.Kind + kinds []uint8 // each chunk's state as its page code (kindByCode) hashes [][32]byte // per segment valid []uint64 // the position its page was last written valid through @@ -148,10 +153,17 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u } r := &chunkRecordRuntime{dir: dir, chunks: chunks, epoch: epoch, appliedPos: appliedPos, maxEntries: 1000, maxAge: time.Minute, - kinds: append([]chunkkernel.Kind(nil), kinds...), hashes: append([][32]byte(nil), hashes...), + kinds: make([]uint8, chunks), hashes: append([][32]byte(nil), hashes...), valid: append([]uint64(nil), valid...), dirtyVer: make([]uint64, segs), writtenVer: make([]uint64, segs), since: make([]uint64, segs), changes: make([]int, segs), firstDirty: make([]time.Time, segs), headerG: headerG} + for c, k := range kinds { + code, err := chunkRecordStateCode(k) + if err != nil { + return nil, err + } + r.kinds[c] = code + } now := time.Now() for seg, changed := range changedAtOpen { if changed { @@ -165,7 +177,7 @@ func newChunkRecordRuntime(dir string, chunks, epoch uint64, appliedPos func() u func (r *chunkRecordRuntime) Kind(chunk uint64) chunkkernel.Kind { r.mu.Lock() defer r.mu.Unlock() - return r.kinds[chunk] + return kindByCode[r.kinds[chunk]] } // Apply runs one kernel event on a chunk. hash is the evidence the event @@ -190,17 +202,18 @@ func (r *chunkRecordRuntime) ApplyIf(chunk uint64, ev chunkkernel.Event, argFor r.mu.Unlock() return chunkkernel.None, false, fmt.Errorf("storage: chunk record: chunk %d out of range", chunk) } - if cond != nil && !cond(r.kinds[chunk]) { + if cond != nil && !cond(kindByCode[r.kinds[chunk]]) { r.mu.Unlock() return chunkkernel.None, false, nil } - eff, err = r.applyLocked(chunk, ev, argFor(r.kinds[chunk]), hash) + eff, err = r.applyLocked(chunk, ev, argFor(kindByCode[r.kinds[chunk]]), hash) return eff, err == nil, err } // applyLocked steps the kernel with r.mu held and releases it. func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg chunkkernel.Arg, hash *[32]byte) (chunkkernel.Effect, error) { - res, eff, err := chunkkernel.Step(chunkkernel.State{Kind: r.kinds[chunk]}, ev, arg) + cur := kindByCode[r.kinds[chunk]] + res, eff, err := chunkkernel.Step(chunkkernel.State{Kind: cur}, ev, arg) if err != nil { r.mu.Unlock() return chunkkernel.None, err @@ -232,13 +245,18 @@ func (r *chunkRecordRuntime) applyLocked(chunk uint64, ev chunkkernel.Event, arg if r.unmarked == nil { r.unmarked = map[uint64]chunkkernel.Kind{} } - r.unmarked[chunk] = r.kinds[chunk] // A or P + r.unmarked[chunk] = cur // A or P } else if held && res.State.Kind == chunkkernel.Absent { delete(r.unmarked, chunk) // an evict: nothing local is claimed } } - if res.State.Kind != r.kinds[chunk] || newHash != r.hashes[chunk] { - r.kinds[chunk], r.hashes[chunk] = res.State.Kind, newHash + if res.State.Kind != cur || newHash != r.hashes[chunk] { + code, err := chunkRecordStateCode(res.State.Kind) + if err != nil { + r.mu.Unlock() + return chunkkernel.None, err + } + r.kinds[chunk], r.hashes[chunk] = code, newHash if r.dirtyVer[seg] == r.writtenVer[seg] { r.since[seg], r.firstDirty[seg] = r.appliedPos(), time.Now() } @@ -401,7 +419,7 @@ func (r *chunkRecordRuntime) writeSegmentLocked(seg uint64) error { p := &chunkRecordPage{Segment: seg, ValidThrough: pos, Entries: make([]chunkRecordEntry, chunkRecordSegmentLen(r.chunks, seg))} for i := range p.Entries { c := seg*chunkRecordSegment + uint64(i) - k, h := r.kinds[c], r.hashes[c] + k, h := kindByCode[r.kinds[c]], r.hashes[c] if held, ok := r.unmarked[c]; ok { // a fill not yet durable in the store's bits if held == chunkkernel.Absent && k != chunkkernel.HashPublished { held = chunkkernel.Partial // written since the fill: some blocks are local diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index 1ac74dd4ff..5e61affbb3 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -346,7 +346,7 @@ func (s *chunkRecordShadow) openedChangedLocked(chunk uint64, k chunkkernel.Kind // again; the record remembers it (an exemption the checker names). The // caller (the barrier check's skip) holds the record's lock. func (s *chunkRecordShadow) openedCleanRecLocked(chunk uint64) bool { - return s.v11 && s.version != nil && s.version(chunk) == 0 && s.rec.kinds[chunk] == chunkkernel.HashPublished + return s.v11 && s.version != nil && s.version(chunk) == 0 && kindByCode[s.rec.kinds[chunk]] == chunkkernel.HashPublished } // scratchHoldsLocked reports whether a P chunk's scratch-cut exemption @@ -367,14 +367,15 @@ var errShadowMiss = errors.New("storage: chunk record shadow: an engine candidat func (s *chunkRecordShadow) check(engine map[uint64]bool, skip func(uint64) bool, withExtra, proceeds bool) (miss, extra []uint64) { s.rec.mu.Lock() for idx := range engine { - if !isRecordCandidate(s.rec.kinds[idx]) && !skip(idx) { + if !isRecordCandidate(kindByCode[s.rec.kinds[idx]]) && !skip(idx) { miss = append(miss, idx) } } if withExtra || (shadowFindings != nil && proceeds) { // tests only: O(chunks), never at a production barrier s.mu.Lock() s.fullScans++ - for idx, k := range s.rec.kinds { + for idx, code := range s.rec.kinds { + k := kindByCode[code] if isRecordCandidate(k) && !engine[uint64(idx)] && !s.scratchHoldsLocked(uint64(idx), k) && !s.openedChangedLocked(uint64(idx), k) { extra = append(extra, uint64(idx)) } diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 2a390ee920..1591befd2f 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -426,7 +426,7 @@ func TestShadowRecoverChangesOnlyTheRecoveredChunks(t *testing.T) { // Forget the write in the record only, as if its event were lost: only // Recover's event can bring the chunk back. l.shadow.rec.mu.Lock() - l.shadow.rec.kinds[1] = chunkkernel.HashPublished + l.shadow.rec.kinds[1] = 5 // HP l.shadow.rec.mu.Unlock() if _, err := s.Recover(); err != nil { t.Fatal(err) From d100675112e97a837cb491080688271c56b0c515 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 06:52:04 -0800 Subject: [PATCH 02/51] storage: the ref table, the holder's fixed-width copy of HEAD's references refTable keeps one entry a chunk behind Get/Set/Delete/FillSegment/Len: a canonical layout reference as its full SHA-256 and an interned owner prefix (the key derived), any other shape kept whole, so it is exact for every remote. At the 1 TiB chunk count it holds 34 B/chunk, against the flat map's ~287 with its keys. Not wired yet. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_ref_table.go | 126 ++++++++++++++++++ .../core/storage/chunk_ref_table_test.go | 86 ++++++++++++ 2 files changed, 212 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_ref_table.go create mode 100644 seaweed-block/core/storage/chunk_ref_table_test.go diff --git a/seaweed-block/core/storage/chunk_ref_table.go b/seaweed-block/core/storage/chunk_ref_table.go new file mode 100644 index 0000000000..4839603102 --- /dev/null +++ b/seaweed-block/core/storage/chunk_ref_table.go @@ -0,0 +1,126 @@ +package storage + +import ( + "encoding/hex" + "strconv" +) + +// refTable is the holder's copy of the references HEAD names, one entry a +// chunk, in fixed width (r2.777): what the flat chunk map held, without a +// per-entry key string or map overhead. It sits behind a narrow interface +// (Get, Set, Delete, FillSegment, Len) so that a paged form can replace it +// without touching its readers. +// +// An entry is the chunk's identity as the layout names it: its index (the +// position), its full SHA-256, and its owner. A canonical reference's key is +// "-" (the layout remote's form: the prefix +// is "layout:::"), so the entry keeps only the SHA-256 and +// an index into the interned owner prefixes, and Get derives the key. A +// reference of any other shape (another remote's opaque key, an encoding +// other than "full") is kept whole in a side map, so nothing is lost: the +// table is exact for every remote, and compact for the layout's. +type refTable struct { + sums [][32]byte + prefix []uint16 // 0: absent; prefixOther: kept in other; else 1 + index into prefixes + prefixes []string + byPrefix map[string]uint16 + other map[uint64]chunkRef + n int +} + +const prefixOther = ^uint16(0) + +func newRefTable(chunks uint64) *refTable { + return &refTable{sums: make([][32]byte, chunks), prefix: make([]uint16, chunks), byPrefix: map[string]uint16{}} +} + +// Len is the number of chunks the table names. +func (t *refTable) Len() int { return t.n } + +// Get returns the reference HEAD names at chunk index i. +func (t *refTable) Get(i uint64) (chunkRef, bool) { + if i >= uint64(len(t.prefix)) { + return chunkRef{}, false + } + switch p := t.prefix[i]; p { + case 0: + return chunkRef{}, false + case prefixOther: + r, ok := t.other[i] + return r, ok + default: + sum := t.sums[i] + return chunkRef{Key: t.prefixes[p-1] + strconv.FormatUint(i, 10) + "-" + hex.EncodeToString(sum[:]), SHA256: sum, Encoding: "full"}, true + } +} + +// canonicalSplit returns the owner prefix of a reference at index i whose key +// is "-" with the "full" encoding, or false. +func canonicalSplit(i uint64, ref chunkRef) (string, bool) { + if ref.Encoding != "full" { + return "", false + } + suffix := strconv.FormatUint(i, 10) + "-" + hex.EncodeToString(ref.SHA256[:]) + if len(ref.Key) <= len(suffix) || ref.Key[len(ref.Key)-len(suffix):] != suffix { + return "", false + } + return ref.Key[:len(ref.Key)-len(suffix)], true +} + +// Set names ref at chunk index i. +func (t *refTable) Set(i uint64, ref chunkRef) { + if i >= uint64(len(t.prefix)) { + return + } + if t.prefix[i] == 0 { + t.n++ + } + if p, ok := canonicalSplit(i, ref); ok && len(t.prefixes) < int(prefixOther)-1 { + id, seen := t.byPrefix[p] + if !seen { + t.prefixes = append(t.prefixes, p) + id = uint16(len(t.prefixes)) + t.byPrefix[p] = id + } + if t.prefix[i] == prefixOther { + delete(t.other, i) + } + t.prefix[i], t.sums[i] = id, ref.SHA256 + return + } + if t.other == nil { + t.other = map[uint64]chunkRef{} + } + t.prefix[i], t.sums[i] = prefixOther, [32]byte{} + t.other[i] = ref +} + +// Delete makes chunk index i named by nothing (HEAD reads it as zeros). +func (t *refTable) Delete(i uint64) { + if i >= uint64(len(t.prefix)) || t.prefix[i] == 0 { + return + } + if t.prefix[i] == prefixOther { + delete(t.other, i) + } + t.prefix[i], t.sums[i] = 0, [32]byte{} + t.n-- +} + +// FillSegment names every reference one segment of HEAD holds (the attach's +// fill, one segment at a time). +func (t *refTable) FillSegment(refs map[uint64]chunkRef) { + for i, r := range refs { + t.Set(i, r) + } +} + +// each calls f for every named chunk, in index order. +func (t *refTable) each(f func(i uint64, ref chunkRef)) { + for i := range t.prefix { + if t.prefix[i] != 0 { + r, _ := t.Get(uint64(i)) + f(uint64(i), r) + } + } +} diff --git a/seaweed-block/core/storage/chunk_ref_table_test.go b/seaweed-block/core/storage/chunk_ref_table_test.go new file mode 100644 index 0000000000..c46cc620b5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_ref_table_test.go @@ -0,0 +1,86 @@ +package storage + +import ( + "crypto/sha256" + "fmt" + "reflect" + "runtime" + "testing" +) + +// The ref table returns exactly the reference it was given, for canonical +// layout keys (kept as owner prefix + SHA-256, key derived) and for any other +// shape (kept whole): another remote's key, another encoding, a key whose +// suffix names another index or hash. Delete and Len follow. +func TestRefTableIsExactForEveryReferenceShape(t *testing.T) { + tab := newRefTable(16) + sum := func(s string) [32]byte { return sha256.Sum256([]byte(s)) } + canon := func(owner string, i uint64, s [32]byte) chunkRef { + return chunkRef{Key: fmt.Sprintf("layout:%s:309016fbc5b31531e1e7c44585851c7d:%d-%x", owner, i, s), SHA256: s, Encoding: "full"} + } + refs := map[uint64]chunkRef{ + 0: canon("v1", 0, sum("a")), + 1: canon("v1", 1, sum("b")), + 2: canon("src", 2, sum("c")), // a restore source: a second owner prefix + 3: {Key: "chunks/e1/c3/opaque-1", SHA256: sum("d"), Encoding: "full"}, + 4: {Key: canon("v1", 4, sum("e")).Key, SHA256: sum("e"), Encoding: "zstd"}, + 5: canon("v1", 6, sum("f")), // the key names another index + 6: {Key: canon("v1", 6, sum("g")).Key, SHA256: sum("h"), Encoding: "full"}, // the key names another hash + 15: canon("v1", 15, sum("z")), + } + for i, r := range refs { + tab.Set(i, r) + } + if tab.Len() != len(refs) { + t.Fatalf("Len %d, want %d", tab.Len(), len(refs)) + } + for i := uint64(0); i < 16; i++ { + got, ok := tab.Get(i) + want, named := refs[i] + if ok != named || !reflect.DeepEqual(got, want) { + t.Fatalf("chunk %d: %+v %v, want %+v %v", i, got, ok, want, named) + } + } + if len(tab.prefixes) != 2 || len(tab.other) != 4 { + t.Fatalf("%d owner prefixes, %d whole refs; want 2 and 4 (only the non-canonical kept whole)", len(tab.prefixes), len(tab.other)) + } + // Replacing a whole ref by a canonical one, and the reverse, keeps one entry. + tab.Set(3, canon("v1", 3, sum("d2"))) + tab.Set(0, chunkRef{Key: "opaque", SHA256: sum("x"), Encoding: "full"}) + if r, _ := tab.Get(3); r != canon("v1", 3, sum("d2")) { + t.Fatalf("chunk 3 after a canonical replacement: %+v", r) + } + if r, _ := tab.Get(0); r.Key != "opaque" { + t.Fatalf("chunk 0 after an opaque replacement: %+v", r) + } + if tab.Len() != len(refs) || len(tab.other) != 4 { + t.Fatalf("after replacements: Len %d, %d whole refs; want %d and 4", tab.Len(), len(tab.other), len(refs)) + } + tab.Delete(15) + tab.Delete(3) + tab.Delete(9) // never named + if _, ok := tab.Get(15); ok || tab.Len() != len(refs)-2 { + t.Fatalf("after deletes: Len %d", tab.Len()) + } + if _, ok := tab.Get(99); ok { + t.Fatal("an index beyond the volume is named") + } +} + +// The table's held heap at the 1 TiB chunk count with canonical keys: at +// most 40 B per chunk (32 B SHA-256 + a 2 B owner index, and the slices' +// headers), against the flat map's ~287 B with its keys. +func TestRefTableSpaceAt1TiBChunkCount(t *testing.T) { + const chunks = 262144 + head := fullHead(chunks, "v1") + before := heapNow() + tab := newRefTable(chunks) + tab.FillSegment(head.Chunks) + per := float64(int64(heapNow())-int64(before)) / chunks + runtime.KeepAlive(tab) + runtime.KeepAlive(head) // the source map lives across both readings + t.Logf("ref table: %.1f B/chunk at %d chunks (%d owner prefix)", per, chunks, len(tab.prefixes)) + if per > 40 || tab.Len() != chunks || len(tab.other) != 0 { + t.Fatalf("ref table %.1f B/chunk, %d named, %d whole; want <= 40, %d, 0", per, tab.Len(), len(tab.other), chunks) + } +} From ce490fdb39719a94a99abfcc3e8388ef6b6dace8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 08:44:25 -0800 Subject: [PATCH 03/51] storage: the ref table's fill replaces its segment and refuses out of range; its space test owns its source FillSegment(first, end, refs) makes a segment's range exactly refs, so a re-fill drops a reference the new HEAD no longer names; Set and FillSegment refuse an index beyond the volume or outside the segment (errRefBeyondVolume) and change nothing, so an attach refuses a malformed HEAD. The space test drops its source HEAD before the reading, so a table that aliased its keys would be charged for them (control: a shallow flat-map copy measures ~287 B/chunk by the same method). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_ref_table.go | 47 +++++++-- .../core/storage/chunk_ref_table_test.go | 95 ++++++++++++++++--- 2 files changed, 120 insertions(+), 22 deletions(-) diff --git a/seaweed-block/core/storage/chunk_ref_table.go b/seaweed-block/core/storage/chunk_ref_table.go index 4839603102..4139e79e54 100644 --- a/seaweed-block/core/storage/chunk_ref_table.go +++ b/seaweed-block/core/storage/chunk_ref_table.go @@ -2,9 +2,15 @@ package storage import ( "encoding/hex" + "errors" + "fmt" "strconv" ) +// errRefBeyondVolume refuses a reference at an index the volume does not +// have: a malformed HEAD, which the attach refuses, never trims. +var errRefBeyondVolume = errors.New("storage: chunk reference beyond the volume") + // refTable is the holder's copy of the references HEAD names, one entry a // chunk, in fixed width (r2.777): what the flat chunk map held, without a // per-entry key string or map overhead. It sits behind a narrow interface @@ -67,10 +73,10 @@ func canonicalSplit(i uint64, ref chunkRef) (string, bool) { return ref.Key[:len(ref.Key)-len(suffix)], true } -// Set names ref at chunk index i. -func (t *refTable) Set(i uint64, ref chunkRef) { +// Set names ref at chunk index i; an index beyond the volume is refused. +func (t *refTable) Set(i uint64, ref chunkRef) error { if i >= uint64(len(t.prefix)) { - return + return fmt.Errorf("%w: index %d, the volume has %d chunks", errRefBeyondVolume, i, len(t.prefix)) } if t.prefix[i] == 0 { t.n++ @@ -86,13 +92,14 @@ func (t *refTable) Set(i uint64, ref chunkRef) { delete(t.other, i) } t.prefix[i], t.sums[i] = id, ref.SHA256 - return + return nil } if t.other == nil { t.other = map[uint64]chunkRef{} } t.prefix[i], t.sums[i] = prefixOther, [32]byte{} t.other[i] = ref + return nil } // Delete makes chunk index i named by nothing (HEAD reads it as zeros). @@ -107,15 +114,35 @@ func (t *refTable) Delete(i uint64) { t.n-- } -// FillSegment names every reference one segment of HEAD holds (the attach's -// fill, one segment at a time). -func (t *refTable) FillSegment(refs map[uint64]chunkRef) { - for i, r := range refs { - t.Set(i, r) +// FillSegment makes the chunk range [first, end) of one segment of HEAD +// exactly refs (the attach's fill, one segment at a time): an index of the +// range refs does not name reads as zeros afterwards, even if an earlier fill +// named it (a re-fill never keeps a reference HEAD dropped). A reference +// outside the range, or a range beyond the volume, is refused and changes +// nothing. O(end - first). +func (t *refTable) FillSegment(first, end uint64, refs map[uint64]chunkRef) error { + if first > end || end > uint64(len(t.prefix)) { + return fmt.Errorf("%w: segment range [%d, %d), the volume has %d chunks", errRefBeyondVolume, first, end, len(t.prefix)) } + for i := range refs { + if i < first || i >= end { + return fmt.Errorf("%w: index %d is outside its segment's range [%d, %d)", errRefBeyondVolume, i, first, end) + } + } + for i := first; i < end; i++ { + if r, ok := refs[i]; ok { + if err := t.Set(i, r); err != nil { + return err + } + } else { + t.Delete(i) + } + } + return nil } -// each calls f for every named chunk, in index order. +// each calls f for every named chunk, in index order: O(S), the whole +// volume (for the paths that need the whole set, never for a lookup). func (t *refTable) each(f func(i uint64, ref chunkRef)) { for i := range t.prefix { if t.prefix[i] != 0 { diff --git a/seaweed-block/core/storage/chunk_ref_table_test.go b/seaweed-block/core/storage/chunk_ref_table_test.go index c46cc620b5..64fe613abf 100644 --- a/seaweed-block/core/storage/chunk_ref_table_test.go +++ b/seaweed-block/core/storage/chunk_ref_table_test.go @@ -2,6 +2,7 @@ package storage import ( "crypto/sha256" + "errors" "fmt" "reflect" "runtime" @@ -24,12 +25,14 @@ func TestRefTableIsExactForEveryReferenceShape(t *testing.T) { 2: canon("src", 2, sum("c")), // a restore source: a second owner prefix 3: {Key: "chunks/e1/c3/opaque-1", SHA256: sum("d"), Encoding: "full"}, 4: {Key: canon("v1", 4, sum("e")).Key, SHA256: sum("e"), Encoding: "zstd"}, - 5: canon("v1", 6, sum("f")), // the key names another index + 5: canon("v1", 6, sum("f")), // the key names another index 6: {Key: canon("v1", 6, sum("g")).Key, SHA256: sum("h"), Encoding: "full"}, // the key names another hash 15: canon("v1", 15, sum("z")), } for i, r := range refs { - tab.Set(i, r) + if err := tab.Set(i, r); err != nil { + t.Fatal(err) + } } if tab.Len() != len(refs) { t.Fatalf("Len %d, want %d", tab.Len(), len(refs)) @@ -45,8 +48,8 @@ func TestRefTableIsExactForEveryReferenceShape(t *testing.T) { t.Fatalf("%d owner prefixes, %d whole refs; want 2 and 4 (only the non-canonical kept whole)", len(tab.prefixes), len(tab.other)) } // Replacing a whole ref by a canonical one, and the reverse, keeps one entry. - tab.Set(3, canon("v1", 3, sum("d2"))) - tab.Set(0, chunkRef{Key: "opaque", SHA256: sum("x"), Encoding: "full"}) + _ = tab.Set(3, canon("v1", 3, sum("d2"))) + _ = tab.Set(0, chunkRef{Key: "opaque", SHA256: sum("x"), Encoding: "full"}) if r, _ := tab.Get(3); r != canon("v1", 3, sum("d2")) { t.Fatalf("chunk 3 after a canonical replacement: %+v", r) } @@ -67,20 +70,88 @@ func TestRefTableIsExactForEveryReferenceShape(t *testing.T) { } } +// heldAfterSourceDropped is the heap per chunk that build's result holds +// once the HEAD it was built from is gone: the source is allocated after the +// first reading and dropped before the second, so whatever the result still +// references of it (an aliased key string) is charged to the result. +func heldAfterSourceDropped(chunks uint64, build func(chunkHead) any) float64 { + before := heapNow() + src := fullHead(chunks, "v1") + held := build(src) + src = chunkHead{} + per := float64(int64(heapNow())-int64(before)) / float64(chunks) + runtime.KeepAlive(held) + return per +} + // The table's held heap at the 1 TiB chunk count with canonical keys: at // most 40 B per chunk (32 B SHA-256 + a 2 B owner index, and the slices' -// headers), against the flat map's ~287 B with its keys. +// headers), against the flat map's ~287 B with its keys. The source HEAD is +// dropped before the reading, so a table that aliased its keys instead of +// holding its own bytes would be charged for them: the control, a shallow +// copy of the flat map (which shares the source's key strings), measures +// well above the bound by the same method. func TestRefTableSpaceAt1TiBChunkCount(t *testing.T) { const chunks = 262144 - head := fullHead(chunks, "v1") - before := heapNow() - tab := newRefTable(chunks) - tab.FillSegment(head.Chunks) - per := float64(int64(heapNow())-int64(before)) / chunks - runtime.KeepAlive(tab) - runtime.KeepAlive(head) // the source map lives across both readings + var tab *refTable + per := heldAfterSourceDropped(chunks, func(h chunkHead) any { + tab = newRefTable(chunks) + if err := tab.FillSegment(0, chunks, h.Chunks); err != nil { + t.Fatal(err) + } + return tab + }) t.Logf("ref table: %.1f B/chunk at %d chunks (%d owner prefix)", per, chunks, len(tab.prefixes)) if per > 40 || tab.Len() != chunks || len(tab.other) != 0 { t.Fatalf("ref table %.1f B/chunk, %d named, %d whole; want <= 40, %d, 0", per, tab.Len(), len(tab.other), chunks) } + aliased := heldAfterSourceDropped(chunks, func(h chunkHead) any { return copyHead(h) }) + t.Logf("control, a shallow flat-map copy aliasing the source's keys: %.1f B/chunk", aliased) + if aliased <= 40 { + t.Fatalf("the control measured %.1f B/chunk: the method would not see aliased keys", aliased) + } +} + +// A segment's fill makes its range exactly the refs given: a re-fill drops a +// reference the new HEAD no longer names (it reads as zeros), and leaves the +// other segments alone. A reference beyond the volume, outside the segment's +// range, or a range beyond the volume is refused and changes nothing. +func TestRefTableFillReplacesItsSegmentAndRefusesOutOfRange(t *testing.T) { + tab := newRefTable(20) + ref := func(i uint64, tag string) chunkRef { + s := sha256.Sum256([]byte(tag)) + return chunkRef{Key: fmt.Sprintf("layout:v1:0011:%d-%x", i, s), SHA256: s, Encoding: "full"} + } + if err := tab.FillSegment(0, 10, map[uint64]chunkRef{1: ref(1, "a"), 2: ref(2, "b")}); err != nil { + t.Fatal(err) + } + if err := tab.FillSegment(10, 20, map[uint64]chunkRef{15: ref(15, "c")}); err != nil { + t.Fatal(err) + } + // HEAD now names chunk 1 again and no longer chunk 2. + if err := tab.FillSegment(0, 10, map[uint64]chunkRef{1: ref(1, "a2")}); err != nil { + t.Fatal(err) + } + if _, ok := tab.Get(2); ok { + t.Fatal("a re-fill kept a reference the new HEAD dropped") + } + if r, _ := tab.Get(1); r != ref(1, "a2") { + t.Fatalf("chunk 1 after the re-fill: %+v", r) + } + if r, ok := tab.Get(15); !ok || r != ref(15, "c") || tab.Len() != 2 { + t.Fatalf("another segment changed: %+v %v, Len %d", r, ok, tab.Len()) + } + before := tab.Len() + for name, err := range map[string]error{ + "Set beyond the volume": tab.Set(20, ref(20, "x")), + "a ref outside its segment": tab.FillSegment(0, 10, map[uint64]chunkRef{1: ref(1, "a3"), 12: ref(12, "y")}), + "a segment beyond the volume": tab.FillSegment(10, 30, nil), + } { + if !errors.Is(err, errRefBeyondVolume) { + t.Fatalf("%s: %v; want errRefBeyondVolume", name, err) + } + } + if r, _ := tab.Get(1); r != ref(1, "a2") || tab.Len() != before { + t.Fatal("a refused fill changed the table") + } } From 5e97bae96f663e81f80f4f14d18bf795d5a130a8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 08:57:35 -0800 Subject: [PATCH 04/51] storage: every single-chunk reader of HEAD goes through headRef; the chunkRefs interface The thirteen readers that looked one chunk's reference up in the flat HEAD map (the COW window, hydration, clean marks, fill, evict, the shadow's seed) now ask headRef/headChunk, the one place that still reads the map by index, so the map behind it can be replaced. chunkRefs declares the ref table's narrow interface (Get, Set, Delete, FillSegment, Len). No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_cut_cow.go | 4 ++-- .../core/storage/chunk_hydrate_all.go | 6 ++--- seaweed-block/core/storage/chunk_hydration.go | 4 ++-- seaweed-block/core/storage/chunk_layer.go | 24 +++++++++++++++---- .../core/storage/chunk_record_shadow.go | 2 +- seaweed-block/core/storage/chunk_ref_table.go | 14 +++++++++++ 6 files changed, 42 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/storage/chunk_cut_cow.go b/seaweed-block/core/storage/chunk_cut_cow.go index f5ff20f4a7..aab6a70b9b 100644 --- a/seaweed-block/core/storage/chunk_cut_cow.go +++ b/seaweed-block/core/storage/chunk_cut_cow.go @@ -505,7 +505,7 @@ func (l *chunkLayerImpl) readLocalBlock(lba uint64, w *cutCOWWindow, dst []byte) idx := l.chunkOf(lba) l.stMu.Lock() absent := l.absent[idx] && !l.localBlocks[lba] - _, inHead := l.head.Chunks[idx] + _, inHead := l.headRef(idx) l.stMu.Unlock() if absent && inHead { return nil, false, nil @@ -536,7 +536,7 @@ func (l *chunkLayerImpl) fillMissing(ctx context.Context, base map[uint64]chunkR var gen, version uint64 if fill { l.stMu.Lock() - fill = l.absent[idx] && l.head.Chunks[idx] == ref + fill = l.absent[idx] && l.headChunk(idx) == ref gen, version = l.absentGen[idx], l.chunkVersion(idx) l.stMu.Unlock() } diff --git a/seaweed-block/core/storage/chunk_hydrate_all.go b/seaweed-block/core/storage/chunk_hydrate_all.go index 17fae0e4b3..f58d0b259a 100644 --- a/seaweed-block/core/storage/chunk_hydrate_all.go +++ b/seaweed-block/core/storage/chunk_hydrate_all.go @@ -143,7 +143,7 @@ func (l *chunkLayerImpl) HydrateAllAt(ctx context.Context, bytesPerSecond int64) return quit(errChunkLayerClosed) } l.stMu.Lock() - changed := l.absentGen[f.idx] != f.gen || l.head.Chunks[f.idx] != f.ref + changed := l.absentGen[f.idx] != f.gen || l.headChunk(f.idx) != f.ref ferr := f.err l.stMu.Unlock() switch { @@ -175,7 +175,7 @@ func (l *chunkLayerImpl) startWalkerFill(lba uint64, release func()) (*chunkHydr release() return nil, errChunkLayerClosed } - ref, named := l.head.Chunks[idx] + ref, named := l.headRef(idx) if !l.absent[idx] || l.localBlocks[lba] || !named { release() return nil, nil @@ -238,7 +238,7 @@ func (l *chunkLayerImpl) absentHydratable() int { // hydratableBlockLocked returns a block of chunk idx that is not written // locally, if HEAD names the chunk. Caller holds stMu. func (l *chunkLayerImpl) hydratableBlockLocked(idx uint64) (uint64, bool) { - if _, named := l.head.Chunks[idx]; !named { + if _, named := l.headRef(idx); !named { return 0, false } first := idx * l.chunkBlocks diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index 510ed56ed2..582a5642df 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -63,7 +63,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Unlock() return nil, nil } - ref, ok := l.head.Chunks[idx] + ref, ok := l.headRef(idx) if !ok { l.stMu.Unlock() return make([]byte, l.blockSize), nil @@ -114,7 +114,7 @@ func (l *chunkLayerImpl) OnReadMissContext(ctx context.Context, lba uint64) ([]b l.stMu.Lock() f.waiters-- closed := l.closed - changed := l.absentGen[idx] != f.gen || l.head.Chunks[idx] != f.ref + changed := l.absentGen[idx] != f.gen || l.headChunk(idx) != f.ref err = f.err if !closed && !changed && errors.Is(err, ErrChunkHydrationPending) { l.stats.Hydration.WaitRefusals++ diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 05cc317428..96412dd9d5 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -441,6 +441,22 @@ func copyHeadEach(h chunkHead, each func(uint64)) chunkHead { func (l *chunkLayerImpl) chunkOf(lba uint64) uint64 { return lba / l.chunkBlocks } +// headRef is the reference HEAD names at chunk idx, and whether it names one: +// every single-chunk reader of HEAD goes through it (and headChunk), so the +// flat map behind it can be replaced (V4-B PR 4). Caller holds stMu. +func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) { + r, ok := l.head.Chunks[idx] + return r, ok +} + +// headChunk is headRef's reference alone: the zero reference when HEAD names +// none (a comparison with a named reference then fails, as a map read's +// zero value did). Caller holds stMu. +func (l *chunkLayerImpl) headChunk(idx uint64) chunkRef { + r, _ := l.headRef(idx) + return r +} + // chunkHasLocalLocked reports whether any block of an absent chunk was // written locally since it became absent. Caller holds stMu. func (l *chunkLayerImpl) chunkHasLocalLocked(idx uint64) bool { @@ -646,7 +662,7 @@ type filledMark struct { // Caller holds stMu. func (l *chunkLayerImpl) knownEqualToHeadLocked(idx uint64) bool { m, ok := l.filledClean[idx] - return ok && !l.own[idx] && l.chunkVersion(idx) == m.version && l.head.Chunks[idx] == m.ref + return ok && !l.own[idx] && l.chunkVersion(idx) == m.version && l.headChunk(idx) == m.ref } // chunkVersion is chunk idx's mutation count. @@ -720,7 +736,7 @@ func (l *chunkLayerImpl) installFill(idx, gen, version uint64, ref chunkRef, dat // current reports whether this fill still belongs to the chunk's present // absence: same generation, same HEAD ref. Caller holds stMu. current := func() bool { - return l.absent[idx] && l.absentGen[idx] == gen && l.head.Chunks[idx] == ref + return l.absent[idx] && l.absentGen[idx] == gen && l.headChunk(idx) == ref } first := idx * l.chunkBlocks for i := uint64(0); i < l.chunkBlocks; i++ { @@ -948,7 +964,7 @@ func (l *chunkLayerImpl) shadowExemptLocked(idx uint64) bool { } v, ok := l.shadow.recoverKilled(idx) m, marked := l.filledClean[idx] - return ok && marked && v == l.chunkVersion(idx) && l.head.Chunks[idx] == m.ref + return ok && marked && v == l.chunkVersion(idx) && l.headChunk(idx) == m.ref } // shadowCommit is the record's E6: the HEAD just installed names every @@ -2280,7 +2296,7 @@ func (l *chunkLayerImpl) EvictChunk(idx uint64) error { l.stMu.Unlock() return fmt.Errorf("%w: chunk %d is dirty since HEAD or HEAD is unknown", errChunkEvictRefused, idx) } - if _, inHead := l.head.Chunks[idx]; !inHead { + if _, inHead := l.headRef(idx); !inHead { l.stMu.Unlock() return nil // ZERO in HEAD: nothing to make absent } diff --git a/seaweed-block/core/storage/chunk_record_shadow.go b/seaweed-block/core/storage/chunk_record_shadow.go index 5e61affbb3..bcf7cec89b 100644 --- a/seaweed-block/core/storage/chunk_record_shadow.go +++ b/seaweed-block/core/storage/chunk_record_shadow.go @@ -127,7 +127,7 @@ func newChunkRecordShadow(l *chunkLayerImpl) (*chunkRecordShadow, error) { default: kinds[i] = chunkkernel.HashPublished hashes[i] = zero - if ref, ok := l.head.Chunks[i]; ok { + if ref, ok := l.headRef(i); ok { hashes[i] = ref.SHA256 } } diff --git a/seaweed-block/core/storage/chunk_ref_table.go b/seaweed-block/core/storage/chunk_ref_table.go index 4139e79e54..b796e33efb 100644 --- a/seaweed-block/core/storage/chunk_ref_table.go +++ b/seaweed-block/core/storage/chunk_ref_table.go @@ -36,6 +36,20 @@ type refTable struct { const prefixOther = ^uint16(0) +// chunkRefs is the narrow interface the layer reads HEAD's references +// through (r2.777): a paged form can replace refTable behind it without +// touching a reader. Get, Set and Delete are O(1); FillSegment is O(its +// range); Len is O(1). +type chunkRefs interface { + Get(i uint64) (chunkRef, bool) + Set(i uint64, ref chunkRef) error + Delete(i uint64) + FillSegment(first, end uint64, refs map[uint64]chunkRef) error + Len() int +} + +var _ chunkRefs = (*refTable)(nil) + func newRefTable(chunks uint64) *refTable { return &refTable{sums: make([][32]byte, chunks), prefix: make([]uint16, chunks), byPrefix: map[string]uint16{}} } From 7e5f1fce7d07c8ddd971a4c3d67b3585b7d956b7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 09:41:21 -0800 Subject: [PATCH 05/51] storage: every HEAD install goes through setHeadLocked; the ref table mirrors it under test The nine places that installed the layer's HEAD (attach, settlement, adoption, a fence, a cut's finish) go through setHeadLocked, and a cut's finish through setHeadChangedLocked, which updates only its changed chunks. On the v1.1 format they keep the ref table HEAD's when refTableMirror is on; it stays off until the flat map goes (both at once only add memory). TestRefTableMirrorsHeadThroughTheLayer runs the cut, settle, hydration and fill suites on v1.1 with the table on and every table read checked against the map (a mutant that drops a cut's changes fails it). Tests that wrote the layer's HEAD directly now install it. Co-Authored-By: Claude Opus 5.5 --- .../chunk_fresh_readback_candidates_test.go | 2 +- seaweed-block/core/storage/chunk_head_belt.go | 2 +- .../chunk_hydration_concurrency_test.go | 4 +- seaweed-block/core/storage/chunk_layer.go | 79 ++++++++++++++++--- .../storage/chunk_record_shadow_main_test.go | 10 +++ seaweed-block/core/storage/chunk_ref_table.go | 14 ++++ .../storage/chunk_ref_table_mirror_test.go | 43 ++++++++++ 7 files changed, 139 insertions(+), 15 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_ref_table_mirror_test.go diff --git a/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go index 370e53c949..6bbbb68b6e 100644 --- a/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go +++ b/seaweed-block/core/storage/chunk_fresh_readback_candidates_test.go @@ -229,7 +229,7 @@ func TestACleanFillRecordEndsWithItsHeadRef(t *testing.T) { ref.Key += "-replaced" ref.SHA256[0] ^= 0xFF h.Chunks[idx] = ref - l.head = h + l.setHeadLocked(h) l.stMu.Unlock() if !l.captureCandidates()[idx] { t.Fatal("a chunk whose HEAD ref changed after its fill is not a candidate") diff --git a/seaweed-block/core/storage/chunk_head_belt.go b/seaweed-block/core/storage/chunk_head_belt.go index 45663e5189..86058240f7 100644 --- a/seaweed-block/core/storage/chunk_head_belt.go +++ b/seaweed-block/core/storage/chunk_head_belt.go @@ -196,7 +196,7 @@ func (l *chunkLayerImpl) fencePublication(cur chunkHead) { if cur.Gen != 0 { // Preserve the existing hydration identity invalidation. This is not // settlement of our cut: remoteLSN and captured-map dirt stay unchanged. - l.head = copyHead(cur) + l.setHeadLocked(copyHead(cur)) } l.stMu.Unlock() log.Printf("ALARM: chunk publisher fenced: local epoch=%d holder=%q, observed gen=%d epoch=%d holder=%q; keeping local data and intents", l.cfg.Epoch, l.cfg.Holder, cur.Gen, cur.Epoch, cur.Holder) diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index 575e90b035..71caa18817 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -327,7 +327,7 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { t.Fatal("old Get not entered") } layer.stMu.Lock() - layer.head.Chunks[2] = newRef + setHeadChunkForTest(layer, 2, newRef) layer.absentGen[2]++ layer.stMu.Unlock() newer := startHydrationRead(t, s, ctx, 8) @@ -368,7 +368,7 @@ func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) { t.Fatal("old Get not entered") } layer.stMu.Lock() - layer.head.Chunks[2] = newRef + setHeadChunkForTest(layer, 2, newRef) layer.absentGen[2]++ layer.stMu.Unlock() newer := startHydrationRead(t, s, ctx, 8) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 96412dd9d5..1d9b832939 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -140,9 +140,12 @@ type chunkLayerImpl struct { stMu sync.Mutex closed bool head chunkHead - pending *chunkHead // a proposal whose CAS outcome is unresolved - fenced bool - detached *chunkCutResult // set by a successful Detach + // refs is the ref table of head on the v1.1 format (nil on v1.0): headRef + // reads it; setHeadLocked and setHeadChangedLocked keep it head's. + refs *refTable + pending *chunkHead // a proposal whose CAS outcome is unresolved + fenced bool + detached *chunkCutResult // set by a successful Detach // pendingDetach says the unresolved proposal in pending is a Detach; // pendingCut is its cut result, installed as the detach result if the // re-read shows it applied. @@ -333,7 +336,7 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.cancel() return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err) } - l.head = copyHeadEach(head, l.attachProgress.add) // reports as it copies + l.setHeadLocked(copyHeadEach(head, l.attachProgress.add)) // reports as it copies l.remoteLSN = head.RemoteLSN // A HEAD that already belongs to a newer epoch or a competing holder is // never used as this holder's publication guard. @@ -445,10 +448,61 @@ func (l *chunkLayerImpl) chunkOf(lba uint64) uint64 { return lba / l.chunkBlocks // every single-chunk reader of HEAD goes through it (and headChunk), so the // flat map behind it can be replaced (V4-B PR 4). Caller holds stMu. func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) { + if l.refs != nil { + r, ok := l.refs.Get(idx) + if check := refTableCheck; check != nil { + if m, mok := l.head.Chunks[idx]; mok != ok || m != r { + check(fmt.Sprintf("chunk %d: the ref table names %+v (%v), the flat map %+v (%v)", idx, r, ok, m, mok)) + } + } + return r, ok + } r, ok := l.head.Chunks[idx] return r, ok } +// refTableCheck, set by tests only, compares every ref-table read with the +// flat map while both exist (a finding fails the package's tests). +var refTableCheck func(string) + +// refTableMirror keeps the ref table beside the flat map on the v1.1 format. +// Off until the flat map goes (V4-B PR 4 commit 4): both at once only add +// memory. Tests turn it on to check the table against the map through the +// layer's every HEAD install (TestRefTableMirrorsHeadThroughTheLayer). +var refTableMirror = false + +// setHeadLocked installs h as the layer's HEAD and, on the v1.1 format, +// refills the ref table from it whole (attach, settlement, adoption: the +// rare paths). Caller holds stMu or owns the layer. +func (l *chunkLayerImpl) setHeadLocked(h chunkHead) { + l.head = h + if !chunkV11Format || !refTableMirror { + l.refs = nil + return + } + if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks { + l.refs = newRefTable(l.numChunks) + } + l.refs.fillAll(h.Chunks) +} + +// setHeadChangedLocked installs h after a commit whose changed chunks are +// changed: the ref table takes only those (O(C)), the rest is unchanged. +func (l *chunkLayerImpl) setHeadChangedLocked(h chunkHead, changed []uint64) { + if l.refs == nil { + l.setHeadLocked(h) + return + } + l.head = h + for _, idx := range changed { + if r, ok := h.Chunks[idx]; ok { + _ = l.refs.Set(idx, r) + } else { + l.refs.Delete(idx) + } + } +} + // headChunk is headRef's reference alone: the zero reference when HEAD names // none (a comparison with a named reference then fails, as a map read's // zero value did). Caller holds stMu. @@ -1548,7 +1602,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if l.supersededBy(cur) { l.stMu.Lock() l.fenced = true - l.head = copyHead(cur) + l.setHeadLocked(copyHead(cur)) l.stMu.Unlock() l.abortCOW(errChunkLayerFenced) return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) @@ -1651,7 +1705,8 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle switch { case sameProposal(cur, *pending): l.noteSettled(l.head, cur) - l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + l.setHeadLocked(copyHead(cur)) + l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) cut.Head = copyHead(cur) l.detached = &cut @@ -1660,7 +1715,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle return detachApplied, r, nil case l.supersededBy(cur): l.fenced = true - l.head = copyHead(cur) + l.setHeadLocked(copyHead(cur)) return detachFenced, chunkCutResult{}, nil default: if l.adoptHeadLocked(cur) != nil { @@ -1887,7 +1942,8 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { switch { case sameProposal(cur, *pending): l.noteSettled(l.head, cur) - l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + l.setHeadLocked(copyHead(cur)) + l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) if wasDetach { cut.Head = copyHead(cur) @@ -1896,7 +1952,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { } case l.supersededBy(cur): l.fenced = true - l.head = copyHead(cur) + l.setHeadLocked(copyHead(cur)) return errChunkLayerFenced default: // HEAD moved past the unresolved CAS's base without it: that CAS @@ -1921,7 +1977,7 @@ var errChunkForeignRoot = fmt.Errorf("%w: HEAD moved to a chunk root this holder // (errChunkForeignRoot). Caller holds stMu. func (l *chunkLayerImpl) adoptHeadLocked(cur chunkHead) error { same := sameChunkRoot(l.head.Chunks, cur.Chunks) - l.head = copyHead(cur) + l.setHeadLocked(copyHead(cur)) if !same { l.fenced = true log.Printf("level=WARN storage: chunk layer fenced: HEAD gen %d moved the chunk root without superseding holder %q epoch %d", cur.Gen, l.cfg.Holder, l.cfg.Epoch) @@ -2226,7 +2282,8 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n l.stMu.Lock() defer l.stMu.Unlock() l.noteSettled(l.head, head) - l.head, l.remoteLSN, l.pending = copyHead(head), h, nil + l.setHeadChangedLocked(copyHead(head), changed) + l.remoteLSN, l.pending = h, nil l.pendingCaptured, l.pendingChanges = nil, nil l.reusable = nil l.inflight = map[uint64]bool{} diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go index e8bbbd3493..80a196dbe8 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -18,6 +18,16 @@ func TestMain(m *testing.M) { found = append(found, msg) mu.Unlock() } + // While the flat map and the ref table both exist (V4-B PR 4), every + // ref-table read is checked against the map: a difference is a finding. + if os.Getenv("REF_TABLE_MIRROR_CHILD") == "1" { + refTableMirror = true + } + refTableCheck = func(msg string) { + mu.Lock() + found = append(found, "ref table: "+msg) + mu.Unlock() + } // CHUNK_RECORD_V11=1 runs the whole package on the draft v1.1 store // format (the lab build's mode); it selects a format, it turns no check // off. diff --git a/seaweed-block/core/storage/chunk_ref_table.go b/seaweed-block/core/storage/chunk_ref_table.go index b796e33efb..08eb7240bd 100644 --- a/seaweed-block/core/storage/chunk_ref_table.go +++ b/seaweed-block/core/storage/chunk_ref_table.go @@ -155,6 +155,20 @@ func (t *refTable) FillSegment(first, end uint64, refs map[uint64]chunkRef) erro return nil } +// fillAll makes the table exactly m (a whole HEAD's references): O(S). +// References beyond the volume are dropped here; the attach refuses them +// before (a malformed HEAD). +func (t *refTable) fillAll(m map[uint64]chunkRef) { + for i := range t.prefix { + if t.prefix[i] != 0 { + t.Delete(uint64(i)) + } + } + for i, r := range m { + _ = t.Set(i, r) + } +} + // each calls f for every named chunk, in index order: O(S), the whole // volume (for the paths that need the whole set, never for a lookup). func (t *refTable) each(f func(i uint64, ref chunkRef)) { diff --git a/seaweed-block/core/storage/chunk_ref_table_mirror_test.go b/seaweed-block/core/storage/chunk_ref_table_mirror_test.go new file mode 100644 index 0000000000..7f36d0b55e --- /dev/null +++ b/seaweed-block/core/storage/chunk_ref_table_mirror_test.go @@ -0,0 +1,43 @@ +package storage + +import ( + "os" + "os/exec" + "strings" + "testing" +) + +// setHeadChunkForTest replaces one chunk's reference in the layer's HEAD, as +// a HEAD install would (the ref table follows when it is kept). +func setHeadChunkForTest(l *chunkLayerImpl, idx uint64, ref chunkRef) { + l.head.Chunks[idx] = ref + if l.refs != nil { + _ = l.refs.Set(idx, ref) + } +} + +// The ref table, kept beside the flat map, names exactly what the map names +// through every HEAD install the layer makes: attach, cuts (the changed +// chunks only), settlement, adoption, a fence. The package's cut, settle, +// hydration and fill suites run on the v1.1 format with the table kept and +// every table read checked against the map (refTableCheck: a difference is +// a finding, which fails the run). A child run, so the table's switch and +// the format are this test's alone. +func TestRefTableMirrorsHeadThroughTheLayer(t *testing.T) { + if os.Getenv("REF_TABLE_MIRROR_CHILD") == "1" { + t.Skip("the child run itself") + } + if testing.Short() { + t.Skip("runs the cut suites in a child process") + } + cmd := exec.Command(os.Args[0], "-test.run", "Cut|Settle|Pending|Hydrat|Fill|Evict|Adopt|Detach|Fresh|Clean|V11|Shadow|RefTable", "-test.count=1") + cmd.Env = append(os.Environ(), "REF_TABLE_MIRROR_CHILD=1", "CHUNK_RECORD_V11=1") + out, _ := cmd.CombinedOutput() + if strings.Contains(string(out), "ref table: ") { + i := strings.Index(string(out), "ref table: ") + t.Fatalf("the ref table and the flat map differ: %s", string(out)[i:min(len(out), i+400)]) + } + if !strings.Contains(string(out), "ok") && !strings.Contains(string(out), "FAIL") { + t.Fatalf("the child run reported nothing: %s", out) + } +} From de256fc5aac9aa1f985bad37344137e683f077fc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 10:27:12 -0800 Subject: [PATCH 06/51] chunkstore: EachSegment reads HEAD one segment at a time; one segment walker LayoutRemote.EachSegment is GetHead one segment at a time: HEAD's identity, and each segment its root names delivered with its shard's range and references, only one held at a time (for the streaming attach, V4-B PR 4 commit 4). The manifest read and the attach's bounded read now share one walker (walkSegments: the root and each segment, counted, each fetch bounded within an attach). Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/layout_each_segment_test.go | 51 +++++++ .../core/frontend/chunkstore/layout_remote.go | 127 +++++++++++------- 2 files changed, 128 insertions(+), 50 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/layout_each_segment_test.go diff --git a/seaweed-block/core/frontend/chunkstore/layout_each_segment_test.go b/seaweed-block/core/frontend/chunkstore/layout_each_segment_test.go new file mode 100644 index 0000000000..42112dbb48 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/layout_each_segment_test.go @@ -0,0 +1,51 @@ +package chunkstore + +import ( + "reflect" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// EachSegment is GetHead one segment at a time: one call per segment HEAD's +// root names, each with its shard's range and exactly the references GetHead +// lists in that range, and HEAD's identity with no chunk listed. It reads the +// root once and each segment once, and holds one segment at a time. +func TestEachSegmentIsGetHeadOneSegmentAtATime(t *testing.T) { + ctx, _, r, _ := threeShardVolume(t) + full, err := r.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + type call struct{ first, end uint64 } + var calls []call + got := map[uint64]storage.ChunkRef{} + octx, count := storage.ObserveCutWork(ctx) + id, err := r.EachSegment(octx, func(first, end uint64, refs map[uint64]storage.ChunkRef) error { + calls = append(calls, call{first, end}) + for i, ref := range refs { + if i < first || i >= end { + t.Errorf("chunk %d delivered outside its range [%d, %d)", i, first, end) + } + got[i] = ref + } + return nil + }) + if err != nil { + t.Fatal(err) + } + want := []call{{0, layout.ShardSize}, {layout.ShardSize, 2 * layout.ShardSize}, {2 * layout.ShardSize, 3 * layout.ShardSize}} + if !reflect.DeepEqual(calls, want) { + t.Fatalf("calls %v, want %v", calls, want) + } + if !reflect.DeepEqual(got, full.Chunks) { + t.Fatalf("EachSegment's references differ from GetHead's: %d vs %d", len(got), len(full.Chunks)) + } + if id.Chunks != nil || id.Gen != full.Gen || id.Epoch != full.Epoch || id.Holder != full.Holder || id.RemoteLSN != full.RemoteLSN { + t.Fatalf("identity %+v, GetHead %+v", id, full) + } + if roots, segs := count(storage.CountRootReads), count(storage.CountSegmentReads); roots != 1 || segs != 3 { + t.Fatalf("%d root reads, %d segment reads; want 1 and 3", roots, segs) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 5d56d17433..70fa4906d6 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -412,30 +412,94 @@ func (l *LayoutRemote) headIdentityLocked(ctx context.Context) (layout.Head, sto // no bound on the read as a whole (the segment count grows with the volume). func (l *LayoutRemote) manifest(ctx context.Context, rn layout.RootName) (map[uint64]layout.Ref, error) { defer storage.MeasureCutWork(ctx, storage.CutManifestRead)() - if af, ok := storage.AttachFetchFrom(ctx); ok { - m, err := boundedManifest(ctx, l.r, rn, af) - if err != nil { - return nil, layoutRemoteErr(err) + m := map[uint64]layout.Ref{} + err := walkSegments(ctx, l.r, rn, func(_ uint64, seg map[uint64]layout.Ref) error { + for idx, ref := range seg { + m[idx] = ref } - return m, nil - } - img, err := l.r.Open(ctx, rn) + return nil + }) if err != nil { return nil, layoutRemoteErr(err) } + return m, nil +} + +// walkSegments reads root rn and then each segment it names, one at a time, +// handing each to fn (its shard and its references by chunk index): the +// root and every segment, each read counted; within an attach each fetch is +// bounded by the attach's fetch bound and the completed references are +// reported. Only one segment is held at a time. +func walkSegments(ctx context.Context, r *layout.Reader, rn layout.RootName, fn func(shard uint64, seg map[uint64]layout.Ref) error) error { + af, attach := storage.AttachFetchFrom(ctx) + fetchCtx := func() (context.Context, context.CancelFunc) { + if attach && af.Bound > 0 { + return context.WithTimeout(ctx, af.Bound) + } + return context.WithCancel(ctx) + } + c, cancel := fetchCtx() + img, err := r.Open(c, rn) + cancel() + if err != nil { + return err + } storage.CountCutWork(ctx, storage.CountRootReads, 1) - m := map[uint64]layout.Ref{} for _, sh := range img.Shards() { - seg, _, err := img.Segment(ctx, sh) + c, cancel := fetchCtx() + seg, _, err := img.Segment(c, sh) + cancel() if err != nil { - return nil, layoutRemoteErr(err) + return err } storage.CountCutWork(ctx, storage.CountSegmentReads, 1) - for idx, ref := range seg.Chunks { - m[idx] = ref + if err := fn(sh, seg.Chunks); err != nil { + return err + } + if attach && af.Done != nil { + af.Done(uint64(len(seg.Chunks))) } } - return m, nil + return nil +} + +// boundedManifest is the whole manifest of rn read under an attach's fetch +// bound af (walkSegments within that attach). +func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, af storage.AttachFetch) (map[uint64]layout.Ref, error) { + m := map[uint64]layout.Ref{} + err := walkSegments(storage.WithAttachFetch(ctx, af), r, rn, func(_ uint64, seg map[uint64]layout.Ref) error { + for idx, ref := range seg { + m[idx] = ref + } + return nil + }) + return m, err +} + +// EachSegment is GetHead one segment at a time (storage.ChunkSegmentReader): +// HEAD's identity as GetHead returns it (no chunk listed), and fn called for +// each segment HEAD's root names with its chunk range [first, end) (a +// shard's range: the caller clamps it to its volume) and its references. +// Only one segment is held at a time. A HEAD with no image calls fn never. +func (l *LayoutRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]storage.ChunkRef) error) (storage.ChunkHead, error) { + l.mu.Lock() + defer l.mu.Unlock() + h, out, err := l.headIdentityLocked(ctx) + out.Chunks = nil + if err != nil || h.Current == nil { + return out, err + } + err = walkSegments(ctx, l.r, *h.Current, func(shard uint64, seg map[uint64]layout.Ref) error { + refs := make(map[uint64]storage.ChunkRef, len(seg)) + for idx, ref := range seg { + refs[idx] = storage.ChunkRef{Key: LayoutKey(ref), SHA256: ref.Chunk.Hash, Encoding: "full"} + } + return fn(shard*layout.ShardSize, (shard+1)*layout.ShardSize, refs) + }) + if err != nil { + return storage.ChunkHead{}, layoutRemoteErr(err) + } + return out, nil } // attachFetchBound bounds one object call of an attach's manifest read by @@ -447,43 +511,6 @@ func attachFetchBound(ctx context.Context) (context.Context, context.CancelFunc) return context.WithCancel(ctx) } -// boundedManifest reads root rn's chunk map one fetch at a time: the root, -// then each segment, every fetch under af.Bound on its own, reporting each -// completed segment's entries to af.Done. A fetch that cannot finish within -// its bound fails the read (never a partial map). -func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, af storage.AttachFetch) (map[uint64]layout.Ref, error) { - fetchCtx := func() (context.Context, context.CancelFunc) { - if af.Bound > 0 { - return context.WithTimeout(ctx, af.Bound) - } - return context.WithCancel(ctx) - } - c, cancel := fetchCtx() - img, err := r.Open(c, rn) - cancel() - if err != nil { - return nil, err - } - storage.CountCutWork(ctx, storage.CountRootReads, 1) - m := map[uint64]layout.Ref{} - for _, sh := range img.Shards() { - c, cancel := fetchCtx() - seg, _, err := img.Segment(c, sh) - cancel() - if err != nil { - return nil, err - } - storage.CountCutWork(ctx, storage.CountSegmentReads, 1) - for idx, ref := range seg.Chunks { - m[idx] = ref - } - if af.Done != nil { - af.Done(uint64(len(seg.Chunks))) - } - } - return m, nil -} - // CASHead commits next as this cut's session: the root of next's chunk // map, position next.RemoteLSN, detached when next is, and the pending // snapshot name. It uses the engine view from before this session's Begin. From 73ec053d7f226e31e69772699af5c92200939392 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:10:57 -0800 Subject: [PATCH 07/51] build: the draft v1.1 store format gets its own tag, apart from the cap lift swblock_v11_format now turns on the draft v1.1 store format; swblock_lab_bigvol lifts only the create cap and the headroom refusal. A build with the format tag names itself in its revision ("LAB BUILD(swblock_v11_format)"), so the image refusal keys on it as it does on the cap tag, and the CI tag check refuses either tag outside its allowlist. CI tests each tag alone and both together. Co-Authored-By: Claude Opus 5.5 --- .../.github/scripts/lab-tag-check-test.sh | 11 ++++- .../.github/scripts/lab-tag-check.sh | 48 +++++++++++-------- .../core/storage/chunk_v11_format_draft.go | 9 ++++ .../core/storage/chunk_v11_format_lab.go | 8 ---- .../core/storage/chunk_v11_format_release.go | 2 +- .../core/storage/chunk_v11_format_tag_test.go | 18 +++++++ seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/internal/buildinfo/buildinfo.go | 21 +++++--- .../internal/buildinfo/buildinfo_lab_test.go | 12 +++++ .../internal/buildinfo/v11_format_draft.go | 7 +++ .../internal/buildinfo/v11_format_release.go | 7 +++ seaweed-block/scripts/refuse-lab-binary.sh | 3 +- 12 files changed, 108 insertions(+), 40 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_v11_format_draft.go delete mode 100644 seaweed-block/core/storage/chunk_v11_format_lab.go create mode 100644 seaweed-block/core/storage/chunk_v11_format_tag_test.go create mode 100644 seaweed-block/internal/buildinfo/v11_format_draft.go create mode 100644 seaweed-block/internal/buildinfo/v11_format_release.go diff --git a/seaweed-block/.github/scripts/lab-tag-check-test.sh b/seaweed-block/.github/scripts/lab-tag-check-test.sh index c919d8e201..e153192057 100644 --- a/seaweed-block/.github/scripts/lab-tag-check-test.sh +++ b/seaweed-block/.github/scripts/lab-tag-check-test.sh @@ -37,6 +37,10 @@ expect() { # expect pass|fail name } repo; expect pass "the real recipes, unchanged" repo; printf '// %s\npackage x\n' "$tag" > "$r/core/x/x.go"; gadd; expect fail "the tag outside the allowlist" +repo; printf '// swblock_v11_format +package x +' > "$r/core/x/x.go"; gadd; expect fail "the format tag outside the allowlist" +repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags swblock_v11_format -o /out/blockvolume#"; expect fail "the format tag in a real recipe's build" repo; edit "$sw" "s#go build -o /out/blockvolume#go build -tags $tag -o /out/blockvolume#"; expect fail "the tag in a real recipe's build" repo; edit "$sw" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the real recipe's RUN guard deleted, its comment kept" repo; edit "$csi" '/^RUN bash scripts\/refuse-lab-binary.sh/d'; expect fail "the CSI recipe's RUN guard deleted, its comment kept" @@ -55,12 +59,15 @@ r="$t/notgit"; mkdir -p "$r"; expect fail "a directory the scan cannot read as a b="$t/bin"; mkdir -p "$b" printf '#!/bin/sh\necho "b revision=1 modified=false"\n' > "$b/release" printf '#!/bin/sh\necho "b revision=1 modified=false LAB BUILD(%s)"\n' "$tag" > "$b/lab" +printf '#!/bin/sh +echo "b revision=1 modified=false LAB BUILD(swblock_v11_format)" +' > "$b/draft" printf '#!/bin/sh\nexit 3\n' > "$b/broken" printf '#!/bin/sh\nexit 0\n' > "$b/silent" chmod +x "$b"/* bash "$refuse" "$b/release" >/dev/null || { echo "FAIL: refuse-lab-binary refused a release binary"; exit 1; } -for x in lab broken silent; do +for x in lab draft broken silent; do if bash "$refuse" "$b/release" "$b/$x" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed a $x binary"; exit 1; fi done if bash "$refuse" >/dev/null 2>&1; then echo "FAIL: refuse-lab-binary passed with no binary"; exit 1; fi -echo "lab-tag-check controls: OK ($n repositories, 4 binaries)" +echo "lab-tag-check controls: OK ($n repositories, 5 binaries)" diff --git a/seaweed-block/.github/scripts/lab-tag-check.sh b/seaweed-block/.github/scripts/lab-tag-check.sh index 1c42ac092e..8c0b76d927 100644 --- a/seaweed-block/.github/scripts/lab-tag-check.sh +++ b/seaweed-block/.github/scripts/lab-tag-check.sh @@ -1,8 +1,9 @@ #!/usr/bin/env bash -# The lab-only build tag swblock_lab_bigvol lifts the 256 GiB create cap and -# the local headroom refusal for scale rehearsals. It must never reach an -# image or a release build. Two checks, both failing closed: -# 1. Allowlist: only the files below may name the tag (git grep over the +# The lab-only build tags must never reach an image or a release build: +# swblock_lab_bigvol lifts the 256 GiB create cap and the local headroom +# refusal for scale rehearsals; swblock_v11_format turns on the draft v1.1 +# store format. Two checks, both failing closed: +# 1. Allowlist: only the files below may name either tag (git grep over the # tracked tree; a scan that cannot run is a failure, never "clean"). # 2. Wiring: every image Dockerfile under deploy/ that runs go build also runs # scripts/refuse-lab-binary.sh after its last go build, and the publish @@ -12,7 +13,7 @@ # unreadable input (printed). set -euo pipefail root=${1:-.} -tag=swblock_lab_bigvol +tags='swblock_lab_bigvol swblock_v11_format' allowed='.github/scripts/lab-tag-check-test.sh .github/scripts/lab-tag-check.sh .github/workflows/test.yml @@ -20,8 +21,9 @@ core/host/volume/status_heap_lab.go core/host/volume/status_heap_lab_test.go core/host/volume/status_heap_release.go core/host/volume/status_heap_release_test.go -core/storage/chunk_v11_format_lab.go +core/storage/chunk_v11_format_draft.go core/storage/chunk_v11_format_release.go +core/storage/chunk_v11_format_tag_test.go core/frontend/durable/headroom.go core/frontend/durable/headroom_lab_test.go core/geometry/volume_size.go @@ -32,24 +34,28 @@ core/geometry/volume_size_release_test.go docs/design/invariants.md docs/lab-heap-profiles.md internal/buildinfo/buildinfo.go +internal/buildinfo/v11_format_draft.go +internal/buildinfo/v11_format_release.go scripts/refuse-lab-binary.sh' fail() { echo "lab-tag: $*" >&2; exit 1; } [ -d "$root" ] || fail "no repository at $root" -set +e -hits=$(git -C "$root" grep -l -- "$tag") -rc=$? -set -e -case $rc in - 0) ;; - 1) hits="" ;; - *) fail "git grep failed (rc=$rc): the scan did not run" ;; -esac -bad="" -while IFS= read -r f; do - [ -n "$f" ] || continue - printf '%s\n' "$allowed" | grep -qxF -- "$f" || bad="$bad $f" -done <<< "$hits" -[ -z "$bad" ] || fail "$tag named outside the allowlist:$bad" +for tag in $tags; do + set +e + hits=$(git -C "$root" grep -l -- "$tag") + rc=$? + set -e + case $rc in + 0) ;; + 1) hits="" ;; + *) fail "git grep failed (rc=$rc): the scan did not run" ;; + esac + bad="" + while IFS= read -r f; do + [ -n "$f" ] || continue + printf '%s\n' "$allowed" | grep -qxF -- "$f" || bad="$bad $f" + done <<< "$hits" + [ -z "$bad" ] || fail "$tag named outside the allowlist:$bad" +done # read FILE: its whole content, once; a read that fails is a failure, never # "no match". diff --git a/seaweed-block/core/storage/chunk_v11_format_draft.go b/seaweed-block/core/storage/chunk_v11_format_draft.go new file mode 100644 index 0000000000..1af611d2f5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_v11_format_draft.go @@ -0,0 +1,9 @@ +//go:build swblock_v11_format + +package storage + +// chunkV11FormatBuild is true in a build with the swblock_v11_format tag: the +// draft v1.1 store format is exercised on lab volumes. Never a release build +// (CI refuses the tag in every image and release build). It is independent of +// swblock_lab_bigvol, which lifts only the create cap. +const chunkV11FormatBuild = true diff --git a/seaweed-block/core/storage/chunk_v11_format_lab.go b/seaweed-block/core/storage/chunk_v11_format_lab.go deleted file mode 100644 index 16b2b66ffc..0000000000 --- a/seaweed-block/core/storage/chunk_v11_format_lab.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build swblock_lab_bigvol - -package storage - -// chunkV11FormatBuild is true in a lab build: the draft v1.1 store format is -// exercised on lab volumes. Never a release build (CI refuses the tag in -// every image and release build). -const chunkV11FormatBuild = true diff --git a/seaweed-block/core/storage/chunk_v11_format_release.go b/seaweed-block/core/storage/chunk_v11_format_release.go index 558e51b4f2..48bb334265 100644 --- a/seaweed-block/core/storage/chunk_v11_format_release.go +++ b/seaweed-block/core/storage/chunk_v11_format_release.go @@ -1,4 +1,4 @@ -//go:build !swblock_lab_bigvol +//go:build !swblock_v11_format package storage diff --git a/seaweed-block/core/storage/chunk_v11_format_tag_test.go b/seaweed-block/core/storage/chunk_v11_format_tag_test.go new file mode 100644 index 0000000000..da9094b749 --- /dev/null +++ b/seaweed-block/core/storage/chunk_v11_format_tag_test.go @@ -0,0 +1,18 @@ +package storage + +import ( + "testing" + + "github.com/seaweedfs/seaweed-block/core/geometry" + "github.com/seaweedfs/seaweed-block/internal/buildinfo" +) + +// The draft v1.1 format follows its own tag (swblock_v11_format) alone: the +// lab cap tag (swblock_lab_bigvol) does not turn it on, and a build that runs +// it names itself in its revision (the image refusal keys on that). CI runs +// this with no tag, with each tag alone and with both. +func TestV11FormatFollowsItsOwnTagAlone(t *testing.T) { + if chunkV11FormatBuild != buildinfo.V11FormatDraft { + t.Fatalf("v1.1 format %v, but the build's format tag says %v (cap tag %v)", chunkV11FormatBuild, buildinfo.V11FormatDraft, geometry.LabBigVolume) + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 63e38a18f2..0c6d72d923 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -22,7 +22,7 @@ The design is described in three documents, and this one collects their machines - `INV-WAL-V3-W-MODE-A-001`, `INV-WAL-V3-W-SETWMODE-001`: no production code sets mode A or calls `SetWMode`. - `INV-WAL-V3-RESET-001`, `INV-WAL-V3-RESET-TWO-SLOT-001`, `INV-WAL-V3-RESET-HALF-001`, `INV-WAL-V3-RESET-INVARIANT-001`: no production code starts a reset; an open only detects a half reset. - `INV-PUBLISH-SETTLED-001`: no binary sets `ChunkOnPublishSettled`, so the hook is nil. - - `INV-CHUNK-RECORD-V11-001`: the draft v1.1 store format runs only in lab builds and tests (`chunkV11Format`); the row waits for the change that declares the format. + - `INV-CHUNK-RECORD-V11-001`: the draft v1.1 store format runs only in builds with the `swblock_v11_format` tag and in tests (`chunkV11Format`), independently of the cap tag `swblock_lab_bigvol` (`TestV11FormatFollowsItsOwnTagAlone`); the row waits for the change that declares the format. - `INV-WAL-V3-BASE-RETIRE-GATE-001`, and the chunk layer's attach over a completed BASE: a BASE is installed only by the replica side of replication, and a chunk volume refuses every replica role, so no production path puts a BASE on a chunk store. ## Contents diff --git a/seaweed-block/internal/buildinfo/buildinfo.go b/seaweed-block/internal/buildinfo/buildinfo.go index 1f76858a84..367c5bf22d 100644 --- a/seaweed-block/internal/buildinfo/buildinfo.go +++ b/seaweed-block/internal/buildinfo/buildinfo.go @@ -7,10 +7,15 @@ import ( "github.com/seaweedfs/seaweed-block/core/geometry" ) -// LabMarker is in every revision of a lab build (geometry.LabBigVolume): a -// published image refuses any binary that reports it -// (scripts/refuse-lab-binary.sh, run in each image Dockerfile). -const LabMarker = "LAB BUILD(swblock_lab_bigvol)" +// LabMarker is in every revision of a lab build (geometry.LabBigVolume), and +// V11FormatMarker in every revision of a build with the draft v1.1 store +// format (V11FormatDraft): a published image refuses any binary that reports +// either (scripts/refuse-lab-binary.sh, run in each image Dockerfile, refuses +// "LAB BUILD"). +const ( + LabMarker = "LAB BUILD(swblock_lab_bigvol)" + V11FormatMarker = "LAB BUILD(swblock_v11_format)" +) // Version returns a compact provenance string suitable for lab artifacts. func Version(component string) string { @@ -35,8 +40,12 @@ func Revision() string { } } } + out := fmt.Sprintf("%s modified=%s", revision, modified) if geometry.LabBigVolume { - return fmt.Sprintf("%s modified=%s %s", revision, modified, LabMarker) + out += " " + LabMarker } - return fmt.Sprintf("%s modified=%s", revision, modified) + if V11FormatDraft { + out += " " + V11FormatMarker + } + return out } diff --git a/seaweed-block/internal/buildinfo/buildinfo_lab_test.go b/seaweed-block/internal/buildinfo/buildinfo_lab_test.go index a2348ac1a4..116ea07d57 100644 --- a/seaweed-block/internal/buildinfo/buildinfo_lab_test.go +++ b/seaweed-block/internal/buildinfo/buildinfo_lab_test.go @@ -15,3 +15,15 @@ func TestRevisionNamesALabBuild(t *testing.T) { t.Fatalf("lab build %v, revision %q", geometry.LabBigVolume, Revision()) } } + +// A build with the draft v1.1 store format names itself in every revision, +// independently of the lab cap tag; a release build never does. +func TestRevisionNamesADraftFormatBuild(t *testing.T) { + has := strings.Contains(Revision(), V11FormatMarker) && strings.Contains(Version("x"), V11FormatMarker) + if has != V11FormatDraft { + t.Fatalf("draft format build %v, revision %q", V11FormatDraft, Revision()) + } + if strings.Contains(Revision(), LabMarker) != geometry.LabBigVolume { + t.Fatalf("the cap tag's marker does not follow the cap tag alone: %q", Revision()) + } +} diff --git a/seaweed-block/internal/buildinfo/v11_format_draft.go b/seaweed-block/internal/buildinfo/v11_format_draft.go new file mode 100644 index 0000000000..e77c9a2367 --- /dev/null +++ b/seaweed-block/internal/buildinfo/v11_format_draft.go @@ -0,0 +1,7 @@ +//go:build swblock_v11_format + +package buildinfo + +// V11FormatDraft is true in a build with the swblock_v11_format tag (the +// draft v1.1 store format, core/storage chunkV11FormatBuild). +const V11FormatDraft = true diff --git a/seaweed-block/internal/buildinfo/v11_format_release.go b/seaweed-block/internal/buildinfo/v11_format_release.go new file mode 100644 index 0000000000..8a29b05ca9 --- /dev/null +++ b/seaweed-block/internal/buildinfo/v11_format_release.go @@ -0,0 +1,7 @@ +//go:build !swblock_v11_format + +package buildinfo + +// V11FormatDraft is false in a release build: the v1.1 store format is not +// declared. +const V11FormatDraft = false diff --git a/seaweed-block/scripts/refuse-lab-binary.sh b/seaweed-block/scripts/refuse-lab-binary.sh index 5c94a62f9f..ac0a9e7474 100644 --- a/seaweed-block/scripts/refuse-lab-binary.sh +++ b/seaweed-block/scripts/refuse-lab-binary.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash # refuse-lab-binary.sh BIN...: refuse to publish a lab build. Each BIN must # answer -version, and its answer must not carry the lab marker -# (internal/buildinfo LabMarker, set by the swblock_lab_bigvol tag). A binary +# (internal/buildinfo LabMarker or V11FormatMarker, set by the +# swblock_lab_bigvol or swblock_v11_format tag; both say "LAB BUILD"). A binary # that cannot answer is refused too (fail closed). Run by every image # Dockerfile right after its go build, so no image holding a lab binary is # built, and so none is pushed. From 32f9366542b708791de776df779a76c55edf0ac5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:16:50 -0800 Subject: [PATCH 08/51] ci: vet and test each lab tag alone and both together The draft v1.1 format tag is now separate from the 256 GiB cap lift, so the lab-tag step builds and tests swblock_lab_bigvol, swblock_v11_format and both, and runs the format-tag test under each. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/.github/workflows/test.yml | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/seaweed-block/.github/workflows/test.yml b/seaweed-block/.github/workflows/test.yml index dd27fd102d..b6ffd7f332 100644 --- a/seaweed-block/.github/workflows/test.yml +++ b/seaweed-block/.github/workflows/test.yml @@ -100,20 +100,24 @@ jobs: if: matrix.suite == 'unit' run: go vet ./... - - name: Lab build tag stays out of images and releases + - name: Lab build tags stay out of images and releases if: matrix.suite == 'unit' # swblock_lab_bigvol lifts the 256 GiB create cap and the local - # headroom refusal for scale rehearsals only. The default test run - # pins the release cap (TestReleaseBuildKeepsTheCreateCap). This step - # checks the tag allowlist and that every image Dockerfile refuses a - # lab binary (scripts/refuse-lab-binary.sh) after its build, with - # controls, then tests the lab build. + # headroom refusal for scale rehearsals only; swblock_v11_format turns + # on the draft v1.1 store format. The default test run pins the + # release cap (TestReleaseBuildKeepsTheCreateCap) and the release + # format. This step checks the tags' allowlist and that every image + # Dockerfile refuses a lab binary (scripts/refuse-lab-binary.sh) after + # its build, with controls, then tests each tag alone and both. run: | set -euo pipefail bash .github/scripts/lab-tag-check.sh . bash .github/scripts/lab-tag-check-test.sh - go vet -tags swblock_lab_bigvol ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/ - go test -count=1 -tags swblock_lab_bigvol -run 'Lab|Headroom|Revision' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ + for tags in swblock_lab_bigvol swblock_v11_format swblock_lab_bigvol,swblock_v11_format; do + go vet -tags "$tags" ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ ./core/storage/ + go test -count=1 -tags "$tags" -run 'Lab|Headroom|Revision' ./core/geometry/ ./core/frontend/durable/ ./internal/buildinfo/ + go test -count=1 -tags "$tags" -run 'TestV11FormatFollowsItsOwnTagAlone' ./core/storage/ + done - name: Test default configuration if: matrix.suite == 'unit' From 0eb8f0e1741792bb7075276caed8c3d11f2e4162 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 10:51:10 -0800 Subject: [PATCH 09/51] storage: sameProposalByChange, the O(C) "proposal landed" decision (not wired yet) A commit by change landed iff HEAD's generation is past the expected base, every identity field the full comparison has is equal, every changed index names the new reference (nothing for a zeroing) and every candidate the cut marked equal names the base reference its mark assumed; unchanged, unmarked indices are not compared. The rule is SegCut's existing decision (no new row). TestSameProposalByChange: each condition broken alone is not landed, a replay is landed. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_proposal_by_change.go | 55 +++++++++++++++ .../storage/chunk_proposal_by_change_test.go | 69 +++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_proposal_by_change.go create mode 100644 seaweed-block/core/storage/chunk_proposal_by_change_test.go diff --git a/seaweed-block/core/storage/chunk_proposal_by_change.go b/seaweed-block/core/storage/chunk_proposal_by_change.go new file mode 100644 index 0000000000..3726bf7382 --- /dev/null +++ b/seaweed-block/core/storage/chunk_proposal_by_change.go @@ -0,0 +1,55 @@ +package storage + +// sameProposalByChange decides whether a commit by change landed in cur, +// without comparing whole chunk maps (V4-B PR 4; the rule is SegCut's +// "proposal landed" decision, the model's existing row): O(C) in the cut's +// changed and equal-marked chunks. The proposal landed iff +// +// 1. cur's generation is past the base the CAS expected (baseGen); +// 2. every identity field the full comparison has is equal: epoch, holder, +// position, the detached state and who detached, the chunk size and the +// manifest's chunk count; +// 3. for every changed index cur names exactly the new reference (nothing, +// for a chunk the change made zeros); +// 4. for every candidate the cut marked equal to its base reference, cur +// names that base reference (a mark assumes it; without the check an +// index another writer changed would be marked published under a hash +// HEAD does not name). +// +// Indices the cut neither changed nor marked carry marks set by earlier +// landings and are not compared. cur's chunks are read through ref (a lookup +// in whatever representation the caller has: a map, the ref table). +func sameProposalByChange(cur, ident chunkHead, baseGen uint64, ref func(idx uint64) (chunkRef, bool), + changes map[uint64]*chunkRef, marked map[uint64]chunkRef) bool { + if cur.Gen <= baseGen { + return false + } + if cur.Epoch != ident.Epoch || cur.Holder != ident.Holder || cur.RemoteLSN != ident.RemoteLSN || + cur.ChunkBytes != ident.ChunkBytes || cur.ManifestChunkCount != ident.ManifestChunkCount { + return false + } + if chunkHeadIsDetached(cur) != chunkHeadIsDetached(ident) || (cur.DetachedBy == nil) != (ident.DetachedBy == nil) || + (cur.DetachedBy != nil && (cur.DetachedBy.Holder != ident.DetachedBy.Holder || cur.DetachedBy.Epoch != ident.DetachedBy.Epoch)) { + return false + } + same := func(a, b chunkRef) bool { return a.Key == b.Key && a.SHA256 == b.SHA256 && a.Encoding == b.Encoding } + for idx, want := range changes { + got, ok := ref(idx) + if want == nil { + if ok { + return false + } + continue + } + if !ok || !same(got, *want) { + return false + } + } + for idx, base := range marked { + got, ok := ref(idx) + if !ok || !same(got, base) { + return false + } + } + return true +} diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go new file mode 100644 index 0000000000..41470508e2 --- /dev/null +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -0,0 +1,69 @@ +package storage + +import ( + "crypto/sha256" + "fmt" + "testing" +) + +// sameProposalByChange is landed iff the generation advanced past the base, +// every identity field equals, every changed index names the new reference +// (nothing for a zeroing) and every equal-marked candidate names the base +// reference its mark assumed; unchanged, unmarked indices are not compared. +// Each condition broken alone is not landed; a replay of the identical +// proposal is landed whichever copy won. +func TestSameProposalByChange(t *testing.T) { + r := func(tag string) chunkRef { + s := sha256.Sum256([]byte(tag)) + return chunkRef{Key: fmt.Sprintf("k-%s", tag), SHA256: s, Encoding: "full"} + } + newRef, base5, other := r("new"), r("base5"), r("other") + ident := chunkHead{Epoch: 3, Holder: "a", RemoteLSN: 90, ChunkBytes: 4096, ManifestChunkCount: 64, State: chunkHeadActive} + changes := map[uint64]*chunkRef{2: &newRef, 4: nil} // chunk 2 rewritten, chunk 4 zeroed + marked := map[uint64]chunkRef{5: base5} // chunk 5 compared equal to its base ref + landedHead := func() (chunkHead, map[uint64]chunkRef) { + h := ident + h.Gen = 8 + return h, map[uint64]chunkRef{2: newRef, 5: base5, 7: other} // 7: neither changed nor marked + } + check := func(h chunkHead, m map[uint64]chunkRef) bool { + return sameProposalByChange(h, ident, 7, func(i uint64) (chunkRef, bool) { r, ok := m[i]; return r, ok }, changes, marked) + } + h, m := landedHead() + if !check(h, m) { + t.Fatal("the landed proposal is not found landed") + } + m[7] = r("elsewhere") // an index the cut neither changed nor marked: not compared + if !check(h, m) { + t.Fatal("an unchanged, unmarked index decided the outcome") + } + for name, mutate := range map[string]func(h *chunkHead, m map[uint64]chunkRef){ + "generation not past the base": func(h *chunkHead, _ map[uint64]chunkRef) { h.Gen = 7 }, + "another epoch": func(h *chunkHead, _ map[uint64]chunkRef) { h.Epoch = 4 }, + "another holder": func(h *chunkHead, _ map[uint64]chunkRef) { h.Holder = "b" }, + "another position": func(h *chunkHead, _ map[uint64]chunkRef) { h.RemoteLSN = 91 }, + "another chunk size": func(h *chunkHead, _ map[uint64]chunkRef) { h.ChunkBytes = 8192 }, + "another manifest count": func(h *chunkHead, _ map[uint64]chunkRef) { h.ManifestChunkCount = 65 }, + "detached": func(h *chunkHead, _ map[uint64]chunkRef) { + h.State = chunkHeadDetached + h.DetachedBy = &chunkDetachedBy{Holder: "a", Epoch: 3} + }, + "a changed index not written": func(_ *chunkHead, m map[uint64]chunkRef) { m[2] = other }, + "a changed index missing": func(_ *chunkHead, m map[uint64]chunkRef) { delete(m, 2) }, + "a zeroed index still named": func(_ *chunkHead, m map[uint64]chunkRef) { m[4] = other }, + "an equal-marked index changed": func(_ *chunkHead, m map[uint64]chunkRef) { m[5] = other }, + "an equal-marked index now nothing": func(_ *chunkHead, m map[uint64]chunkRef) { delete(m, 5) }, + } { + h, m := landedHead() + mutate(&h, m) + if check(h, m) { + t.Errorf("%s: found landed", name) + } + } + // A replay of the identical proposal: whichever copy won, cur is the same. + h1, m1 := landedHead() + h1.Gen = 9 // the re-proposal landed one generation later + if !check(h1, m1) { + t.Fatal("a replay of the identical proposal is not found landed") + } +} From ff41808326175c4da7e56c4b8ba25d2608aa62ac Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:29:36 -0800 Subject: [PATCH 10/51] storage: a mark may name an absent base (zero chunk equal to nothing) The cut marks a zero chunk equal to an absent base; marked now takes the shape of changes (nil: cur must name nothing there), so a landed proposal with such a mark is judged landed and one where cur names a reference is not. Co-Authored-By: Claude Opus 5.5 --- .../core/storage/chunk_proposal_by_change.go | 25 ++++++++++--------- .../storage/chunk_proposal_by_change_test.go | 12 ++++++++- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/seaweed-block/core/storage/chunk_proposal_by_change.go b/seaweed-block/core/storage/chunk_proposal_by_change.go index 3726bf7382..464d343174 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change.go @@ -12,15 +12,16 @@ package storage // 3. for every changed index cur names exactly the new reference (nothing, // for a chunk the change made zeros); // 4. for every candidate the cut marked equal to its base reference, cur -// names that base reference (a mark assumes it; without the check an -// index another writer changed would be marked published under a hash -// HEAD does not name). +// names that base reference, or nothing when the base named nothing (a +// zero chunk marked equal to an absent base); a mark assumes it, and +// without the check an index another writer changed would be marked +// published under a hash HEAD does not name. // // Indices the cut neither changed nor marked carry marks set by earlier // landings and are not compared. cur's chunks are read through ref (a lookup // in whatever representation the caller has: a map, the ref table). func sameProposalByChange(cur, ident chunkHead, baseGen uint64, ref func(idx uint64) (chunkRef, bool), - changes map[uint64]*chunkRef, marked map[uint64]chunkRef) bool { + changes, marked map[uint64]*chunkRef) bool { if cur.Gen <= baseGen { return false } @@ -33,21 +34,21 @@ func sameProposalByChange(cur, ident chunkHead, baseGen uint64, ref func(idx uin return false } same := func(a, b chunkRef) bool { return a.Key == b.Key && a.SHA256 == b.SHA256 && a.Encoding == b.Encoding } - for idx, want := range changes { + // names reports whether cur names exactly want at idx (nil: nothing). + names := func(idx uint64, want *chunkRef) bool { got, ok := ref(idx) if want == nil { - if ok { - return false - } - continue + return !ok } - if !ok || !same(got, *want) { + return ok && same(got, *want) + } + for idx, want := range changes { + if !names(idx, want) { return false } } for idx, base := range marked { - got, ok := ref(idx) - if !ok || !same(got, base) { + if !names(idx, base) { return false } } diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index 41470508e2..6a9c5ea534 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -20,7 +20,7 @@ func TestSameProposalByChange(t *testing.T) { newRef, base5, other := r("new"), r("base5"), r("other") ident := chunkHead{Epoch: 3, Holder: "a", RemoteLSN: 90, ChunkBytes: 4096, ManifestChunkCount: 64, State: chunkHeadActive} changes := map[uint64]*chunkRef{2: &newRef, 4: nil} // chunk 2 rewritten, chunk 4 zeroed - marked := map[uint64]chunkRef{5: base5} // chunk 5 compared equal to its base ref + marked := map[uint64]*chunkRef{5: &base5, 6: nil} // chunk 5 equal to its base ref; chunk 6 a zero chunk equal to an absent base landedHead := func() (chunkHead, map[uint64]chunkRef) { h := ident h.Gen = 8 @@ -66,4 +66,14 @@ func TestSameProposalByChange(t *testing.T) { if !check(h1, m1) { t.Fatal("a replay of the identical proposal is not found landed") } + // A zero chunk marked equal to an absent base: cur naming nothing there + // is landed; cur naming a reference there is not. + h2, m2 := landedHead() + if _, named := m2[6]; named || !check(h2, m2) { + t.Fatal("a zero chunk marked equal to an absent base: cur absent is not found landed") + } + m2[6] = other + if check(h2, m2) { + t.Fatal("a zero chunk marked equal to an absent base: cur naming a reference is found landed") + } } From 9391166b25050ce353e874e73abf3eb9f91c548d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:43:59 -0800 Subject: [PATCH 11/51] hostlimit, storage: red tests, a per-host cap on chunk fetches Seams: Config.FetchSlots (default 64), fetchSlot (a key's hash slot), Limiter.HoldFetch (no cap yet) and storage.BudgetFetch. - TestHoldFetchCapHoldsAcrossProcesses: with every slot held by other processes, a fetch waits until one is released, then takes it. Fails here. - TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld: a waiter past its context returns the context's error, and a slot it gets after is released at once. Fails here. - TestHoldFetchTakesAnotherSlotThatFreesFirst: a waiter behind a slow holder of its own hash slot takes another slot within one retry interval of its release. Fails here. - TestHoldFetchTakesAFreeSlotAtOnce: a fetch with a free slot does not wait (holds here, must keep holding). - TestChunkFetchHoldsAHostSlotAroundItsRemoteRead: a chunk fetch holds one slot exactly across its remote read. Fails here: none is held. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/hostlimit/fetch.go | 20 +++ seaweed-block/core/hostlimit/fetch_test.go | 162 ++++++++++++++++++ seaweed-block/core/hostlimit/limiter.go | 6 +- .../core/storage/chunk_cut_budget.go | 6 + .../core/storage/chunk_fetch_cap_test.go | 74 ++++++++ 5 files changed, 266 insertions(+), 2 deletions(-) create mode 100644 seaweed-block/core/hostlimit/fetch.go create mode 100644 seaweed-block/core/hostlimit/fetch_test.go create mode 100644 seaweed-block/core/storage/chunk_fetch_cap_test.go diff --git a/seaweed-block/core/hostlimit/fetch.go b/seaweed-block/core/hostlimit/fetch.go new file mode 100644 index 0000000000..009a5308a4 --- /dev/null +++ b/seaweed-block/core/hostlimit/fetch.go @@ -0,0 +1,20 @@ +package hostlimit + +import ( + "context" + "hash/fnv" +) + +// fetchSlot is the fetch slot a key waits on when every slot is held: its +// hash, modulo the slot count. +func fetchSlot(key string, n int) int { + h := fnv.New32a() + _, _ = h.Write([]byte(key)) + return int(h.Sum32() % uint32(n)) +} + +// HoldFetch holds one of the host's fetch slots for one chunk transfer +// (seam: no cap yet). +func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) { + return func() {}, ctx.Err() +} diff --git a/seaweed-block/core/hostlimit/fetch_test.go b/seaweed-block/core/hostlimit/fetch_test.go new file mode 100644 index 0000000000..143e02d451 --- /dev/null +++ b/seaweed-block/core/hostlimit/fetch_test.go @@ -0,0 +1,162 @@ +package hostlimit + +import ( + "context" + "errors" + "fmt" + "testing" + "time" +) + +func fetchConfig(t *testing.T, slots int) Config { + t.Helper() + c := testConfig(t) + c.FetchSlots = slots + return c +} + +// keyOnSlot is a key whose hash slot is s among n. +func keyOnSlot(t *testing.T, s, n int) string { + t.Helper() + for i := 0; i < 10000; i++ { + k := fmt.Sprintf("v/%d", i) + if fetchSlot(k, n) == s { + return k + } + } + t.Fatalf("no key on slot %d of %d", s, n) + return "" +} + +type held struct { + release func() + err error +} + +// holdAsync runs HoldFetch in the background; its result arrives on the +// channel. The test's cleanup releases a slot it got. +func holdAsync(t *testing.T, l *Limiter, ctx context.Context, key string) <-chan held { + t.Helper() + got := make(chan held, 1) + go func() { + r, err := l.HoldFetch(ctx, key) + got <- held{r, err} + }() + return got +} + +func mustHold(t *testing.T, l *Limiter, key string) func() { + t.Helper() + r, err := l.HoldFetch(context.Background(), key) + if err != nil { + t.Fatal(err) + } + return r +} + +// While slots are free, a fetch takes one without waiting. +func TestHoldFetchTakesAFreeSlotAtOnce(t *testing.T) { + c := fetchConfig(t, 2) + a, b := newTest(t, c), newTest(t, c) + r1 := mustHold(t, a, keyOnSlot(t, 0, 2)) + defer r1() + start := time.Now() + r2 := mustHold(t, b, keyOnSlot(t, 0, 2)) // its hash slot is held: it takes the other one + defer r2() + if d := time.Since(start); d > 200*time.Millisecond { + t.Fatalf("a fetch with a free slot waited %s", d) + } +} + +// The cap holds across processes: with every slot held by others, a fetch +// waits until one is released, and then takes it. +func TestHoldFetchCapHoldsAcrossProcesses(t *testing.T) { + c := fetchConfig(t, 2) + a, b, w := newTest(t, c), newTest(t, c), newTest(t, c) + r1 := mustHold(t, a, keyOnSlot(t, 0, 2)) + r2 := mustHold(t, b, keyOnSlot(t, 1, 2)) + defer r2() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + got := holdAsync(t, w, ctx, "v/third") + select { + case h := <-got: + if h.release != nil { + h.release() + } + t.Fatalf("a third fetch held a slot while both were held (err %v)", h.err) + case <-time.After(150 * time.Millisecond): + } + r1() + select { + case h := <-got: + if h.err != nil { + t.Fatalf("the waiting fetch: %v", h.err) + } + h.release() + case <-time.After(2 * time.Second): + t.Fatal("the waiting fetch did not take the released slot") + } +} + +// A waiter whose context ends returns its context's error, and a slot it +// gets after that is released at once: a later fetch is not held back by it. +func TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld(t *testing.T) { + c := fetchConfig(t, 1) + a, w, later := newTest(t, c), newTest(t, c), newTest(t, c) + r1 := mustHold(t, a, "v/a") + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if _, err := w.HoldFetch(ctx, "v/w"); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("a waiter past its context answered %v, want its deadline", err) + } + r1() // the abandoned wait now gets the slot, and must release it at once + ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel2() + select { + case h := <-holdAsync(t, later, ctx2, "v/later"): + if h.err != nil { + t.Fatalf("a later fetch was held back by an abandoned wait: %v", h.err) + } + h.release() + case <-time.After(3 * time.Second): + t.Fatal("a later fetch never got the slot") + } +} + +// A waiter blocked behind a slow holder on its own hash slot is not delayed +// beyond one retry interval once another slot is free: the host's slots are +// one pool, not N separate queues. +func TestHoldFetchTakesAnotherSlotThatFreesFirst(t *testing.T) { + c := fetchConfig(t, 2) + slow, other, w := newTest(t, c), newTest(t, c), newTest(t, c) + key := keyOnSlot(t, 0, 2) + rSlow := mustHold(t, slow, key) // the waiter's hash slot, held for the whole test + defer rSlow() + rOther := mustHold(t, other, keyOnSlot(t, 1, 2)) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + got := holdAsync(t, w, ctx, key) + select { + case h := <-got: + if h.release != nil { + h.release() + } + t.Fatalf("the waiter held a slot while both were held (err %v)", h.err) + case <-time.After(150 * time.Millisecond): + } + freed := time.Now() + rOther() + select { + case h := <-got: + if h.err != nil { + t.Fatalf("the waiter: %v", h.err) + } + if d := time.Since(freed); d > 300*time.Millisecond { + t.Fatalf("the waiter took the freed slot %s after it was freed, behind a slow holder of its own slot", d) + } + h.release() + case <-time.After(2 * time.Second): + t.Fatal("the waiter never took the other slot while its own stayed held") + } +} diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 4b60b65831..6107d5024b 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -63,13 +63,15 @@ type Config struct { // only after this long with no progress of its work (Progress). Work // that keeps progressing is never revoked, however long it holds. NoProgress time.Duration + // FetchSlots caps the chunk fetches in flight on the host (seam). + FetchSlots int } func DefaultConfig(dir string) Config { - return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second} + return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second, FetchSlots: 64} } func (c Config) Validate() error { - if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 { + if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 || c.FetchSlots < 1 || c.FetchSlots > 1024 { return errors.New("hostlimit: invalid configuration") } return nil diff --git a/seaweed-block/core/storage/chunk_cut_budget.go b/seaweed-block/core/storage/chunk_cut_budget.go index b68022a1db..ec1d9de652 100644 --- a/seaweed-block/core/storage/chunk_cut_budget.go +++ b/seaweed-block/core/storage/chunk_cut_budget.go @@ -32,6 +32,12 @@ func budgetProgress(b Budget, ticket uint64) func() { return func() {} } +// BudgetFetch is a Budget that caps the chunk fetches in flight on the host +// (seam). +type BudgetFetch interface { + HoldFetch(ctx context.Context, key string) (release func(), err error) +} + type cutBudgetReservation struct { budget Budget ticket uint64 diff --git a/seaweed-block/core/storage/chunk_fetch_cap_test.go b/seaweed-block/core/storage/chunk_fetch_cap_test.go new file mode 100644 index 0000000000..6d0d2a1018 --- /dev/null +++ b/seaweed-block/core/storage/chunk_fetch_cap_test.go @@ -0,0 +1,74 @@ +package storage + +import ( + "context" + "sync" + "testing" + "time" +) + +// fetchSlots is a BudgetFetch that counts the fetch slots held, and the most +// held at once. +type fetchSlots struct { + Budget + mu sync.Mutex + active, holds int + keys []string +} + +func (f *fetchSlots) HoldFetch(ctx context.Context, key string) (func(), error) { + f.mu.Lock() + f.active++ + f.holds++ + f.keys = append(f.keys, key) + f.mu.Unlock() + var once sync.Once + return func() { + once.Do(func() { + f.mu.Lock() + f.active-- + f.mu.Unlock() + }) + }, nil +} + +func (f *fetchSlots) state() (active, holds int) { + f.mu.Lock() + defer f.mu.Unlock() + return f.active, f.holds +} + +// A chunk fetch holds one host fetch slot exactly across its remote read: +// held while the read is in flight, released once the read has returned (the +// install and the reader's wake-up hold none). +func TestChunkFetchHoldsAHostSlotAroundItsRemoteRead(t *testing.T) { + s, layer, remote, _ := hydrationFixture(t, 2, 64) + slots := &fetchSlots{} + layer.cfg.Budget = slots + entered, release := holdGets(t, remote) + read := make(chan error, 1) + go func() { + _, err := s.Read(0) + read <- err + }() + select { + case <-entered: + case <-time.After(ctLocalBound): + t.Fatal("the read miss never reached the remote") + } + if active, holds := slots.state(); active != 1 || holds != 1 { + t.Fatalf("during the remote read %d slots are held (%d taken), want exactly one", active, holds) + } + release() + select { + case err := <-read: + if err != nil { + t.Fatal(err) + } + case <-time.After(ctLocalBound): + t.Fatal("the read did not complete") + } + if active, _ := slots.state(); active != 0 { + t.Fatalf("%d fetch slots still held after the read returned", active) + } +} From 5a57e8564dadf51119187fe3dd44e879000ebf44 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:52:37 -0800 Subject: [PATCH 12/51] hostlimit, storage: chunk fetches are capped per host - hostlimit: Config.FetchSlots (default 64, files fetch-0..N-1 in the pool). HoldFetch takes a free slot without waiting, from the key's hash slot; with every slot held it blocks on its hash slot (the kernel queues the waiters) and tries the other slots every 20 ms, using whichever lock comes first and releasing the other; its context bounds the wait, and a lock got after that is released at once. lockBlocking on Unix and Windows. - storage: BudgetFetch; fillOnce holds one slot across its remote read only (a read miss and a hydrate-all fill alike); a context error on the wait is the hydration path's pending, as before. - blockvolume: --host-limit-fetch-slots. Invariants: INV-HOST-FETCH-CAP-001; M7 states it. v1.1 notes carry it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/host_limit.go | 1 + seaweed-block/core/hostlimit/fetch.go | 106 +++++++++++++++++- seaweed-block/core/hostlimit/limiter.go | 3 +- seaweed-block/core/hostlimit/lock_unix.go | 11 ++ seaweed-block/core/hostlimit/lock_windows.go | 6 + .../core/storage/chunk_cut_budget.go | 5 +- seaweed-block/core/storage/chunk_layer.go | 12 ++ seaweed-block/docs/design/invariants.md | 3 +- seaweed-block/docs/releases/v1.1.md | 4 + 9 files changed, 144 insertions(+), 7 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go index 7b04e69382..b20da0de9a 100644 --- a/seaweed-block/cmd/blockvolume/host_limit.go +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -16,6 +16,7 @@ func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { fs.Int64Var(&c.COWBytes, "host-limit-cow-bytes", c.COWBytes, "maximum saved COW bytes per slot") fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap. --host-limit-no-progress must exceed one chunk's send time at this rate per held slot, or a steadily sending cut is revoked") fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "kept for configuration compatibility; the urgent fallback is not paced (no shared host cap to protect)") + fs.IntVar(&c.FetchSlots, "host-limit-fetch-slots", c.FetchSlots, "chunk fetches in flight on the host, across its processes (1-1024); a read of an absent chunk waits for a slot, bounded by its read-miss timeout") fs.DurationVar(&c.NoProgress, "host-limit-no-progress", c.NoProgress, "a held slot is revoked after this long with no progress of its work (chunks compared, staged, uploaded or filled); revocation aborts but waits for admitted I/O before release") fs.DurationVar(&c.NoProgress, "host-limit-max-hold", c.NoProgress, "deprecated: the same as --host-limit-no-progress (a hold is no longer limited by its age)") } diff --git a/seaweed-block/core/hostlimit/fetch.go b/seaweed-block/core/hostlimit/fetch.go index 009a5308a4..d0dc83d554 100644 --- a/seaweed-block/core/hostlimit/fetch.go +++ b/seaweed-block/core/hostlimit/fetch.go @@ -2,9 +2,20 @@ package hostlimit import ( "context" + "errors" + "fmt" "hash/fnv" + "os" + "path/filepath" + "sync" + "time" ) +// fetchRetry is how often a waiting fetch tries the other slots while it is +// blocked on its own: the host's slots are one pool, so a slot that frees +// elsewhere is taken within one interval. +const fetchRetry = 20 * time.Millisecond + // fetchSlot is the fetch slot a key waits on when every slot is held: its // hash, modulo the slot count. func fetchSlot(key string, n int) int { @@ -13,8 +24,97 @@ func fetchSlot(key string, n int) int { return int(h.Sum32() % uint32(n)) } -// HoldFetch holds one of the host's fetch slots for one chunk transfer -// (seam: no cap yet). +// HoldFetch holds one of the host's FetchSlots fetch slots (files fetch-0 .. +// fetch-(N-1) in the pool, so the cap is per host and dies with its +// holders) for one chunk transfer; release gives it back. It never refuses: +// +// 1. it takes a free slot without waiting, trying from key's hash slot; +// 2. with every slot held, it blocks on its hash slot (the kernel queues the +// waiters) and, while blocked, tries the other slots every fetchRetry; +// whichever lock comes first is used and the other is released at once; +// 3. the wait is bounded by ctx: when it ends, HoldFetch returns ctx's error, +// and a lock the blocked wait gets after that is released at once. func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) { - return func() {}, ctx.Err() + if err := ctx.Err(); err != nil { + return nil, err + } + n := l.cfg.FetchSlots + home := fetchSlot(key, n) + open := func(i int) (*os.File, error) { + return os.OpenFile(filepath.Join(l.cfg.Directory, fmt.Sprintf("fetch-%d", i)), os.O_CREATE|os.O_RDWR, 0o600) + } + // try takes a free slot among those try covers, without waiting; nil + // when every one is held. + try := func(skip int) (*os.File, error) { + for k := 0; k < n; k++ { + i := (home + k) % n + if i == skip { + continue + } + f, err := open(i) + if err != nil { + return nil, err + } + err = tryLock(f) + if err == nil { + return f, nil + } + _ = f.Close() + if !errors.Is(err, ErrBusy) { + return nil, err + } + } + return nil, nil + } + if f, err := try(-1); f != nil || err != nil { + if err != nil { + return nil, err + } + return releaseFetch(f), nil + } + homeF, err := open(home) + if err != nil { + return nil, err + } + locked := make(chan error, 1) + go func() { locked <- lockBlocking(homeF) }() + // abandon releases the blocked wait's lock once it gets it. + abandon := func() { + go func() { + <-locked + _ = homeF.Close() + }() + } + t := time.NewTicker(fetchRetry) + defer t.Stop() + for { + select { + case err := <-locked: + if err != nil { + _ = homeF.Close() + return nil, err + } + return releaseFetch(homeF), nil + case <-ctx.Done(): + abandon() + return nil, ctx.Err() + case <-t.C: + f, err := try(home) + if err != nil { + abandon() + return nil, err + } + if f != nil { + abandon() + return releaseFetch(f), nil + } + } + } +} + +// releaseFetch gives a fetch slot back, once: closing the file releases its +// lock. +func releaseFetch(f *os.File) func() { + var once sync.Once + return func() { once.Do(func() { _ = f.Close() }) } } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 6107d5024b..9bb19dfa05 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -63,7 +63,8 @@ type Config struct { // only after this long with no progress of its work (Progress). Work // that keeps progressing is never revoked, however long it holds. NoProgress time.Duration - // FetchSlots caps the chunk fetches in flight on the host (seam). + // FetchSlots caps the chunk fetches in flight on the host, across its + // processes (HoldFetch): a guest read waits for a slot, never refused. FetchSlots int } diff --git a/seaweed-block/core/hostlimit/lock_unix.go b/seaweed-block/core/hostlimit/lock_unix.go index ea3d6c09f3..0c4959fd52 100644 --- a/seaweed-block/core/hostlimit/lock_unix.go +++ b/seaweed-block/core/hostlimit/lock_unix.go @@ -24,3 +24,14 @@ func tryLockShared(f *os.File) error { } return err } + +// lockBlocking takes an exclusive lock on f, waiting until it is free. It +// cannot be cancelled: a caller that stops waiting closes f once it returns. +func lockBlocking(f *os.File) error { + for { + err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX) + if !errors.Is(err, syscall.EINTR) { + return err + } + } +} diff --git a/seaweed-block/core/hostlimit/lock_windows.go b/seaweed-block/core/hostlimit/lock_windows.go index 3870ad922c..c3aa7ed6d4 100644 --- a/seaweed-block/core/hostlimit/lock_windows.go +++ b/seaweed-block/core/hostlimit/lock_windows.go @@ -24,3 +24,9 @@ func tryLockShared(f *os.File) error { } return err } + +// lockBlocking takes an exclusive lock on f, waiting until it is free. It +// cannot be cancelled: a caller that stops waiting closes f once it returns. +func lockBlocking(f *os.File) error { + return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &windows.Overlapped{}) +} diff --git a/seaweed-block/core/storage/chunk_cut_budget.go b/seaweed-block/core/storage/chunk_cut_budget.go index ec1d9de652..e74f7071b6 100644 --- a/seaweed-block/core/storage/chunk_cut_budget.go +++ b/seaweed-block/core/storage/chunk_cut_budget.go @@ -32,8 +32,9 @@ func budgetProgress(b Budget, ticket uint64) func() { return func() {} } -// BudgetFetch is a Budget that caps the chunk fetches in flight on the host -// (seam). +// BudgetFetch is a Budget that caps the chunk fetches in flight on the host: +// HoldFetch holds one slot for one chunk transfer, waiting (bounded by ctx) +// when every slot is held; release gives it back. type BudgetFetch interface { HoldFetch(ctx context.Context, key string) (release func(), err error) } diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 14406f0a84..aa522e46ae 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -701,7 +701,19 @@ func (l *chunkLayerImpl) fillOnce(ctx context.Context, idx, gen uint64, ref chun l.stMu.Lock() version := l.chunkVersion(idx) l.stMu.Unlock() + // The host's fetch cap: one slot held across the remote read only, not + // the install. Its wait is bounded by ctx, a context error that the + // hydration path answers as pending. + release := func() {} + if fb, ok := l.cfg.Budget.(BudgetFetch); ok { + r, err := fb.HoldFetch(ctx, fmt.Sprintf("%s/%d", l.cfg.VolumeID, idx)) + if err != nil { + return false, fmt.Errorf("storage: chunk %d fetch slot: %w", idx, err) + } + release = r + } data, err := l.remote.Get(ctx, ref.Key) + release() if err != nil { return false, fmt.Errorf("storage: chunk %d fetch: %w", idx, err) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d1ee250300..07806f3346 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -509,7 +509,7 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, waiting for one when all are held (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. **Waiting (timer cuts).** A timer cut waiting for a slot holds a ticket: a file in `tickets/` named by its due time on the host monotonic clock, locked while it waits; it is taken by create, lock, and a re-check that the path still names the locked file. It is admitted only when no earlier ticket is live: an earlier ticket whose lock can be taken (its process exited) is removed by lock, re-check, unlink, unlock; a live one is passed only after the waiter has seen it stay ahead for 2 s of time with a normal slot free and no urgent work pending, summed across polls (a busy period pauses the count; the skip rule; it can be wrong about a slow holder: ticket order is fairness only, the slot lock is the exclusion). Only the earliest live earlier ticket not yet judged stalled is observed; a process keeps its judgement, for its later tickets too, until that ticket's file disappears, so one stalled ticket costs one skip, not one per hand-off. Admission consumes the ticket; a success elsewhere, fencing, Close, exit, not attempting (backoff, spacing, reconciling), or a refusal that waiting cannot fix drop it (the reason is reported). A refusal for held slots, pending urgent work, an earlier ticket or a held configuration lock is a wait. A timer cut that meets another capture holding the capture lock waits for it and is then skipped (that capture restarted the timer); while it waits, other waiters judge its ticket stalled after the skip time, once. @@ -1003,6 +1003,7 @@ Notes: | `INV-HOST-CUT-BUDGET-RESERVE-001` | Each admitted slot, urgent included, carries at most PayloadBytes of cut payload and at most COWBytes of COW side bytes; a reservation beyond COWBytes revokes the slot and aborts its cut. | M7 admitted | `core/hostlimit/limiter.go` `Admit`, `ReserveCOW`; `core/storage/chunk_cut_budget.go` | `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | `HostBudget` PayloadBound/SpillBound | ACTIVE | | `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE | | `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE | +| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only. With all held it waits, never refused: blocked on its hash slot and taking any other slot that frees within one retry interval; its context bounds the wait, and a slot got after that is released at once. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `fetchSlot`; `core/hostlimit/lock_unix.go`, `lock_windows.go` `lockBlocking`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossProcesses`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | | `INV-HOST-CUT-BUDGET-CONFIG-001` | A busy configuration lock or a mismatched pool configuration refuses every class, urgent included, with no fallback. | M7 free → admitted (refused) | `core/hostlimit/limiter.go` `pool`, `Admit` | `TestConfigurationLockContentionRefusesAllClasses` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | | `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on a per-process fallback that claims no host-wide bound, leaves uploads unpaced while only fallback leases live, and is reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestUrgentFallbackUploadIsNotPaced`, `TestFallbackDoesNotUnpaceAHealthyLease`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE | | `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index ac30ee239d..d752836b95 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -13,6 +13,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released. chunk compared, staged or uploaded), instead of at a fixed 5 minutes of age. `--host-limit-max-hold` is kept as a deprecated alias of the new flag. The window must exceed one chunk's send time at the paced rate per held slot. +- With the limiter on, chunk fetches are capped per host: `--host-limit-fetch-slots` (default 64) fetches in flight + across the host's processes, so a mass move puts at most that many in flight. A read of an absent chunk waits for a + slot (bounded by its read-miss timeout), and is never refused. + ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was created with, and v1.1's differ. Upgrade such a host whole: stop every process using the directory, remove From b51e59711f134dd039dce2190ed98bc2b7b1469e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:03:14 -0800 Subject: [PATCH 13/51] storage: a v1.1 commit settles by its change, not whole chunk maps On the v1.1 format an unresolved commit is found landed by sameProposalByChange over its change set and the captured chunks it left as they were (commitMarks), kept beside the pending change set; the v1.0 format and the no-op cut keep the full comparison. A landed commit whose reply was lost settles although an index it neither changed nor captured differs. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 77 +++++++++++++++---- .../storage/chunk_proposal_by_change_test.go | 33 ++++++++ 2 files changed, 93 insertions(+), 17 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 1d9b832939..718bc4d0c5 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -162,7 +162,10 @@ type chunkLayerImpl struct { // SAME changes at the same base, never a recomputed set. Owned: nothing // writes it after the commit that made it. pendingChanges map[uint64]*chunkRef - pendingCut chunkCutResult + // pendingMarked is that commit's equal-marked set (commitMarks): with + // pendingChanges, what a settlement compares to decide it landed. + pendingMarked map[uint64]*chunkRef + pendingCut chunkCutResult // pendingBase is the version the unresolved CAS expected. While HEAD is // still at it, that CAS may still land, so a read alone never settles it. pendingBase chunkHeadVersion @@ -1510,6 +1513,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // built once from the captured chunks, for the check, the CAS and an // unresolved commit's settlement alike (nil: the full commit). changes := l.commitChanges(next, changed) + marked := commitMarks(next, captured, capturedVersions, changes) // A lookup failure writes nothing and leaves the session open; the dirty // set returns for the next cut. // ManifestNs is the manifest work of the commit check only: the check @@ -1560,7 +1564,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.pending = &p l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = detach, chunkCutResult{H: h, FullHash: all}, expected, false l.pendingCaptured = pendingCapture(captured, capturedVersions) - l.pendingChanges = changes + l.pendingChanges, l.pendingMarked = changes, marked l.stMu.Unlock() // The session stays open: the commit may still land, and the // settlement replays it in the same session (resolvePending). @@ -1576,19 +1580,20 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch keepPending() return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, gerr) } - if !sameProposal(cur, next) && l.publicationOwnerChanged(cur) { + landedNext := proposalLanded(cur, next, expected.Gen, changes, marked) + if !landedNext && l.publicationOwnerChanged(cur) { keepPending() // Close must keep these roots as well. l.fencePublication(cur) return chunkCutResult{}, errors.Join(errChunkLayerFenced, casErr) } - if !errors.Is(casErr, errChunkHeadPrecondition) && !sameProposal(cur, next) && cur.Gen == expected.Gen && cur.Epoch == expected.Epoch { + if !errors.Is(casErr, errChunkHeadPrecondition) && !landedNext && cur.Gen == expected.Gen && cur.Epoch == expected.Epoch { // HEAD is still the CAS's base and the server gave no definite // refusal: the CAS may still land. Settle it before any later // capture or durability point (resolvePending re-proposes it). keepPending() return chunkCutResult{}, fmt.Errorf("storage: capture CAS outcome unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) } - if sameProposal(cur, next) { + if landedNext { st.CASResult = "resolved-by-reread" finishCapturedCut(cur, h, changed, newKeys) l.shadowCommit(captured, capturedVersions) @@ -1652,6 +1657,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle } l.stMu.Lock() fenced, pending, isDetach, base := l.fenced, l.pending, l.pendingDetach, l.pendingBase + changes, marked := l.pendingChanges, l.pendingMarked baseHead := copyHead(l.head) l.stMu.Unlock() if fenced { @@ -1666,7 +1672,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle if err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err) } - if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { if err := l.admit(); err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err) } @@ -1685,11 +1691,11 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle return detachFenced, chunkCutResult{}, nil } else if cur, err = readChunkHead(ctx, l.remote); err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) - } else if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + } else if !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) } } - if !sameProposal(cur, *pending) && l.publicationOwnerChanged(cur) { + if !proposalLanded(cur, *pending, base.Gen, changes, marked) && l.publicationOwnerChanged(cur) { l.fencePublication(cur) return detachFenced, chunkCutResult{}, nil } @@ -1701,9 +1707,9 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.pending = nil l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false landed := l.pendingCaptured - l.pendingCaptured, l.pendingChanges = nil, nil + l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil switch { - case sameProposal(cur, *pending): + case proposalLanded(cur, *pending, base.Gen, changes, marked): l.noteSettled(l.head, cur) l.setHeadLocked(copyHead(cur)) l.remoteLSN = cur.RemoteLSN @@ -1879,6 +1885,43 @@ func (l *chunkLayerImpl) commitChanges(next chunkHead, changed []uint64) map[uin return out } +// commitMarks is a commit by change's equal-marked set: each captured chunk +// the change leaves as it was, with the reference the proposal names there +// (nil: nothing, a zero chunk equal to an absent base). nil when the layer +// commits in full (changes nil). Every index in it is one the full +// comparison also compares. +func commitMarks(next chunkHead, captured []capturedChunk, versions map[uint64]uint64, changes map[uint64]*chunkRef) map[uint64]*chunkRef { + if changes == nil { + return nil + } + out := make(map[uint64]*chunkRef) + for _, c := range captured { + if _, ok := versions[c.idx]; !ok { + continue + } + if _, ok := changes[c.idx]; ok { + continue + } + if ref, ok := next.Chunks[c.idx]; ok { + r := ref + out[c.idx] = &r + } else { + out[c.idx] = nil + } + } + return out +} + +// proposalLanded reports whether HEAD cur is the proposal next made at base +// generation baseGen: by change (sameProposalByChange, O(changed + marked)) +// when the commit went by change, else the full comparison. +func proposalLanded(cur, next chunkHead, baseGen uint64, changes, marked map[uint64]*chunkRef) bool { + if changes == nil { + return sameProposal(cur, next) + } + return sameProposalByChange(cur, next, baseGen, func(i uint64) (chunkRef, bool) { r, ok := cur.Chunks[i]; return r, ok }, changes, marked) +} + func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { // Registered before the state unlock, so invalidation runs without stMu. defer func() { @@ -1887,7 +1930,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { } }() l.stMu.Lock() - pending, base, aborted, changes := l.pending, l.pendingBase, l.pendingAborted, l.pendingChanges + pending, base, aborted, changes, marked := l.pending, l.pendingBase, l.pendingAborted, l.pendingChanges, l.pendingMarked l.stMu.Unlock() if pending == nil { return nil @@ -1896,7 +1939,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) } - if !aborted && !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if !aborted && !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { // HEAD is still the unresolved CAS's base, so that CAS may still // land. Settle it by issuing the same proposal at the same base: // whichever lands first, HEAD ends at this proposal and the other @@ -1919,11 +1962,11 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { return errChunkLayerFenced } else if cur, err = readChunkHead(ctx, l.remote); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) - } else if !sameProposal(cur, *pending) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + } else if !proposalLanded(cur, *pending, base.Gen, changes, marked) && !l.publicationOwnerChanged(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) } } - if !sameProposal(cur, *pending) && l.publicationOwnerChanged(cur) { + if !proposalLanded(cur, *pending, base.Gen, changes, marked) && l.publicationOwnerChanged(cur) { l.fencePublication(cur) return errChunkLayerFenced } @@ -1938,9 +1981,9 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { wasDetach, cut := l.pendingDetach, l.pendingCut l.pendingDetach, l.pendingCut, l.pendingBase, l.pendingAborted = false, chunkCutResult{}, chunkHeadVersion{}, false landed := l.pendingCaptured - l.pendingCaptured, l.pendingChanges = nil, nil + l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil switch { - case sameProposal(cur, *pending): + case proposalLanded(cur, *pending, base.Gen, changes, marked): l.noteSettled(l.head, cur) l.setHeadLocked(copyHead(cur)) l.remoteLSN = cur.RemoteLSN @@ -2284,7 +2327,7 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n l.noteSettled(l.head, head) l.setHeadChangedLocked(copyHead(head), changed) l.remoteLSN, l.pending = h, nil - l.pendingCaptured, l.pendingChanges = nil, nil + l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil l.reusable = nil l.inflight = map[uint64]bool{} l.hdr = chunkBitmapHeader{BaseLSN: h, HeadGen: head.Gen, Epoch: head.Epoch, Base: chunkBaseNone} diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index 6a9c5ea534..c6f8d40000 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -77,3 +77,36 @@ func TestSameProposalByChange(t *testing.T) { t.Fatal("a zero chunk marked equal to an absent base: cur naming a reference is found landed") } } + +// On the v1.1 format a commit whose reply was lost settles by change: HEAD +// names the cut's change and its marks, so it landed, although an index the +// cut neither changed nor captured names something else there (that index +// is not part of this proposal). The full comparison would call it a HEAD +// that moved past the commit and refuse the cut. +func TestV11LostCommitReplySettlesByChange(t *testing.T) { + withV11Format(t) + s, _ := v11Store(t) + f := newFakeChunkRemote() + l := v11Attach(t, s, f) + w := newWriteLog() + w.write(t, s, 2*ctChunkBlocks, 0x22) + w.write(t, s, 9*ctChunkBlocks, 0x99) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if !l.commitByChange() { + t.Fatal("setup: the layer does not commit by change") + } + w.write(t, s, 2*ctChunkBlocks, 0x23) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.afterCAS = func(f *fakeChunkRemote) { f.head.Chunks[9] = f.head.Chunks[2] } + f.mu.Unlock() + res, err := l.Cut(ctTimeout(t)) + if err != nil { + t.Fatalf("a landed commit by change whose reply was lost: %v", err) + } + if res.Head.Chunks[9] != res.Head.Chunks[2] { + t.Fatal("the settled HEAD is not the one read back") + } +} From 2d2e05ba433f603b22892787c59d10435cd529ec Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:11:54 -0800 Subject: [PATCH 14/51] hostlimit: red tests, fetch config check, ended waits and handoff cancel - A fetch-only start must publish and check the host configuration: a child process with FetchSlots 2 fetches first, and a FetchSlots 1 fetch must answer ErrConfig (fails: no configuration is published). - Waits that end at their deadline, or by taking another slot, must leave no goroutine or descriptor behind while their slot stays held (fails: 40 blocked lock waits remain). - A context that ends as a slot is taken must get its error, slot given back (fails: the slot is handed over). Seam: testFetchLocked. - Controls: a killed child's slot is freed; a waiter passed by others ends by its deadline (the waiting is unordered, bounded by the context). - The same-process cap test is renamed AcrossLimiters; holdAsync joins and releases its wait in cleanup. Co-Authored-By: Claude Opus 5.5 --- .../core/hostlimit/fetch_review_test.go | 269 ++++++++++++++++++ seaweed-block/core/hostlimit/fetch_test.go | 33 ++- seaweed-block/core/hostlimit/limiter.go | 1 + 3 files changed, 299 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/hostlimit/fetch_review_test.go diff --git a/seaweed-block/core/hostlimit/fetch_review_test.go b/seaweed-block/core/hostlimit/fetch_review_test.go new file mode 100644 index 0000000000..08365d475d --- /dev/null +++ b/seaweed-block/core/hostlimit/fetch_review_test.go @@ -0,0 +1,269 @@ +package hostlimit + +import ( + "bufio" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +// TestFetchProcessHelper is a child process for the fetch tests: it holds one +// fetch slot of the pool in SWBLOCK_TEST_FETCH_DIR, with FetchSlots from +// SWBLOCK_TEST_FETCH_SLOTS, prints HELD, and holds it until stdin closes or +// it is killed. It makes no cut admission, so nothing but the fetch +// initialises the pool. +func TestFetchProcessHelper(t *testing.T) { + dir := os.Getenv("SWBLOCK_TEST_FETCH_DIR") + if dir == "" { + return + } + c := DefaultConfig(dir) + c.NormalSlots = 1 + c.UrgentSlots = 1 + n, err := strconv.Atoi(os.Getenv("SWBLOCK_TEST_FETCH_SLOTS")) + if err != nil { + t.Fatal(err) + } + c.FetchSlots = n + l, err := New(c) + if err != nil { + t.Fatal(err) + } + if _, err := l.HoldFetch(context.Background(), "v/child"); err != nil { + t.Fatal(err) + } + fmt.Println("HELD") + _, _ = bufio.NewReader(os.Stdin).ReadByte() +} + +// fetchChild starts a child process holding one fetch slot of dir's pool and +// waits until it holds it. The test's cleanup kills it. +func fetchChild(t *testing.T, dir string, slots int) *exec.Cmd { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestFetchProcessHelper$") + cmd.Env = append(os.Environ(), "SWBLOCK_TEST_FETCH_DIR="+dir, "SWBLOCK_TEST_FETCH_SLOTS="+strconv.Itoa(slots)) + out, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + in, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = in.Close(); _ = cmd.Process.Kill(); _ = cmd.Wait() }) + ready := make(chan bool, 1) + go func() { + s := bufio.NewScanner(out) + for s.Scan() { + if s.Text() == "HELD" { + ready <- true + return + } + } + ready <- false + }() + select { + case ok := <-ready: + if !ok { + t.Fatal("the fetch child failed before holding a slot") + } + case <-time.After(15 * time.Second): + t.Fatal("the fetch child never held a slot") + } + return cmd +} + +// A fetch-only start publishes the host's configuration and checks it, as a +// cut admission does: a second process with another FetchSlots is refused +// with ErrConfig on its first fetch, never let in with a cap of its own. +func TestHoldFetchFirstFetchChecksTheHostConfiguration(t *testing.T) { + c := fetchConfig(t, 1) + fetchChild(t, c.Directory, 2) // publishes FetchSlots 2 by its fetch alone + if _, err := os.Stat(filepath.Join(c.Directory, "configuration.json")); err != nil { + t.Fatalf("a fetch-only start published no configuration: %v", err) + } + l := newTest(t, c) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + r, err := l.HoldFetch(ctx, keyOnSlot(t, 1, 2)) + if r != nil { + r() + } + if !errors.Is(err, ErrConfig) { + t.Fatalf("a fetch with FetchSlots 1 beside a process with 2 answered %v, want ErrConfig", err) + } +} + +// A fetch slot dies with its process: a killed holder's slot is taken by a +// waiter in another process. +func TestHoldFetchSlotDiesWithItsProcess(t *testing.T) { + c := fetchConfig(t, 1) + child := fetchChild(t, c.Directory, 1) + l := newTest(t, c) + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + if r, err := l.HoldFetch(ctx, "v/parent"); !errors.Is(err, context.DeadlineExceeded) { + if r != nil { + r() + } + t.Fatalf("a fetch beside a live holder of the only slot answered %v, want its deadline", err) + } + _ = child.Process.Kill() + _ = child.Wait() + ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel2() + r, err := l.HoldFetch(ctx2, "v/parent") + if err != nil { + t.Fatalf("the killed holder's slot was not freed: %v", err) + } + r() +} + +// openFDs counts the process's open descriptors where the platform lists +// them (-1 elsewhere). +func openFDs() int { + if runtime.GOOS != "linux" { + return -1 + } + es, err := os.ReadDir("/proc/self/fd") + if err != nil { + return -1 + } + return len(es) +} + +// settlesTo waits up to a bound for the goroutine (and, on Linux, descriptor) +// count to come back to the baseline plus slack. +func settlesTo(t *testing.T, what string, goroutines, fds int) { + t.Helper() + const slack = 3 + deadline := time.Now().Add(time.Second) + for { + g, f := runtime.NumGoroutine(), openFDs() + if g <= goroutines+slack && (fds < 0 || f <= fds+slack) { + return + } + if time.Now().After(deadline) { + t.Fatalf("after %s: %d goroutines (baseline %d), %d descriptors (baseline %d): fetch waits left work behind", what, g, goroutines, f, fds) + } + time.Sleep(10 * time.Millisecond) + } +} + +// Waits that end (at their deadline, or by taking another slot) leave nothing +// running and nothing open while the slot they waited on stays held. +func TestHoldFetchEndedWaitsLeaveNothingBehind(t *testing.T) { + c := fetchConfig(t, 2) + homeHolder, otherHolder, w := newTest(t, c), newTest(t, c), newTest(t, c) + key := keyOnSlot(t, 0, 2) + rHome := mustHold(t, homeHolder, key) // held for the whole test + defer rHome() + rOther := mustHold(t, otherHolder, keyOnSlot(t, 1, 2)) + g0, f0 := runtime.NumGoroutine(), openFDs() + for i := 0; i < 20; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + r, err := w.HoldFetch(ctx, key) + cancel() + if r != nil { + r() + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("wait %d with both slots held answered %v, want its deadline", i, err) + } + } + settlesTo(t, "20 waits ended at their deadline", g0, f0) + rOther() + for i := 0; i < 20; i++ { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + r, err := w.HoldFetch(ctx, key) + cancel() + if err != nil { + t.Fatalf("fetch %d with the other slot free: %v", i, err) + } + r() + } + settlesTo(t, "20 fetches that took the other slot", g0, f0) +} + +// A context that ends as a slot is taken gets its context's error, and the +// slot is given back: no fetch holds a slot past its context. +func TestHoldFetchCancelledAtTheHandoffHoldsNothing(t *testing.T) { + c := fetchConfig(t, 1) + w, later := newTest(t, c), newTest(t, c) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w.testFetchLocked = cancel + r, err := w.HoldFetch(ctx, "v/w") + if r != nil { + r() + } + if !errors.Is(err, context.Canceled) { + t.Fatalf("a fetch cancelled as it took its slot answered %v, want its context's error", err) + } + ctx2, cancel2 := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel2() + r2, err := later.HoldFetch(ctx2, "v/later") + if err != nil { + t.Fatalf("the slot a cancelled fetch took was kept: %v", err) + } + r2() +} + +// The waiting is unordered (a waiter can be passed by other fetches), and +// bounded by the waiter's own context: with others taking and giving back +// the only slot all along, a waiter ends by its deadline, with a slot or with +// its deadline's error. +func TestHoldFetchAPassedWaiterEndsByItsDeadline(t *testing.T) { + c := fetchConfig(t, 1) + stop := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < 4; i++ { + l := newTest(t, c) + wg.Add(1) + go func(i int) { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + r, err := l.HoldFetch(ctx, fmt.Sprintf("v/c%d", i)) + cancel() + if err == nil { + time.Sleep(5 * time.Millisecond) + r() + } + } + }(i) + } + defer func() { close(stop); wg.Wait() }() + w := newTest(t, c) + const deadline = 150 * time.Millisecond + ctx, cancel := context.WithTimeout(context.Background(), deadline) + defer cancel() + start := time.Now() + r, err := w.HoldFetch(ctx, "v/w") + took := time.Since(start) + if r != nil { + r() + } + if err != nil && !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("a passed waiter answered %v, want a slot or its deadline", err) + } + if took > deadline+250*time.Millisecond { + t.Fatalf("a waiter with a %s deadline returned after %s", deadline, took) + } +} diff --git a/seaweed-block/core/hostlimit/fetch_test.go b/seaweed-block/core/hostlimit/fetch_test.go index 143e02d451..aa2055a1ac 100644 --- a/seaweed-block/core/hostlimit/fetch_test.go +++ b/seaweed-block/core/hostlimit/fetch_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" "testing" "time" ) @@ -34,14 +35,37 @@ type held struct { } // holdAsync runs HoldFetch in the background; its result arrives on the -// channel. The test's cleanup releases a slot it got. +// channel. The test's cleanup ends the wait, joins it (bounded) and releases +// a slot it got, whether or not the test read the result. func holdAsync(t *testing.T, l *Limiter, ctx context.Context, key string) <-chan held { t.Helper() + ctx, cancel := context.WithCancel(ctx) got := make(chan held, 1) + done := make(chan struct{}) + var mu sync.Mutex + var release func() go func() { + defer close(done) r, err := l.HoldFetch(ctx, key) + mu.Lock() + release = r + mu.Unlock() got <- held{r, err} }() + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("a background fetch did not return after its context ended") + return + } + mu.Lock() + defer mu.Unlock() + if release != nil { + release() // releases are idempotent + } + }) return got } @@ -68,9 +92,10 @@ func TestHoldFetchTakesAFreeSlotAtOnce(t *testing.T) { } } -// The cap holds across processes: with every slot held by others, a fetch -// waits until one is released, and then takes it. -func TestHoldFetchCapHoldsAcrossProcesses(t *testing.T) { +// The cap holds across limiters on one pool (separate processes: see +// TestHoldFetchSlotDiesWithItsProcess): with every slot held by others, a +// fetch waits until one is released, and then takes it. +func TestHoldFetchCapHoldsAcrossLimiters(t *testing.T) { c := fetchConfig(t, 2) a, b, w := newTest(t, c), newTest(t, c), newTest(t, c) r1 := mustHold(t, a, keyOnSlot(t, 0, 2)) diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 9bb19dfa05..e6ec66517c 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -124,6 +124,7 @@ type Limiter struct { testExpireRace func() // tests: runs as a hold's expiry decides, under the limiter's lock testAfterTicketCreate func(string) // test-only: between a ticket's create and its lock testSkipAfter time.Duration // test-only TicketSkipAfter override + testFetchLocked func() // test-only: a fetch slot was just locked, before HoldFetch hands it over cfg Config // base is the limiter's monotonic origin: a hold's progress stamp is // time.Since(base), so the window never reads the wall clock. From ea127a0181b2de41abd53a387bb048089e2637ca Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:20:40 -0800 Subject: [PATCH 15/51] hostlimit: fetch waits are non-blocking, checked and bounded - A limiter's first fetch checks the host configuration under configuration.lock, publishing it when absent (configGuard, now shared with cut admission): a fetch-only process with other flags gets ErrConfig. - No blocking lock: with every slot held, one fetch per process polls every slot each 20 ms (the others wait for its turn, within their context). An ended wait leaves no lock request, descriptor or goroutine; lockBlocking is removed. - The waiting is unordered and bounded by the caller's context alone; the docs say so instead of promising a kernel queue. - A slot taken when the context has already ended is given back, with the context's error. - INV-HOST-FETCH-CAP-001, M7 and the v1.1 note state the contract. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/hostlimit/fetch.go | 187 +++++++++++-------- seaweed-block/core/hostlimit/limiter.go | 97 ++++++---- seaweed-block/core/hostlimit/lock_unix.go | 11 -- seaweed-block/core/hostlimit/lock_windows.go | 6 - seaweed-block/docs/design/invariants.md | 4 +- seaweed-block/docs/releases/v1.1.md | 3 +- 6 files changed, 178 insertions(+), 130 deletions(-) diff --git a/seaweed-block/core/hostlimit/fetch.go b/seaweed-block/core/hostlimit/fetch.go index d0dc83d554..45d37b0207 100644 --- a/seaweed-block/core/hostlimit/fetch.go +++ b/seaweed-block/core/hostlimit/fetch.go @@ -6,18 +6,16 @@ import ( "fmt" "hash/fnv" "os" - "path/filepath" "sync" "time" ) -// fetchRetry is how often a waiting fetch tries the other slots while it is -// blocked on its own: the host's slots are one pool, so a slot that frees -// elsewhere is taken within one interval. +// fetchRetry is how often a waiting fetch tries the slots again while every +// one is held. const fetchRetry = 20 * time.Millisecond -// fetchSlot is the fetch slot a key waits on when every slot is held: its -// hash, modulo the slot count. +// fetchSlot is the slot a key's tries start from: its hash, modulo the slot +// count, so concurrent fetches spread over the slots. func fetchSlot(key string, n int) int { h := fnv.New32a() _, _ = h.Write([]byte(key)) @@ -25,90 +23,125 @@ func fetchSlot(key string, n int) int { } // HoldFetch holds one of the host's FetchSlots fetch slots (files fetch-0 .. -// fetch-(N-1) in the pool, so the cap is per host and dies with its -// holders) for one chunk transfer; release gives it back. It never refuses: +// fetch-(N-1) in the pool, so the cap is per host and a slot dies with its +// holder) for one chunk transfer; release gives it back. It never refuses for +// want of a slot: // -// 1. it takes a free slot without waiting, trying from key's hash slot; -// 2. with every slot held, it blocks on its hash slot (the kernel queues the -// waiters) and, while blocked, tries the other slots every fetchRetry; -// whichever lock comes first is used and the other is released at once; -// 3. the wait is bounded by ctx: when it ends, HoldFetch returns ctx's error, -// and a lock the blocked wait gets after that is released at once. +// 1. a limiter's first fetch checks the host's configuration under +// configuration.lock, publishing it when absent, as a cut admission does: +// ErrConfig when another process uses other flags; +// 2. it takes a free slot without waiting, trying from key's hash slot; +// 3. with every slot held, it waits for its process's turn (one fetch per +// process polls) and then tries every slot each fetchRetry. The waiting +// is unordered, so other fetches can take a freed slot first; the wait is +// bounded by ctx alone and ends with ctx's error; +// 4. a slot taken when ctx has already ended is given back, and ctx's error +// returned. +// +// Every lock try is non-blocking, so a wait that ends leaves no lock request, +// descriptor or goroutine behind. func (l *Limiter) HoldFetch(ctx context.Context, key string) (func(), error) { if err := ctx.Err(); err != nil { return nil, err } - n := l.cfg.FetchSlots - home := fetchSlot(key, n) - open := func(i int) (*os.File, error) { - return os.OpenFile(filepath.Join(l.cfg.Directory, fmt.Sprintf("fetch-%d", i)), os.O_CREATE|os.O_RDWR, 0o600) + if err := l.checkFetchConfig(ctx); err != nil { + return nil, err } - // try takes a free slot among those try covers, without waiting; nil - // when every one is held. - try := func(skip int) (*os.File, error) { - for k := 0; k < n; k++ { - i := (home + k) % n - if i == skip { - continue - } - f, err := open(i) - if err != nil { - return nil, err - } - err = tryLock(f) - if err == nil { - return f, nil - } - _ = f.Close() - if !errors.Is(err, ErrBusy) { - return nil, err - } - } - return nil, nil + home := fetchSlot(key, l.cfg.FetchSlots) + f, err := l.tryFetch(home) + if f == nil && err == nil { + f, err = l.waitFetch(ctx, home) } - if f, err := try(-1); f != nil || err != nil { - if err != nil { - return nil, err - } - return releaseFetch(f), nil - } - homeF, err := open(home) if err != nil { return nil, err } - locked := make(chan error, 1) - go func() { locked <- lockBlocking(homeF) }() - // abandon releases the blocked wait's lock once it gets it. - abandon := func() { - go func() { - <-locked - _ = homeF.Close() - }() + if l.testFetchLocked != nil { + l.testFetchLocked() + } + if err := ctx.Err(); err != nil { + _ = f.Close() + return nil, err + } + return releaseFetch(f), nil +} + +// checkFetchConfig checks the host's configuration once per limiter. A +// configuration lock held past its bound by another admission is waited out +// within ctx; a mismatch is ErrConfig. +func (l *Limiter) checkFetchConfig(ctx context.Context) error { + if l.fetchChecked.Load() { + return nil + } + if err := l.checkPoolDir(); err != nil { + return err } - t := time.NewTicker(fetchRetry) - defer t.Stop() for { - select { - case err := <-locked: - if err != nil { - _ = homeF.Close() - return nil, err - } - return releaseFetch(homeF), nil - case <-ctx.Done(): - abandon() - return nil, ctx.Err() - case <-t.C: - f, err := try(home) - if err != nil { - abandon() - return nil, err - } - if f != nil { - abandon() - return releaseFetch(f), nil - } + guard, err := l.configGuard() + if err == nil { + _ = guard.Close() + l.fetchChecked.Store(true) + return nil } + if !errors.Is(err, ErrSlotsHeld) { + return err + } + if err := sleepCtx(ctx, fetchRetry); err != nil { + return err + } + } +} + +// tryFetch takes a free fetch slot without waiting, trying from home; nil +// when every slot is held. +func (l *Limiter) tryFetch(home int) (*os.File, error) { + n := l.cfg.FetchSlots + for k := 0; k < n; k++ { + f, err := l.poolFile(fmt.Sprintf("fetch-%d", (home+k)%n)) + if err != nil { + return nil, err + } + err = tryLock(f) + if err == nil { + return f, nil + } + _ = f.Close() + if !errors.Is(err, ErrBusy) { + return nil, err + } + } + return nil, nil +} + +// waitFetch waits for a fetch slot while every one is held: it takes its +// process's turn, so one fetch per process polls, and tries every slot each +// fetchRetry until one is free or ctx ends. +func (l *Limiter) waitFetch(ctx context.Context, home int) (*os.File, error) { + select { + case l.fetchTurn <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-l.fetchTurn }() + for { + f, err := l.tryFetch(home) + if f != nil || err != nil { + return f, err + } + if err := sleepCtx(ctx, fetchRetry); err != nil { + return nil, err + } + } +} + +// sleepCtx waits d, or until ctx ends (its error). +func sleepCtx(ctx context.Context, d time.Duration) error { + t := time.NewTimer(d) + defer t.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-t.C: + return nil } } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index e6ec66517c..d8c7f5086c 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -151,6 +151,12 @@ type Limiter struct { // by the skip rule. It is never taken with mu held, nor mu under it. skipMu sync.Mutex stalled map[string]bool + + // fetchChecked is set once a fetch has checked the host's configuration; + // fetchTurn (capacity 1) is held by the one fetch of this process that + // polls for a slot while every slot is held. + fetchChecked atomic.Bool + fetchTurn chan struct{} } func (l *Limiter) skipAfter() time.Duration { @@ -164,7 +170,7 @@ func New(c Config) (*Limiter, error) { if err := c.Validate(); err != nil { return nil, err } - l := &Limiter{cfg: c, base: time.Now(), live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{})} + l := &Limiter{cfg: c, base: time.Now(), live: map[uint64]*lease{}, wake: make(chan struct{}, 1), done: make(chan struct{}), fetchTurn: make(chan struct{}, 1)} go l.releaseLoop() return l, nil } @@ -182,20 +188,10 @@ func Phase(volume string, period time.Duration) time.Duration { // pool checks the immutable configuration under a separate OS lock. Slot files // are never unlinked: replacing them could create a second set of live permits. func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { - info, err := os.Lstat(l.cfg.Directory) - if err != nil { + if err := l.checkPoolDir(); err != nil { return nil, err } - if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { - return nil, errors.New("hostlimit: pool must be a local directory") - } - open := func(name string) (*os.File, error) { - path := filepath.Join(l.cfg.Directory, name) - if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() { - return nil, errors.New("hostlimit: nonregular pool file") - } - return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) - } + open := l.poolFile // A ticketed Normal admission first checks its place in the queue. The // ticket files synchronise through their own locks, so this runs outside // the configuration lock and does not lengthen it. @@ -204,30 +200,11 @@ func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { return nil, err } } - guard, err := open("configuration.lock") + guard, err := l.configGuard() if err != nil { return nil, err } defer guard.Close() - if l.testBeforeConfigLock != nil { - l.testBeforeConfigLock(guard) - } - if err = lockGuard(guard); err != nil { - return nil, err - } - expected, _ := json.Marshal(l.cfg) - path := filepath.Join(l.cfg.Directory, "configuration.json") - existing, err := os.ReadFile(path) - if errors.Is(err, os.ErrNotExist) { - err = l.publishConfig(path, expected) - existing = expected - } - if err != nil { - return nil, err - } - if string(existing) != string(expected) { - return nil, ErrConfig - } if c == Normal { // The probe is held until the slot try-lock below has been made, so // no Normal admission completes after urgent work became pending. @@ -280,6 +257,60 @@ func (l *Limiter) pool(c Class, t *Ticket) (*os.File, error) { return nil, ErrSlotsHeld } +// checkPoolDir refuses a pool that is not a local directory. +func (l *Limiter) checkPoolDir() error { + info, err := os.Lstat(l.cfg.Directory) + if err != nil { + return err + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return errors.New("hostlimit: pool must be a local directory") + } + return nil +} + +// poolFile opens (creating) a regular file of the pool. +func (l *Limiter) poolFile(name string) (*os.File, error) { + path := filepath.Join(l.cfg.Directory, name) + if i, e := os.Lstat(path); e == nil && !i.Mode().IsRegular() { + return nil, errors.New("hostlimit: nonregular pool file") + } + return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) +} + +// configGuard takes configuration.lock and, under it, checks the host's +// immutable configuration, publishing it when absent: ErrConfig when another +// process published other flags. The caller closes the guard, which releases +// the lock. +func (l *Limiter) configGuard() (*os.File, error) { + guard, err := l.poolFile("configuration.lock") + if err != nil { + return nil, err + } + if l.testBeforeConfigLock != nil { + l.testBeforeConfigLock(guard) + } + if err = lockGuard(guard); err != nil { + _ = guard.Close() + return nil, err + } + expected, _ := json.Marshal(l.cfg) + path := filepath.Join(l.cfg.Directory, "configuration.json") + existing, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + err = l.publishConfig(path, expected) + existing = expected + } + if err == nil && string(existing) != string(expected) { + err = ErrConfig + } + if err != nil { + _ = guard.Close() + return nil, err + } + return guard, nil +} + // guardWait bounds how long an admission waits for configuration.lock. // Another admission holds it only while it checks the configuration and // tries its slots. diff --git a/seaweed-block/core/hostlimit/lock_unix.go b/seaweed-block/core/hostlimit/lock_unix.go index 0c4959fd52..ea3d6c09f3 100644 --- a/seaweed-block/core/hostlimit/lock_unix.go +++ b/seaweed-block/core/hostlimit/lock_unix.go @@ -24,14 +24,3 @@ func tryLockShared(f *os.File) error { } return err } - -// lockBlocking takes an exclusive lock on f, waiting until it is free. It -// cannot be cancelled: a caller that stops waiting closes f once it returns. -func lockBlocking(f *os.File) error { - for { - err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX) - if !errors.Is(err, syscall.EINTR) { - return err - } - } -} diff --git a/seaweed-block/core/hostlimit/lock_windows.go b/seaweed-block/core/hostlimit/lock_windows.go index c3aa7ed6d4..3870ad922c 100644 --- a/seaweed-block/core/hostlimit/lock_windows.go +++ b/seaweed-block/core/hostlimit/lock_windows.go @@ -24,9 +24,3 @@ func tryLockShared(f *os.File) error { } return err } - -// lockBlocking takes an exclusive lock on f, waiting until it is free. It -// cannot be cancelled: a caller that stops waiting closes f once it returns. -func lockBlocking(f *os.File) error { - return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &windows.Overlapped{}) -} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 07806f3346..5f715d47af 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -509,7 +509,7 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, waiting for one when all are held (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. **Waiting (timer cuts).** A timer cut waiting for a slot holds a ticket: a file in `tickets/` named by its due time on the host monotonic clock, locked while it waits; it is taken by create, lock, and a re-check that the path still names the locked file. It is admitted only when no earlier ticket is live: an earlier ticket whose lock can be taken (its process exited) is removed by lock, re-check, unlink, unlock; a live one is passed only after the waiter has seen it stay ahead for 2 s of time with a normal slot free and no urgent work pending, summed across polls (a busy period pauses the count; the skip rule; it can be wrong about a slow holder: ticket order is fairness only, the slot lock is the exclusion). Only the earliest live earlier ticket not yet judged stalled is observed; a process keeps its judgement, for its later tickets too, until that ticket's file disappears, so one stalled ticket costs one skip, not one per hand-off. Admission consumes the ticket; a success elsewhere, fencing, Close, exit, not attempting (backoff, spacing, reconciling), or a refusal that waiting cannot fix drop it (the reason is reported). A refusal for held slots, pending urgent work, an earlier ticket or a held configuration lock is a wait. A timer cut that meets another capture holding the capture lock waits for it and is then skipped (that capture restarted the timer); while it waits, other waiters judge its ticket stalled after the skip time, once. @@ -1003,7 +1003,7 @@ Notes: | `INV-HOST-CUT-BUDGET-RESERVE-001` | Each admitted slot, urgent included, carries at most PayloadBytes of cut payload and at most COWBytes of COW side bytes; a reservation beyond COWBytes revokes the slot and aborts its cut. | M7 admitted | `core/hostlimit/limiter.go` `Admit`, `ReserveCOW`; `core/storage/chunk_cut_budget.go` | `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | `HostBudget` PayloadBound/SpillBound | ACTIVE | | `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE | | `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE | -| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only. With all held it waits, never refused: blocked on its hash slot and taking any other slot that frees within one retry interval; its context bounds the wait, and a slot got after that is released at once. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `fetchSlot`; `core/hostlimit/lock_unix.go`, `lock_windows.go` `lockBlocking`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossProcesses`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | +| `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only; a limiter's first fetch checks the host configuration (ErrConfig on a mismatch). With all held it waits, never refused: unordered, bounded by its context alone. Only non-blocking tries: an ended wait leaves nothing. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `checkFetchConfig`, `waitFetch`; `core/hostlimit/limiter.go` `configGuard`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossLimiters`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestHoldFetchFirstFetchChecksTheHostConfiguration`, `TestHoldFetchSlotDiesWithItsProcess`, `TestHoldFetchEndedWaitsLeaveNothingBehind`, `TestHoldFetchCancelledAtTheHandoffHoldsNothing`, `TestHoldFetchAPassedWaiterEndsByItsDeadline` (`core/hostlimit/fetch_review_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | | `INV-HOST-CUT-BUDGET-CONFIG-001` | A busy configuration lock or a mismatched pool configuration refuses every class, urgent included, with no fallback. | M7 free → admitted (refused) | `core/hostlimit/limiter.go` `pool`, `Admit` | `TestConfigurationLockContentionRefusesAllClasses` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | | `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on a per-process fallback that claims no host-wide bound, leaves uploads unpaced while only fallback leases live, and is reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestUrgentFallbackUploadIsNotPaced`, `TestFallbackDoesNotUnpaceAHealthyLease`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE | | `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index d752836b95..044a5550d7 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -15,7 +15,8 @@ These notes collect v1.1's changes as they land; v1.1 is not released. - With the limiter on, chunk fetches are capped per host: `--host-limit-fetch-slots` (default 64) fetches in flight across the host's processes, so a mass move puts at most that many in flight. A read of an absent chunk waits for a - slot (bounded by its read-miss timeout), and is never refused. + slot, in no set order and bounded by its read-miss timeout, and is never refused. A process's first fetch checks the + host's `configuration.json` as a cut admission does, so a fetch-only process with other flags is refused too. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was From 1febcbcedb9aa21f87102a46e5406c492f5437ed Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:15:00 -0800 Subject: [PATCH 16/51] authority: a per-volume line index; a call reconciles only its volume's bindings The publisher indexes its lines by volume, kept by the one writer of its state, so every per-volume read (the workspace line, the authority line, the bound replica, the published epoch, the promotion basis) costs the volume's replicas, not every line. A register, ACK or move reconciles the bindings of its own volume and of any volume whose reconcile failed before; the start still reconciles every volume. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 50 +++++++-- .../core/authority/line_index_test.go | 102 ++++++++++++++++++ seaweed-block/core/authority/policy.go | 2 +- seaweed-block/core/authority/workspace.go | 4 +- seaweed-block/core/host/master/host.go | 5 +- .../core/host/master/workspace_binding.go | 65 +++++++---- .../master/workspace_binding_call_test.go | 66 ++++++++++++ .../core/host/master/workspace_service.go | 4 +- 8 files changed, 267 insertions(+), 31 deletions(-) create mode 100644 seaweed-block/core/authority/line_index_test.go create mode 100644 seaweed-block/core/host/master/workspace_binding_call_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 30cafb9342..b4038436f0 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -127,7 +127,11 @@ type Publisher struct { mu sync.Mutex state map[subKey]assignmentState - subs map[subKey][]*subscription + // replicas indexes state by volume: the replica ids of every key of + // that volume. Kept by setStateLocked, the only writer of state, so a + // per-volume read costs that volume's replicas, not every line. + replicas map[string]map[string]struct{} + subs map[subKey][]*subscription // P14 S5 — durable authority store. Optional; nil means // in-memory only (existing behavior, used by tests and @@ -248,6 +252,7 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { p := &Publisher{ dir: dir, state: make(map[subKey]assignmentState), + replicas: map[string]map[string]struct{}{}, subs: make(map[subKey][]*subscription), writeSeqByVolume: map[string]uint64{}, workspace: map[string]*WorkspaceState{}, @@ -301,7 +306,7 @@ func (p *Publisher) reloadFromStore() { loaded.info.Primary = *rec.Primary } p.captureAssignmentOwner(&loaded.info, rec.Workspace) - p.state[key] = loaded + p.setStateLocked(key, loaded) if rec.WriteSeq > p.writeSeqByVolume[rec.VolumeID] { p.writeSeqByVolume[rec.VolumeID] = rec.WriteSeq } @@ -556,7 +561,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // any slot of the volume holds an authority line, a Bind for // another slot would mint a second epoch-1 line beside it. // Moving authority to another slot is IntentReassign. - if bound, ok := boundReplicaForVolume(p.state, ask.VolumeID); ok { + if bound, ok := boundReplicaForVolume(p.volumeStateLocked(ask.VolumeID), ask.VolumeID); ok { p.mu.Unlock() return fmt.Errorf("%w: volume %s is already bound to replica %s; use Reassign", ErrBindAlreadyBound, ask.VolumeID, bound) @@ -625,7 +630,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // establishment is the IntentBind path, not this one — // using Reassign to create a volume's very first binding // would confuse the per-volume monotonic line. - maxEpoch := maxPublishedEpochForVolume(p.state, ask.VolumeID) + maxEpoch := maxPublishedEpochForVolume(p.volumeStateLocked(ask.VolumeID), ask.VolumeID) if maxEpoch == 0 { p.mu.Unlock() return ErrReassignNotBound @@ -661,7 +666,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr // planned (after the planned-move guard, no fence), or heal (the // line's own primary, at this epoch). No path mints one without. if ask.Evidence.Kind == adapter.PrimaryKindPromotion { - if err := promotionBasisHolds(ask, next.Epoch, p.state, maxEpoch); err != nil { + if err := promotionBasisHolds(ask, next.Epoch, p.volumeStateLocked(ask.VolumeID), maxEpoch); err != nil { p.mu.Unlock() return fmt.Errorf("%w: volume %s replica %s: %v", ErrPromotionUnfenced, ask.VolumeID, ask.ReplicaID, err) } @@ -726,7 +731,7 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr p.workspace[ask.VolumeID] = issuedWorkspace } - p.state[k] = assignmentState{info: next, present: true} + p.setStateLocked(k, assignmentState{info: next, present: true}) if issuedWorkspace != nil { // The issued move starts the new holder's lease (issuedAt+TTL grant). p.publishIssuedLeaseLocked(ask.VolumeID, issuedAt.Add(p.workspaceTTL)) @@ -754,6 +759,39 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr return nil } +// setStateLocked records the state of key k and indexes it under its +// volume. It is the only writer of p.state. p.mu held. +func (p *Publisher) setStateLocked(k subKey, st assignmentState) { + p.state[k] = st + r := p.replicas[k.volumeID] + if r == nil { + r = map[string]struct{}{} + p.replicas[k.volumeID] = r + } + r[k.replicaID] = struct{}{} +} + +// volumeStateLocked is the state of every key of one volume, read through +// the index: O(replicas of the volume), whatever the number of volumes. +// p.mu held. +func (p *Publisher) volumeStateLocked(volumeID string) map[subKey]assignmentState { + out := make(map[subKey]assignmentState, len(p.replicas[volumeID])) + for r := range p.replicas[volumeID] { + k := subKey{volumeID: volumeID, replicaID: r} + if st, ok := p.state[k]; ok { + out[k] = st + } + } + if check := testLineIndexCheck; check != nil { + check(p, volumeID, out) + } + return out +} + +// testLineIndexCheck, set by tests, is called with every per-volume read +// of the index, so the package's tests check the index against the scan. +var testLineIndexCheck func(p *Publisher, volumeID string, got map[subKey]assignmentState) + func safeInvokePublishObserver(observer func(PublishEvent), event PublishEvent) { defer func() { _ = recover() diff --git a/seaweed-block/core/authority/line_index_test.go b/seaweed-block/core/authority/line_index_test.go new file mode 100644 index 0000000000..725fbb80c3 --- /dev/null +++ b/seaweed-block/core/authority/line_index_test.go @@ -0,0 +1,102 @@ +package authority + +import ( + "fmt" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/adapter" +) + +// Every per-volume read of the line index, in every test of this package, +// equals a scan of the whole state restricted to that volume. +func init() { + testLineIndexCheck = func(p *Publisher, volumeID string, got map[subKey]assignmentState) { + want := map[subKey]assignmentState{} + for k, st := range p.state { + if k.volumeID == volumeID { + want[k] = st + } + } + if !reflect.DeepEqual(got, want) { + panic(fmt.Sprintf("authority: line index for volume %q holds %v, the scan %v", volumeID, got, want)) + } + } +} + +// A per-volume authority read costs that volume's replicas, not every +// line: reading one volume among 64,000 takes about as long as among +// 1,000 (the scan it replaces grows 64 times). +func TestVolumeAuthorityLineCostIsPerVolume(t *testing.T) { + saved := testLineIndexCheck + testLineIndexCheck = nil // the check itself scans; time the read alone + t.Cleanup(func() { testLineIndexCheck = saved }) + perRead := func(volumes int) time.Duration { + p := NewPublisher(nil) + p.mu.Lock() + for i := 0; i < volumes; i++ { + for _, r := range []string{"r1", "r2"} { + p.setStateLocked(subKey{volumeID: fmt.Sprintf("v%06d", i), replicaID: r}, assignmentState{info: adapter.AssignmentInfo{VolumeID: fmt.Sprintf("v%06d", i), ReplicaID: r, Epoch: 1}, present: true}) + } + } + p.mu.Unlock() + const reads = 2000 + best := time.Duration(1 << 62) + for round := 0; round < 3; round++ { + start := time.Now() + for i := 0; i < reads; i++ { + if _, ok := p.VolumeAuthorityLine(fmt.Sprintf("v%06d", i%volumes)); !ok { + t.Fatal("no line") + } + } + if d := time.Since(start) / reads; d < best { + best = d + } + } + return best + } + small, large := perRead(1000), perRead(64000) + t.Logf("per read: %v at 1,000 volumes, %v at 64,000", small, large) + if large > 8*small+5*time.Microsecond { + t.Fatalf("a read among 64,000 volumes took %v, among 1,000 %v: the read scans every line", large, small) + } +} + +// The index is right only while setStateLocked is the one writer of +// p.state: a source scan of the package's non-test files finds every +// assignment to, delete from or replacement of the state map, and fails on +// any outside it (a new writer must keep the index too). +func TestLineIndexHasOneWriter(t *testing.T) { + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + write := regexp.MustCompile(`\bp\.state\[[^\]]*\]\s*=[^=]|\bdelete\(p\.state,|\bp\.state\s*=[^=]`) + var sites []string + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + inSetter := false + for i, line := range strings.Split(string(b), "\n") { + if strings.HasPrefix(line, "func ") { + inSetter = strings.HasPrefix(line, "func (p *Publisher) setStateLocked(") + } + if write.MatchString(line) && !inSetter { + sites = append(sites, fmt.Sprintf("%s:%d: %s", f, i+1, strings.TrimSpace(line))) + } + } + } + if len(sites) != 0 { + t.Fatalf("p.state is written outside setStateLocked, which keeps the line index:\n%s", strings.Join(sites, "\n")) + } +} diff --git a/seaweed-block/core/authority/policy.go b/seaweed-block/core/authority/policy.go index cdf0c14232..11fab3639b 100644 --- a/seaweed-block/core/authority/policy.go +++ b/seaweed-block/core/authority/policy.go @@ -99,7 +99,7 @@ func (p *Publisher) VolumeAuthorityLine(volumeID string) (AuthorityBasis, bool) func (p *Publisher) volumeLineLocked(volumeID string) (AuthorityBasis, bool) { var best AuthorityBasis any := false - for k, st := range p.state { + for k, st := range p.volumeStateLocked(volumeID) { if !st.present || k.volumeID != volumeID { continue } diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 3bd2de600c..47ed4cceff 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -379,7 +379,7 @@ func (p *Publisher) WorkspaceSourceMoved(volume, replica, server string) (Publis func (p *Publisher) workspaceLineLocked(volume string) (subKey, assignmentState, bool) { var key subKey var line assignmentState - for k, s := range p.state { + for k, s := range p.volumeStateLocked(volume) { if k.volumeID == volume && s.present && s.info.Epoch > line.info.Epoch { key, line = k, s } @@ -550,7 +550,7 @@ func (p *Publisher) prepareWorkspaceMoveLocked(ask AssignmentAsk, g workspaceGra return nil, 0, time.Time{}, fmt.Errorf("workspace clean move needs detached HEAD and matching revocation ACK") } } - max := maxPublishedEpochForVolume(p.state, q.VolumeID) + max := maxPublishedEpochForVolume(p.volumeStateLocked(q.VolumeID), q.VolumeID) for _, r := range s.Moves { if r.NewEpoch > max { max = r.NewEpoch diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ef00e39956..832ab8175c 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -157,7 +157,10 @@ type Host struct { lifecycle *LifecycleStores // RPC registration/place/move/ACK/delete and product ticks serialize here. // Order: workspaceMu -> publisher or lifecycle store locks (not reversed). - workspaceMu sync.Mutex + workspaceMu sync.Mutex + // bindingRetry: volumes whose binding reconcile failed, retried with the + // next call's own volume (workspaceMu held). + bindingRetry map[string]bool events *eventRing promotionMu sync.RWMutex promotionProber PromotionEvidenceProvider diff --git a/seaweed-block/core/host/master/workspace_binding.go b/seaweed-block/core/host/master/workspace_binding.go index fd9986d824..3bde3751ac 100644 --- a/seaweed-block/core/host/master/workspace_binding.go +++ b/seaweed-block/core/host/master/workspace_binding.go @@ -32,7 +32,7 @@ func (s *services) RegisterWorkspaceBinding(ctx context.Context, q *control.Work if err := ctx.Err(); err != nil { return nil, workspaceError(err) } - if err := s.host.reconcileWorkspaceBindings(); err != nil { + if err := s.host.reconcileWorkspaceCall(q.GetVolumeId()); err != nil { return nil, workspaceError(err) } if _, ok := s.host.lifecycle.Nodes.GetNode(q.GetServerId()); !ok { @@ -133,29 +133,56 @@ func (h *Host) placementSourceHost(volume, replica string) string { // Recover retirement after a crash between the authority ACK/issued record // and binding persistence. Epoch-tagged retirements cannot retire a later // re-registration when an old Move/ACK is retried or replayed on restart. -// Caller owns workspaceMu, or Host.New has not exposed the host yet. +// Caller owns workspaceMu, or Host.New has not exposed the host yet. Every +// volume: the start's pass. func (h *Host) reconcileWorkspaceBindings() error { for _, v := range h.lifecycle.Volumes.ListVolumes() { - volume := v.Spec.VolumeID - state := h.Publisher().WorkspaceState(volume) - if state == nil { - continue + if err := h.reconcileWorkspaceBinding(v.Spec.VolumeID); err != nil { + return err } - for _, m := range state.Moves { - // A move must not retire its own target reservation. A same-host - // successor reuses it; a later ACK still retires that epoch below. - if m.Issued && m.OldHost != m.NewHost { - if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil { - return err - } + } + return nil +} + +// reconcileWorkspaceCall is a call's reconcile (a register, an ACK, a move): +// the call's own volume, and every volume whose reconcile failed before, so a +// failed retirement is retried by the next call as the whole pass did, at the +// cost of the volumes it touches, not every volume. workspaceMu held. +func (h *Host) reconcileWorkspaceCall(volume string) error { + if h.bindingRetry == nil { + h.bindingRetry = map[string]bool{} + } + h.bindingRetry[volume] = true + for v := range h.bindingRetry { + if err := h.reconcileWorkspaceBinding(v); err != nil { + return err + } + delete(h.bindingRetry, v) + } + return nil +} + +// reconcileWorkspaceBinding retires the bindings one volume's moves and ACK +// left behind. +func (h *Host) reconcileWorkspaceBinding(volume string) error { + state := h.Publisher().WorkspaceState(volume) + if state == nil { + return nil + } + for _, m := range state.Moves { + // A move must not retire its own target reservation. A same-host + // successor reuses it; a later ACK still retires that epoch below. + if m.Issued && m.OldHost != m.NewHost { + if err := h.lifecycle.WorkspaceBindings.Retire(volume, m.OldHost, m.OldEpoch); err != nil { + return err } } - if a := state.Ack; a != nil { - host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch) - if host != "" { - if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil { - return err - } + } + if a := state.Ack; a != nil { + host := h.workspaceSourceHost(volume, a.ReplicaID, a.Epoch) + if host != "" { + if err := h.lifecycle.WorkspaceBindings.Retire(volume, host, a.Epoch); err != nil { + return err } } } diff --git a/seaweed-block/core/host/master/workspace_binding_call_test.go b/seaweed-block/core/host/master/workspace_binding_call_test.go new file mode 100644 index 0000000000..8290910075 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_binding_call_test.go @@ -0,0 +1,66 @@ +package master + +import ( + "errors" + "reflect" + "runtime" + "testing" +) + +// A call's binding reconcile (register, ACK, move) is the whole pass +// restricted to the volumes it touches: its own volume, and any volume whose +// reconcile failed before. Another volume's call retires nothing of a volume +// it does not touch; the volume's own call retires exactly what the whole +// pass retires; and an interrupted reconcile is finished by the next call, +// whichever volume that call is for. +func TestWorkspaceBindingCallReconcilesItsVolumeAndRetries(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("requires the binding store's supported directory fsync") + } + want := []bindingRetirement{{"recover", "node-a", 1}, {"recover", "node-b", 2}, {"recover", "node-c", 4}} + + h := bindingReconcileHistory(t, false) + rec := &interruptedBindingStore{workspaceBindingStore: h.lifecycle.WorkspaceBindings} + h.workspaceMu.Lock() + h.lifecycle.WorkspaceBindings = rec + err := h.reconcileWorkspaceCall("other") + h.workspaceMu.Unlock() + if err != nil || len(rec.calls) != 0 { + t.Fatalf("another volume's call retired %+v (%v): it must touch only its own volume", rec.calls, err) + } + h.workspaceMu.Lock() + err = h.reconcileWorkspaceCall("recover") + h.workspaceMu.Unlock() + if err != nil || !reflect.DeepEqual(rec.calls, want) { + t.Fatalf("the volume's own call retired %+v (%v), the whole pass retires %+v", rec.calls, err, want) + } + + h2 := bindingReconcileHistory(t, false) + fault := &interruptedBindingStore{workspaceBindingStore: h2.lifecycle.WorkspaceBindings, at: 2} + h2.workspaceMu.Lock() + h2.lifecycle.WorkspaceBindings = fault + err = h2.reconcileWorkspaceCall("recover") + h2.workspaceMu.Unlock() + if !errors.Is(err, errBindingReconcileInterrupted) { + t.Fatalf("interruption not propagated: %v", err) + } + h2.workspaceMu.Lock() + err = h2.reconcileWorkspaceCall("other") + h2.workspaceMu.Unlock() + if err != nil { + t.Fatal(err) + } + got, _, err := fault.workspaceBindingStore.Get("recover") + if err != nil { + t.Fatal(err) + } + for _, b := range got { + epoch := map[string]uint64{"node-a": 1, "node-b": 2, "node-c": 4}[b.ServerID] + if !b.Retired || b.RetiredEpoch != epoch { + t.Fatalf("the next call did not finish the interrupted volume's retirements: %+v", got) + } + } + if len(h2.bindingRetry) != 0 { + t.Fatalf("volumes still marked for retry: %v", h2.bindingRetry) + } +} diff --git a/seaweed-block/core/host/master/workspace_service.go b/seaweed-block/core/host/master/workspace_service.go index ac134b6fc2..95fa2e3c07 100644 --- a/seaweed-block/core/host/master/workspace_service.go +++ b/seaweed-block/core/host/master/workspace_service.go @@ -243,7 +243,7 @@ func (s *services) AckWorkspaceRevoked(ctx context.Context, q *control.Workspace return nil, workspaceError(err) } recorded = time.Now() - if err := s.host.reconcileWorkspaceBindings(); err != nil { + if err := s.host.reconcileWorkspaceCall(id.GetVolumeId()); err != nil { return nil, workspaceError(err) } return &control.WorkspaceEmpty{}, nil @@ -388,7 +388,7 @@ func (s *services) MoveWorkspace(ctx context.Context, q *control.WorkspaceMove) // The move is issued from here on: record it for the audit log before // anything else can fail. issued = s.grantWithLostRange(r) - if err = s.host.reconcileWorkspaceBindings(); err != nil { + if err = s.host.reconcileWorkspaceCall(q.GetVolumeId()); err != nil { postIssue = err return nil, postIssueError(q, err) } From d7377311f2d5b64f4c5e0063fe5e175dcf09cd43 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:32:20 -0800 Subject: [PATCH 17/51] hostlimit: fetch test ownership and the waiting-path control - The fetch child keeps its release (and so the slot's file) reachable while it lives, with forced collections before it reports HELD. - The ended-waits test registers every release at once, and its second half frees the other slot only once each fetch is already waiting, so the waiting path's success is what is checked. - The competing fetches derive from a cancellable context, and cleanup joins them within a bound. - Comments: one fetch polls per limiter (blockvolume makes one per process); a configuration check in progress can add its bounded guard wait after the context ends. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/hostlimit/fetch.go | 12 ++-- .../core/hostlimit/fetch_review_test.go | 71 +++++++++++++------ seaweed-block/core/hostlimit/limiter.go | 2 +- 3 files changed, 59 insertions(+), 26 deletions(-) diff --git a/seaweed-block/core/hostlimit/fetch.go b/seaweed-block/core/hostlimit/fetch.go index 45d37b0207..e024f7a453 100644 --- a/seaweed-block/core/hostlimit/fetch.go +++ b/seaweed-block/core/hostlimit/fetch.go @@ -31,10 +31,12 @@ func fetchSlot(key string, n int) int { // configuration.lock, publishing it when absent, as a cut admission does: // ErrConfig when another process uses other flags; // 2. it takes a free slot without waiting, trying from key's hash slot; -// 3. with every slot held, it waits for its process's turn (one fetch per -// process polls) and then tries every slot each fetchRetry. The waiting -// is unordered, so other fetches can take a freed slot first; the wait is -// bounded by ctx alone and ends with ctx's error; +// 3. with every slot held, it waits for its limiter's turn (one fetch per +// limiter polls; blockvolume makes one limiter per process) and then +// tries every slot each fetchRetry. The waiting is unordered, so other +// fetches can take a freed slot first; it ends with ctx's error once ctx +// ends, after any file-system step in progress (a configuration check +// can add up to its bounded guard wait, guardWait); // 4. a slot taken when ctx has already ended is given back, and ctx's error // returned. // @@ -113,7 +115,7 @@ func (l *Limiter) tryFetch(home int) (*os.File, error) { } // waitFetch waits for a fetch slot while every one is held: it takes its -// process's turn, so one fetch per process polls, and tries every slot each +// limiter's turn, so one fetch per limiter polls, and tries every slot each // fetchRetry until one is free or ctx ends. func (l *Limiter) waitFetch(ctx context.Context, home int) (*os.File, error) { select { diff --git a/seaweed-block/core/hostlimit/fetch_review_test.go b/seaweed-block/core/hostlimit/fetch_review_test.go index 08365d475d..594516d980 100644 --- a/seaweed-block/core/hostlimit/fetch_review_test.go +++ b/seaweed-block/core/hostlimit/fetch_review_test.go @@ -37,9 +37,15 @@ func TestFetchProcessHelper(t *testing.T) { if err != nil { t.Fatal(err) } - if _, err := l.HoldFetch(context.Background(), "v/child"); err != nil { + release, err := l.HoldFetch(context.Background(), "v/child") + if err != nil { t.Fatal(err) } + // The release keeps the slot's file reachable for as long as the child + // lives; the forced collections show the hold does not depend on luck. + defer release() + runtime.GC() + runtime.GC() fmt.Println("HELD") _, _ = bufio.NewReader(os.Stdin).ReadByte() } @@ -169,7 +175,9 @@ func TestHoldFetchEndedWaitsLeaveNothingBehind(t *testing.T) { key := keyOnSlot(t, 0, 2) rHome := mustHold(t, homeHolder, key) // held for the whole test defer rHome() - rOther := mustHold(t, otherHolder, keyOnSlot(t, 1, 2)) + otherKey := keyOnSlot(t, 1, 2) + rOther := mustHold(t, otherHolder, otherKey) + defer rOther() // releases are idempotent g0, f0 := runtime.NumGoroutine(), openFDs() for i := 0; i < 20; i++ { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) @@ -183,17 +191,34 @@ func TestHoldFetchEndedWaitsLeaveNothingBehind(t *testing.T) { } } settlesTo(t, "20 waits ended at their deadline", g0, f0) - rOther() - for i := 0; i < 20; i++ { - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - r, err := w.HoldFetch(ctx, key) - cancel() - if err != nil { - t.Fatalf("fetch %d with the other slot free: %v", i, err) + // Each fetch below is already waiting (both slots held) when the other + // slot is freed, so it takes that slot from the waiting path. + for i := 0; i < 10; i++ { + if i > 0 { + rOther = mustHold(t, otherHolder, otherKey) + defer rOther() + } + got := holdAsync(t, w, context.Background(), key) + select { + case h := <-got: + if h.release != nil { + h.release() + } + t.Fatalf("fetch %d returned while both slots were held (err %v)", i, h.err) + case <-time.After(60 * time.Millisecond): + } + rOther() + select { + case h := <-got: + if h.err != nil { + t.Fatalf("waiting fetch %d: %v", i, h.err) + } + h.release() + case <-time.After(2 * time.Second): + t.Fatalf("waiting fetch %d never took the freed slot", i) } - r() } - settlesTo(t, "20 fetches that took the other slot", g0, f0) + settlesTo(t, "10 waiting fetches that took the freed slot", g0, f0) } // A context that ends as a slot is taken gets its context's error, and the @@ -226,20 +251,17 @@ func TestHoldFetchCancelledAtTheHandoffHoldsNothing(t *testing.T) { // its deadline's error. func TestHoldFetchAPassedWaiterEndsByItsDeadline(t *testing.T) { c := fetchConfig(t, 1) - stop := make(chan struct{}) + // The competitors' fetches derive from stopCtx, so stopping cancels a + // fetch in progress too; the cleanup joins them within a bound. + stopCtx, stop := context.WithCancel(context.Background()) var wg sync.WaitGroup for i := 0; i < 4; i++ { l := newTest(t, c) wg.Add(1) go func(i int) { defer wg.Done() - for { - select { - case <-stop: - return - default: - } - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + for stopCtx.Err() == nil { + ctx, cancel := context.WithTimeout(stopCtx, 100*time.Millisecond) r, err := l.HoldFetch(ctx, fmt.Sprintf("v/c%d", i)) cancel() if err == nil { @@ -249,7 +271,16 @@ func TestHoldFetchAPassedWaiterEndsByItsDeadline(t *testing.T) { } }(i) } - defer func() { close(stop); wg.Wait() }() + defer func() { + stop() + joined := make(chan struct{}) + go func() { wg.Wait(); close(joined) }() + select { + case <-joined: + case <-time.After(5 * time.Second): + t.Error("the competing fetches did not stop after their context ended") + } + }() w := newTest(t, c) const deadline = 150 * time.Millisecond ctx, cancel := context.WithTimeout(context.Background(), deadline) diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index d8c7f5086c..888482df4f 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -153,7 +153,7 @@ type Limiter struct { stalled map[string]bool // fetchChecked is set once a fetch has checked the host's configuration; - // fetchTurn (capacity 1) is held by the one fetch of this process that + // fetchTurn (capacity 1) is held by the one fetch of this limiter that // polls for a slot while every slot is held. fetchChecked atomic.Bool fetchTurn chan struct{} From e44aba0ed613ecf607a69f5fafddbf72c8ef04e3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:37:54 -0800 Subject: [PATCH 18/51] storage: a v1.1 cut copies HEAD's chunks for its candidates only On the v1.1 format a cut's base is HEAD's identity and its candidates' references (cutBaseLocked), the commit sends identity plus the change set, and a landed commit is applied to HEAD in place (applyCommitLocked): O(C) where the base, the proposal and the install each copied every chunk. A no-op cut compares its captured chunks with the by-change rule less the generation. The cut's result still reports the whole installed HEAD (one copy after the settlement, until the flat map goes). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 166 +++++++++++++++--- .../core/storage/chunk_proposal_by_change.go | 9 +- .../storage/chunk_proposal_by_change_test.go | 55 ++++++ 3 files changed, 202 insertions(+), 28 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 718bc4d0c5..c53ca663a9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1102,9 +1102,9 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch st.HeadReadbackNs += time.Since(start).Nanoseconds() return head, ok, err } - finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) { + finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string, inPlace bool) { start := time.Now() - l.finishCut(head, h, changed, keys) + l.finishCut(head, h, changed, keys, inPlace) st.CommitStateNs += time.Since(start).Nanoseconds() } var pauseStart time.Time @@ -1329,7 +1329,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch l.dirty = map[uint64]bool{} l.allDirty = false l.cutLSN = h - baseHead := copyHead(l.head) + baseHead := l.cutBaseLocked(candidates) l.stMu.Unlock() l.cutPhase("compare") // Candidates, mutation versions and the copy-order hint belong to the same barrier. @@ -1490,7 +1490,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) { // A no-op cut still observes authority: a fresh host may have // claimed HEAD without uploading a single chunk since our last cut. - cur, err := noopCutHead(baseHead, readCapturedRoot, readCapturedHead) + cur, fromBase, err := noopCutHead(baseHead, readCapturedRoot, readCapturedHead) if err != nil { l.requeueCut(all) return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err) @@ -1499,14 +1499,22 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // the CAS path does. Its generation alone may move without either // (a settlement that aborts this holder's session rewrites HEAD as // it was): the cut then completes on the newer generation. - if !sameProposal(cur, baseHead) { + // On the v1.1 format the image compared is the cut's: its captured + // chunks, every one equal to its base (the proposal by change). + byChange := l.commitByChange() + same := sameProposal(cur, baseHead) + if byChange { + same = sameByChange(cur, baseHead, headLookup(cur), nil, commitMarks(baseHead, captured, capturedVersions, map[uint64]*chunkRef{})) + } + if !same { l.requeueCut(all) l.fencePublication(cur) return chunkCutResult{}, errChunkLayerFenced } - finishCapturedCut(cur, h, nil, nil) // nothing new: no CAS + inPlace := byChange && fromBase // cur is the cut's base: its candidates only + finishCapturedCut(cur, h, nil, nil, inPlace) // nothing new: no CAS persistCapturedMap(capturedVersions) - return chunkCutResult{H: h, Head: copyHead(cur), Noop: true, FullHash: all}, nil + return chunkCutResult{H: h, Head: l.cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} // On the v1.1 format the commit goes by change: one owned change set, @@ -1520,7 +1528,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch // runs outside every other measured part, while a HEAD re-read (a // settlement) reads the manifest inside HeadReadbackNs. manifestBefore := work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load() - checkErr := l.checkCommitFirstBy(ctx, expected, next, changes) + checkErr := l.checkCommitFirstBy(ctx, expected, proposalOf(next, changes), changes) st.ManifestNs += work.spans[CutManifestRead].Load() + work.spans[CutSegmentWrites].Load() - manifestBefore if err := checkErr; err != nil { l.requeueCut(all) @@ -1540,7 +1548,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } l.cutPhase("commit") casStart := time.Now() - gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, next, changes, &st) + gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, expected, proposalOf(next, changes), changes, &st) st.CASNs = time.Since(casStart).Nanoseconds() st.CASResult = "ok" if errors.Is(casErr, errChunkHeadPrecondition) { @@ -1551,10 +1559,10 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch if casErr == nil { l.cutPhase("settle") next.Gen = gen - finishCapturedCut(next, h, changed, newKeys) + finishCapturedCut(next, h, changed, newKeys, changes != nil) l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) - return l.cutDone(chunkCutResult{H: h, Head: copyHead(next), FullHash: all}, detach), nil + return l.cutDone(chunkCutResult{H: h, Head: l.cutResultHead(next, changes != nil), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by // a blind retry. @@ -1595,7 +1603,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } if landedNext { st.CASResult = "resolved-by-reread" - finishCapturedCut(cur, h, changed, newKeys) + finishCapturedCut(cur, h, changed, newKeys, false) // cur is HEAD as read: whole l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil @@ -1786,17 +1794,19 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool { // identity alone (a ChunkHeadRootReader remote) and HEAD is still the image baseHead // names (the same generation token, epoch, holder, position and detach // state; the token changes whenever HEAD's root does), it is baseHead with -// its chunks, and no manifest is read. Otherwise it is the whole HEAD (full). -func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (chunkHead, error) { +// its chunks, and no manifest is read (fromBase). Otherwise it is the whole +// HEAD (full). +func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (head chunkHead, fromBase bool, err error) { root, ok, err := rootRead() if err != nil { - return chunkHead{}, err + return chunkHead{}, false, err } if ok && root.Gen == baseHead.Gen && root.Epoch == baseHead.Epoch && root.Holder == baseHead.Holder && root.RemoteLSN == baseHead.RemoteLSN && chunkHeadIsDetached(root) == chunkHeadIsDetached(baseHead) { - return copyHead(baseHead), nil + return copyHead(baseHead), true, nil } - return full() + head, err = full() + return head, false, err } func sameProposal(cur, next chunkHead) bool { @@ -1919,7 +1929,97 @@ func proposalLanded(cur, next chunkHead, baseGen uint64, changes, marked map[uin if changes == nil { return sameProposal(cur, next) } - return sameProposalByChange(cur, next, baseGen, func(i uint64) (chunkRef, bool) { r, ok := cur.Chunks[i]; return r, ok }, changes, marked) + return sameProposalByChange(cur, next, baseGen, headLookup(cur), changes, marked) +} + +// cutBaseLocked is a cut's base: HEAD's identity, and its chunks: on the +// v1.1 format only the candidates' references (O(C): the commit by change, +// its marks and the COW window read no other chunk), else a copy of all. +// Caller holds stMu. +func (l *chunkLayerImpl) cutBaseLocked(candidates map[uint64]bool) chunkHead { + if !l.commitByChange() { + return copyHead(l.head) + } + b := l.head + b.Chunks, b.Segments = nil, nil + b = copyHead(b) + b.Segments = l.head.Segments // shared, never written: every install replaces the map + for idx := range candidates { + if r, ok := l.headRef(idx); ok { + b.Chunks[idx] = r + } + } + return b +} + +// proposalOf is the HEAD a commit sends: by change (changes not nil) its +// identity alone, the remote applying the changes to its own chunks; else +// next whole. +func proposalOf(next chunkHead, changes map[uint64]*chunkRef) chunkHead { + if changes != nil { + next.Chunks = nil + } + return next +} + +// cutResultHead is the HEAD a cut reports, whole: h, or, when h names only +// the cut's chunks (byChange), the HEAD the commit installed (one copy, +// after the settlement, outside the barrier; it goes with the flat map in +// V4-B PR 4 commit 4). +func (l *chunkLayerImpl) cutResultHead(h chunkHead, byChange bool) chunkHead { + if !byChange { + return copyHead(h) + } + l.stMu.Lock() + defer l.stMu.Unlock() + return copyHead(l.head) +} + +// changedIndices is a change set's indices. +func changedIndices(changes map[uint64]*chunkRef) []uint64 { + out := make([]uint64, 0, len(changes)) + for idx := range changes { + out = append(out, idx) + } + return out +} + +// headLookup reads h's chunks as sameProposalByChange's ref. +func headLookup(h chunkHead) func(uint64) (chunkRef, bool) { + return func(i uint64) (chunkRef, bool) { r, ok := h.Chunks[i]; return r, ok } +} + +// applyCommitLocked installs a landed commit by change onto HEAD in place +// (O(C)): id's identity (generation, epoch, holder, position, state, who +// detached, chunk size and count) and each changed chunk's reference from +// id (none: zeros); every other chunk is HEAD's already, as the commit left +// it. The publication report, when one is wanted, gets whole HEADs. Caller +// holds stMu. +func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { + prev := l.head + if l.cfg.OnPublishSettled != nil { + prev = copyHead(l.head) + } + h := l.head + h.Gen, h.Epoch, h.Holder, h.RemoteLSN, h.State = id.Gen, id.Epoch, id.Holder, id.RemoteLSN, id.State + h.ChunkBytes, h.ManifestChunkCount = id.ChunkBytes, id.ManifestChunkCount + h.DetachedBy = nil + if id.DetachedBy != nil { + d := *id.DetachedBy + h.DetachedBy = &d + } + if h.Chunks == nil { + h.Chunks = map[uint64]chunkRef{} + } + for _, idx := range changed { + if r, ok := id.Chunks[idx]; ok { + h.Chunks[idx] = r + } else { + delete(h.Chunks, idx) + } + } + l.setHeadChangedLocked(h, changed) + l.noteSettled(prev, l.head) } func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { @@ -1935,6 +2035,9 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if pending == nil { return nil } + // reproposed: cur is the re-proposal this settlement landed, not HEAD + // as read; by change it names the cut's chunks only. + reproposed := false cur, err := readChunkHead(ctx, l.remote) if err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved: %w: %w", errChunkCASOutcomeUnknown, err) @@ -1950,13 +2053,14 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if err := l.admit(); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal refused: %w", errChunkCASOutcomeUnknown, err) } - if err := l.checkCommitFirstBy(ctx, base, *pending, changes); err != nil { + if err := l.checkCommitFirstBy(ctx, base, proposalOf(*pending, changes), changes); err != nil { return fmt.Errorf("storage: capture: earlier CAS outcome still unresolved (%w); re-proposal check failed: %w", errChunkCASOutcomeUnknown, err) } - gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, copyHead(*pending), changes, nil) + gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, proposalOf(copyHead(*pending), changes), changes, nil) if casErr == nil { cur = copyHead(*pending) cur.Gen = gen + reproposed = true } else if errors.Is(casErr, errChunkLayerFenced) { l.fencePublication(chunkHead{}) return errChunkLayerFenced @@ -1984,12 +2088,20 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil switch { case proposalLanded(cur, *pending, base.Gen, changes, marked): - l.noteSettled(l.head, cur) - l.setHeadLocked(copyHead(cur)) + inPlace := reproposed && changes != nil + if inPlace { + l.applyCommitLocked(cur, changedIndices(changes)) + } else { + l.noteSettled(l.head, cur) + l.setHeadLocked(copyHead(cur)) + } l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) if wasDetach { cut.Head = copyHead(cur) + if inPlace { + cut.Head = copyHead(l.head) // cur names the cut's chunks only + } l.detached = &cut return errChunkLayerDetached } @@ -2321,11 +2433,15 @@ func (l *chunkLayerImpl) requeueCut(all bool) { // finishCut installs HEAD in memory and rolls the bitmap over: only chunks // dirtied after the cut (and WAL entries above it) stay set. -func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string) { +func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, newKeys map[uint64]string, inPlace bool) { l.stMu.Lock() defer l.stMu.Unlock() - l.noteSettled(l.head, head) - l.setHeadChangedLocked(copyHead(head), changed) + if inPlace { + l.applyCommitLocked(head, changed) + } else { + l.noteSettled(l.head, head) + l.setHeadChangedLocked(copyHead(head), changed) + } l.remoteLSN, l.pending = h, nil l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil l.reusable = nil diff --git a/seaweed-block/core/storage/chunk_proposal_by_change.go b/seaweed-block/core/storage/chunk_proposal_by_change.go index 464d343174..24fe53f649 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change.go @@ -22,9 +22,12 @@ package storage // in whatever representation the caller has: a map, the ref table). func sameProposalByChange(cur, ident chunkHead, baseGen uint64, ref func(idx uint64) (chunkRef, bool), changes, marked map[uint64]*chunkRef) bool { - if cur.Gen <= baseGen { - return false - } + return cur.Gen > baseGen && sameByChange(cur, ident, ref, changes, marked) +} + +// sameByChange is sameProposalByChange without the generation (conditions +// 2-4): a no-op cut, which commits nothing, compares HEAD with its base so. +func sameByChange(cur, ident chunkHead, ref func(idx uint64) (chunkRef, bool), changes, marked map[uint64]*chunkRef) bool { if cur.Epoch != ident.Epoch || cur.Holder != ident.Holder || cur.RemoteLSN != ident.RemoteLSN || cur.ChunkBytes != ident.ChunkBytes || cur.ManifestChunkCount != ident.ManifestChunkCount { return false diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index c6f8d40000..077c1f50cd 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -3,6 +3,7 @@ package storage import ( "crypto/sha256" "fmt" + "reflect" "testing" ) @@ -110,3 +111,57 @@ func TestV11LostCommitReplySettlesByChange(t *testing.T) { t.Fatal("the settled HEAD is not the one read back") } } + +// On the v1.1 format a cut copies HEAD's chunks for its candidates only: its +// base names those (at S and at S/16 chunks alike), and a landed commit +// changes HEAD in place (the same map, the changed chunk replaced), where +// the full form copied every chunk at the barrier, for the proposal and at +// the install. +func TestV11CutCopiesOnlyItsCandidates(t *testing.T) { + withV11Format(t) + s, _ := v11Store(t) + f := newFakeChunkRemote() + l := v11Attach(t, s, f) + w := newWriteLog() + for c := uint32(0); c < 4; c++ { + w.write(t, s, c*ctChunkBlocks, byte(0x40+c)) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + before := reflect.ValueOf(l.head.Chunks).Pointer() + l.stMu.Unlock() + w.write(t, s, 2*ctChunkBlocks, 0x77) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + l.stMu.Lock() + after, n, ref2 := reflect.ValueOf(l.head.Chunks).Pointer(), len(l.head.Chunks), l.head.Chunks[2] + l.stMu.Unlock() + if after != before { + t.Fatal("a landed commit by change copied HEAD's chunk map instead of changing it in place") + } + remote, err := f.GetHead(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if got := remote.Chunks; n != len(got) || ref2 != got[2] { + t.Fatalf("HEAD changed in place is not the remote's: %d chunks, chunk 2 %+v; remote %d, %+v", n, ref2, len(got), got[2]) + } + for _, s := range []uint64{16384, 16384 / 16} { + h := chunkHead{Gen: 5, Epoch: 1, Holder: "h", Chunks: make(map[uint64]chunkRef, s)} + for i := uint64(0); i < s; i++ { + h.Chunks[i] = chunkRef{Key: fmt.Sprintf("k%d", i), Encoding: "full"} + } + l.stMu.Lock() + saved := l.head + l.setHeadLocked(h) + base := l.cutBaseLocked(map[uint64]bool{3: true, 9: true, s + 1: true}) // s+1: a candidate HEAD names nothing at + l.setHeadLocked(saved) + l.stMu.Unlock() + if len(base.Chunks) != 2 || base.Chunks[3] != h.Chunks[3] || base.Chunks[9] != h.Chunks[9] || base.Gen != 5 || base.Holder != "h" { + t.Fatalf("S=%d: the cut's base holds %d chunks (want its 2 named candidates) and identity gen %d holder %q", s, len(base.Chunks), base.Gen, base.Holder) + } + } +} From 975628e853d2ad260afdde4cf10565c4987bc31c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:39:46 -0800 Subject: [PATCH 19/51] hostlimit: test, the no-progress window bound starts at the admission The window's timer starts inside Admit; a first admission publishes and syncs the host configuration, which a loaded runner can stretch to hundreds of milliseconds. The upper bound is now measured from Admit's return; the lower bound still from before it. The failure message prints the admission's duration. Co-Authored-By: Claude Opus 5.5 --- .../core/hostlimit/limiter_progress_test.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/hostlimit/limiter_progress_test.go b/seaweed-block/core/hostlimit/limiter_progress_test.go index 08df88edfd..543d65a353 100644 --- a/seaweed-block/core/hostlimit/limiter_progress_test.go +++ b/seaweed-block/core/hostlimit/limiter_progress_test.go @@ -7,7 +7,10 @@ import ( ) // A hold whose work reports no progress is revoked within its no-progress -// window W: not before W, and not much after it. +// window W: not before W, and not much after it. The window starts inside +// Admit, so "not before" is measured from before Admit and "not much after" +// from its return: the admission's own file-system work (a first admission +// publishes and syncs the host configuration) is not counted against W. func TestStalledHoldIsRevokedWithinTheWindow(t *testing.T) { c := testConfig(t) c.NoProgress = 100 * time.Millisecond @@ -18,11 +21,15 @@ func TestStalledHoldIsRevokedWithinTheWindow(t *testing.T) { if err != nil { t.Fatal(err) } + admitted := time.Now() defer l.Release(x) select { case at := <-revoked: - if d := at.Sub(start); d < 80*time.Millisecond || d > 400*time.Millisecond { - t.Fatalf("revoked after %s, want about the window (%s)", d, c.NoProgress) + if d := at.Sub(start); d < 80*time.Millisecond { + t.Fatalf("revoked %s after the admission began, before the window (%s)", d, c.NoProgress) + } + if d := at.Sub(admitted); d > 400*time.Millisecond { + t.Fatalf("revoked %s after the admission returned, want about the window (%s); the admission took %s", d, c.NoProgress, admitted.Sub(start)) } case <-time.After(2 * time.Second): t.Fatalf("a stalled hold was not revoked within its no-progress window (%s)", c.NoProgress) From 204c2132f2e07bb318373cc53f66a5e5bc7f19a0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:46:08 -0800 Subject: [PATCH 20/51] authority: the line index check is exact both ways Every per-volume read in the package's tests now checks the whole index against the whole state: every state key indexed, every indexed key in the state, no empty volume set, and the read equal to the scan. Negative controls: a stale extra entry, a missing entry, an empty set. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/line_index_test.go | 71 ++++++++++++++++--- 1 file changed, 63 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/authority/line_index_test.go b/seaweed-block/core/authority/line_index_test.go index 725fbb80c3..a92bd0aae0 100644 --- a/seaweed-block/core/authority/line_index_test.go +++ b/seaweed-block/core/authority/line_index_test.go @@ -14,18 +14,73 @@ import ( ) // Every per-volume read of the line index, in every test of this package, -// equals a scan of the whole state restricted to that volume. +// checks the whole index against the whole state, both ways: the read +// equals the scan restricted to its volume, and the index holds exactly the +// keys of the state (no stale extra entry, none missing). func init() { testLineIndexCheck = func(p *Publisher, volumeID string, got map[subKey]assignmentState) { - want := map[subKey]assignmentState{} - for k, st := range p.state { - if k.volumeID == volumeID { - want[k] = st + if err := lineIndexMismatch(p, volumeID, got); err != "" { + panic("authority: " + err) + } + } +} + +// lineIndexMismatch is "" when the index is exact: got equals the state of +// volumeID's keys, every state key is indexed, and every indexed key is in +// the state. +func lineIndexMismatch(p *Publisher, volumeID string, got map[subKey]assignmentState) string { + want := map[subKey]assignmentState{} + for k, st := range p.state { + if k.volumeID == volumeID { + want[k] = st + } + if _, ok := p.replicas[k.volumeID][k.replicaID]; !ok { + return fmt.Sprintf("line index lacks state key %v", k) + } + } + for v, rs := range p.replicas { + if len(rs) == 0 { + return fmt.Sprintf("line index holds an empty set for volume %q", v) + } + for r := range rs { + if _, ok := p.state[subKey{volumeID: v, replicaID: r}]; !ok { + return fmt.Sprintf("line index holds %s/%s, which the state does not", v, r) } } - if !reflect.DeepEqual(got, want) { - panic(fmt.Sprintf("authority: line index for volume %q holds %v, the scan %v", volumeID, got, want)) - } + } + if !reflect.DeepEqual(got, want) { + return fmt.Sprintf("line index read for volume %q is %v, the scan %v", volumeID, got, want) + } + return "" +} + +// The exact-membership check catches each way the index can drift: a stale +// extra entry, a missing entry, and an empty volume set. +func TestLineIndexCheckIsExact(t *testing.T) { + saved := testLineIndexCheck + testLineIndexCheck = nil + t.Cleanup(func() { testLineIndexCheck = saved }) + p := NewPublisher(nil) + p.mu.Lock() + defer p.mu.Unlock() + st := assignmentState{info: adapter.AssignmentInfo{VolumeID: "v1", ReplicaID: "r1", Epoch: 1}, present: true} + p.setStateLocked(subKey{volumeID: "v1", replicaID: "r1"}, st) + if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err != "" { + t.Fatalf("green: %s", err) + } + p.replicas["v1"]["r9"] = struct{}{} // stale extra entry + if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err == "" { + t.Error("a stale extra index entry was not caught") + } + delete(p.replicas["v1"], "r9") + p.state[subKey{volumeID: "v2", replicaID: "r1"}] = st // a state key the index lacks + if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err == "" { + t.Error("a missing index entry was not caught") + } + delete(p.state, subKey{volumeID: "v2", replicaID: "r1"}) + p.replicas["v3"] = map[string]struct{}{} + if err := lineIndexMismatch(p, "v1", p.volumeStateLocked("v1")); err == "" { + t.Error("an empty volume set was not caught") } } From ad9ee63491d1ef1e8660a71f32963f3c2c86700b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:15:33 -0800 Subject: [PATCH 21/51] authority: a heartbeat that changes nothing wakes no observation rebuild The observation store wakes a rebuild only when an ingest changes what a snapshot build reads: a new server, a server's facts or freshness, a slot added, removed or changed but for its timestamps, a slot's expiry state, a volume two servers report, or a passed deadline. What changes with time is a deadline: each server's next expiry in a heap, the pending grace's end; the host wakes at the earliest. A published line wakes the build through the publisher's line-change hook. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 17 ++ .../core/authority/observation_changes.go | 174 +++++++++++++ .../authority/observation_changes_test.go | 238 ++++++++++++++++++ .../core/authority/observation_host.go | 31 +++ .../core/authority/observation_store.go | 28 ++- seaweed-block/core/host/master/host.go | 3 + 6 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/authority/observation_changes.go create mode 100644 seaweed-block/core/authority/observation_changes_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 30cafb9342..1e9ba83378 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -124,6 +124,9 @@ type Publisher struct { // (SetIncarnationSource); its own lock, never taken under mu. incarnationMu sync.RWMutex incarnationOf func(volumeID, replicaID, dataAddr, ctrlAddr string) string + // lineChanged is told the volume of every published line (the + // observation build reads lines, and no heartbeat carries them). + lineChanged func(volumeID string) mu sync.Mutex state map[subKey]assignmentState @@ -480,6 +483,14 @@ func (p *Publisher) SetIncarnationSource(of func(volumeID, replicaID, dataAddr, p.incarnationMu.Unlock() } +// SetLineChangeHook registers fn, told the volume of every published line +// after the publication (outside the publisher's lock). nil removes it. +func (p *Publisher) SetLineChangeHook(fn func(volumeID string)) { + p.incarnationMu.Lock() + p.lineChanged = fn + p.incarnationMu.Unlock() +} + func (p *Publisher) apply(ask AssignmentAsk) error { if p.publicationAdmission != nil { return p.publicationAdmission(ask, func() error { return p.applyWithWorkspaceMove(ask, nil) }) @@ -751,6 +762,12 @@ func (p *Publisher) applyWithWorkspaceMove(ask AssignmentAsk, grant *workspaceGr if p.observer != nil { safeInvokePublishObserver(p.observer, PublishEvent{Info: next, Ask: ask}) } + p.incarnationMu.RLock() + changed := p.lineChanged + p.incarnationMu.RUnlock() + if changed != nil { + changed(ask.VolumeID) + } return nil } diff --git a/seaweed-block/core/authority/observation_changes.go b/seaweed-block/core/authority/observation_changes.go new file mode 100644 index 0000000000..0c499335ee --- /dev/null +++ b/seaweed-block/core/authority/observation_changes.go @@ -0,0 +1,174 @@ +package authority + +import ( + "container/heap" + "reflect" + "time" +) + +// What a snapshot build reads changes only by a heartbeat that changes it, +// by time (a server's or a slot's expiry, the pending grace's end), by a +// published line, or by the topology. A heartbeat that refreshes only +// timestamps changes none of these, so it wakes no rebuild; the time each +// such fact changes is kept as a deadline, and the host wakes then. + +// buildReadsChangedLocked says whether storing next for its server (prev the +// observation it replaces) can change a snapshot build at now: a new server; +// a change of the server's facts or freshness; a slot added, removed, or +// changed in anything but its timestamps; a slot whose expiry state flips; +// or any slot of a volume that another server also reports (a build orders +// such slots by their timestamps, so a refresh can change it). s.mu held. +func (s *ObservationStore) buildReadsChangedLocked(prev Observation, hadPrev bool, next Observation, now time.Time) bool { + if !hadPrev || prev.Server != next.Server || now.After(prev.ExpiresAt) != now.After(next.ExpiresAt) || len(prev.Slots) != len(next.Slots) { + return true + } + before := make(map[string]SlotFact, len(prev.Slots)) + for _, sl := range prev.Slots { + before[slotKey(sl)] = sl + } + for _, sl := range next.Slots { + p, ok := before[slotKey(sl)] + if !ok || !sameSlotContent(p, sl) || slotExpired(p, prev, now) != slotExpired(sl, next, now) { + return true + } + if len(s.volServers[sl.VolumeID]) > 1 { + return true + } + } + return false +} + +// sameSlotContent compares two slot facts but for their timestamps. +func sameSlotContent(a, b SlotFact) bool { + a.ObservedAt, a.ExpiresAt, b.ObservedAt, b.ExpiresAt = time.Time{}, time.Time{}, time.Time{}, time.Time{} + return reflect.DeepEqual(a, b) +} + +// indexServerLocked records which volumes server id reports (prev's slots +// out, next's in). s.mu held. +func (s *ObservationStore) indexServerLocked(id string, prev []SlotFact, next []SlotFact) { + if s.volServers == nil { + s.volServers = map[string]map[string]struct{}{} + } + for _, sl := range prev { + if m := s.volServers[sl.VolumeID]; m != nil { + delete(m, id) + if len(m) == 0 { + delete(s.volServers, sl.VolumeID) + } + } + } + for _, sl := range next { + m := s.volServers[sl.VolumeID] + if m == nil { + m = map[string]struct{}{} + s.volServers[sl.VolumeID] = m + } + m[id] = struct{}{} + } +} + +// nextExpiry is the earliest expiry of obs (its own, or a slot's) not yet +// passed at now; zero when none is ahead. A fact expires once now is after +// its expiry (observation_store.go), so an expiry equal to now is still +// ahead. +func nextExpiry(obs Observation, now time.Time) time.Time { + var at time.Time + consider := func(t time.Time) { + if !t.IsZero() && !now.After(t) && (at.IsZero() || t.Before(at)) { + at = t + } + } + consider(obs.ExpiresAt) + for _, sl := range obs.Slots { + consider(sl.ExpiresAt) + } + return at +} + +// deadlineEntry is one server's next expiry; seq tells a current entry from +// one a later heartbeat replaced (lazy deletion). +type deadlineEntry struct { + at time.Time + server string + seq uint64 +} + +type deadlineHeap []deadlineEntry + +func (h deadlineHeap) Len() int { return len(h) } +func (h deadlineHeap) Less(i, j int) bool { return h[i].at.Before(h[j].at) } +func (h deadlineHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } +func (h *deadlineHeap) Push(x any) { *h = append(*h, x.(deadlineEntry)) } +func (h *deadlineHeap) Pop() any { + old := *h + e := old[len(old)-1] + *h = old[:len(old)-1] + return e +} + +// scheduleLocked records server id's next expiry after now. s.mu held. +func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.Time) { + if s.deadlineSeq == nil { + s.deadlineSeq = map[string]uint64{} + } + s.deadlineSeq[id]++ + if at := nextExpiry(obs, now); !at.IsZero() { + heap.Push(&s.deadlines, deadlineEntry{at: at, server: id, seq: s.deadlineSeq[id]}) + } +} + +// NextDeadline is the earliest time a build's input changes with no +// heartbeat: a server's or slot's expiry, or the pending grace's end; zero +// when none is ahead. +func (s *ObservationStore) NextDeadline() time.Time { + s.mu.Lock() + defer s.mu.Unlock() + now := s.now() + for s.deadlines.Len() > 0 { + e := s.deadlines[0] + if e.seq == s.deadlineSeq[e.server] { + break + } + heap.Pop(&s.deadlines) // replaced by a later heartbeat + } + var at time.Time + if s.deadlines.Len() > 0 { + at = s.deadlines[0].at + } + if g := s.startedAt.Add(s.config.PendingGrace); g.After(now) && (at.IsZero() || g.Before(at)) { + at = g + } + return at +} + +// ExpireDue reports whether a deadline has passed since the last call (an +// expiry or the pending grace's end: a build's input changed), and moves +// each such server to its next deadline. +func (s *ObservationStore) ExpireDue() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.expireDueLocked(s.now()) +} + +// expireDueLocked is ExpireDue with s.mu held. +func (s *ObservationStore) expireDueLocked(now time.Time) bool { + due := false + for s.deadlines.Len() > 0 && now.After(s.deadlines[0].at) { + e := heap.Pop(&s.deadlines).(deadlineEntry) + if e.seq != s.deadlineSeq[e.server] { + continue + } + due = true + if obs, ok := s.observations[e.server]; ok { + s.scheduleLocked(e.server, obs, now) + } + } + if !s.graceSeen { + if g := s.startedAt.Add(s.config.PendingGrace); !g.After(now) { + s.graceSeen = true + due = true + } + } + return due +} diff --git a/seaweed-block/core/authority/observation_changes_test.go b/seaweed-block/core/authority/observation_changes_test.go new file mode 100644 index 0000000000..29e1b77dc0 --- /dev/null +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -0,0 +1,238 @@ +package authority + +import ( + "context" + "fmt" + "math/rand" + "reflect" + "sync/atomic" + "testing" + "time" +) + +func countingStore(t *testing.T, clk *fakeClock, window time.Duration) (*ObservationStore, *atomic.Int64) { + t.Helper() + s := NewObservationStore(FreshnessConfig{FreshnessWindow: window}, clk.Now) + var wakes atomic.Int64 + s.SetOnMutation(func() { wakes.Add(1) }) + return s, &wakes +} + +func oneSlotObs(server string, at time.Time, slots ...SlotFact) Observation { + return Observation{ServerID: server, ObservedAt: at, Server: ServerFact{Reachable: true, Eligible: true}, Slots: slots} +} + +// A heartbeat that refreshes only timestamps (every volume process sends one +// every 2 s) wakes no rebuild; a changed slot, a new server, or a refresh of +// a volume two servers report does. On main every heartbeat woke a full +// rebuild. +func TestObservationStoreTimestampOnlyRefreshWakesNothing(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + s, wakes := countingStore(t, clk, 30*time.Second) + const servers = 200 + for i := 0; i < servers; i++ { + if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), start, healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil { + t.Fatal(err) + } + } + if wakes.Load() != servers { + t.Fatalf("%d wakes for %d new servers", wakes.Load(), servers) + } + wakes.Store(0) + clk.Advance(2 * time.Second) + for round := 0; round < 3; round++ { + for i := 0; i < 100; i++ { + if err := s.Ingest(oneSlotObs(fmt.Sprintf("s%03d", i), clk.Now(), healthySlot(fmt.Sprintf("v%03d", i), "r1"))); err != nil { + t.Fatal(err) + } + } + clk.Advance(2 * time.Second) + } + if n := wakes.Load(); n != 0 { + t.Fatalf("300 timestamp-only heartbeats woke %d rebuilds, want 0", n) + } + changed := healthySlot("v007", "r1") + changed.ReadyForPrimary = false + if err := s.Ingest(oneSlotObs("s007", clk.Now(), changed)); err != nil { + t.Fatal(err) + } + if n := wakes.Load(); n != 1 { + t.Fatalf("a changed slot woke %d rebuilds, want 1", n) + } + // A volume two servers report: a refresh of either wakes. + if err := s.Ingest(oneSlotObs("s900", clk.Now(), healthySlot("v008", "r2"))); err != nil { + t.Fatal(err) + } + wakes.Store(0) + if err := s.Ingest(oneSlotObs("s008", clk.Now(), healthySlot("v008", "r1"))); err != nil { + t.Fatal(err) + } + if n := wakes.Load(); n != 1 { + t.Fatalf("a refresh of a volume two servers report woke %d rebuilds, want 1", n) + } +} + +// What changes with time wakes the host at its deadline, with no heartbeat: +// a server whose heartbeats stop is seen expired once its freshness window +// passes. +func TestObservationHostRebuildsAtAnExpiryWithNoHeartbeat(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: 100 * time.Millisecond}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + _ = host.IngestHeartbeat(serverObs("s1", start, healthySlot("v1", "r1"))) + waitFor := func(what string, ok func(BuildResult) bool) { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if b, have := host.LastBuild(); have && ok(b) { + return + } + time.Sleep(10 * time.Millisecond) + } + b, _ := host.LastBuild() + t.Fatalf("%s: last build at %v with %d servers", what, b.BuiltAt, len(b.Snapshot.Servers)) + } + waitFor("the heartbeat's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 1 }) + clk.Advance(time.Second) // past s1's freshness; no heartbeat follows + waitFor("the expiry's build", func(b BuildResult) bool { return len(b.Snapshot.Servers) == 0 && b.BuiltAt.Equal(clk.Now()) }) +} + +// normalizedBuild is a build with its stamps cleared: when it was built, the +// store revision, and the timestamps the evidence carries. +func normalizedBuild(b BuildResult) BuildResult { + b.BuiltAt, b.InputRev = time.Time{}, 0 + b.Snapshot.CollectedAt, b.Snapshot.CollectedRevision = time.Time{}, 0 + vols := make([]VolumeTopologySnapshot, len(b.Snapshot.Volumes)) + for i, v := range b.Snapshot.Volumes { + v.Slots = append([]ReplicaCandidate(nil), v.Slots...) + for j := range v.Slots { + v.Slots[j].ObservedAt = time.Time{} + } + vols[i] = v + } + b.Snapshot.Volumes = vols + pend := map[string]VolumePendingStatus{} + for k, v := range b.Report.Pending { + v.EvaluatedAt = time.Time{} + pend[k] = v + } + b.Report.Pending = pend + uns := map[string]VolumeUnsupportedEvidence{} + for k, v := range b.Report.Unsupported { + v.EvaluatedAt, v.SnapshotRevision = time.Time{}, 0 + facts := make([]Observation, len(v.OffendingFacts)) + for i, o := range v.OffendingFacts { + o.ObservedAt, o.ExpiresAt = time.Time{}, time.Time{} + o.Slots = append([]SlotFact(nil), o.Slots...) + for j := range o.Slots { + o.Slots[j].ObservedAt, o.Slots[j].ExpiresAt = time.Time{}, time.Time{} + } + facts[i] = o + } + v.OffendingFacts = facts + uns[k] = v + } + b.Report.Unsupported = uns + return b +} + +// Whenever the store reports no change (no wake, no passed deadline), a +// build now equals the last build, but for its stamps: random heartbeats +// (new, changed, timestamp-only, of a shared volume), time steps past +// freshness windows and the pending grace, and GC. +func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { + topo := AcceptedTopology{Volumes: []VolumeExpected{ + {VolumeID: "va", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s1"}}}, + {VolumeID: "vb", Slots: []ExpectedSlot{{ReplicaID: "r1", ServerID: "s2"}}}, + threeSlotVolume("vc"), + }} + for seed := int64(1); seed <= 300; seed++ { + rng := rand.New(rand.NewSource(seed)) + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + s := NewObservationStore(FreshnessConfig{FreshnessWindow: 5 * time.Second, PendingGrace: 7 * time.Second}, clk.Now) + var woke bool + s.SetOnMutation(func() { woke = true }) + last := BuildSnapshot(s.Snapshot(), topo, nil) + s.ExpireDue() + reports := map[string][]SlotFact{ + "s1": {healthySlot("va", "r1"), healthySlot("vc", "r1")}, + "s2": {healthySlot("vb", "r1"), healthySlot("vc", "r2")}, + "s3": {healthySlot("vc", "r3")}, + "s4": {healthySlot("vx", "r1")}, + } + names := []string{"s1", "s2", "s3", "s4"} + for step := 0; step < 300; step++ { + woke = false + switch rng.Intn(7) { + case 0, 1, 2: // a heartbeat, maybe with a change + srv := names[rng.Intn(len(names))] + slots := append([]SlotFact(nil), reports[srv]...) + if rng.Intn(4) == 0 { + i := rng.Intn(len(slots)) + slots[i].ReadyForPrimary = !slots[i].ReadyForPrimary + reports[srv] = slots + } + obs := oneSlotObs(srv, clk.Now(), slots...) + if rng.Intn(8) == 0 { + obs.Server.Eligible = false + } + _ = s.Ingest(obs) + case 3: // time passes + clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond) + case 4: // the host's timer + if s.ExpireDue() { + woke = true + } + case 5: + s.GC(time.Duration(rng.Intn(20)) * time.Second) + case 6: // exactly at the next deadline, or just past it + if at := s.NextDeadline(); !at.IsZero() { + clk.Set(at.Add(time.Duration(rng.Intn(2)))) + } + } + if s.ExpireDue() { // a deadline passed: the host's timer would wake + woke = true + } + now := BuildSnapshot(s.Snapshot(), topo, nil) + if woke { + last = now + continue + } + if !reflect.DeepEqual(normalizedBuild(now), normalizedBuild(last)) { + t.Fatalf("seed %d step %d: the store reported no change, but the build changed:\nlast %+v\nnow %+v", seed, step, normalizedBuild(last), normalizedBuild(now)) + } + } + } +} + +// A published line wakes the observation build (no heartbeat carries it): +// the publisher tells its line-change hook the volume of every publication, +// and only of a publication. +func TestPublisherTellsItsLineChangeHook(t *testing.T) { + var told []string + pub := NewPublisher(NewStaticDirective(nil)) + pub.SetLineChangeHook(func(v string) { told = append(told, v) }) + ask := AssignmentAsk{VolumeID: "v1", ReplicaID: "r1", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind} + if err := pub.apply(ask); err != nil { + t.Fatal(err) + } + if len(told) != 1 || told[0] != "v1" { + t.Fatalf("hook told %v after one publication, want [v1]", told) + } + if err := pub.apply(ask); err == nil { + t.Fatal("a second bind was accepted") + } + if len(told) != 1 { + t.Fatalf("hook told %v after a refused ask", told) + } +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 8748df39f0..1d1850f6df 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -116,6 +116,11 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// Wake asks for a rebuild: a change a build reads that no heartbeat +// carries (a published authority line, a topology change). Non-blocking; +// wakes coalesce. +func (h *ObservationHost) Wake() { h.signalRebuild() } + // Store returns the underlying store. Exposed for tests and for // downstream diagnosis; the host does not expect external code // to manipulate it beyond Ingest. @@ -221,14 +226,40 @@ func (h *ObservationHost) run(ctx context.Context) { h.rebuildOnce() for { + // A heartbeat that refreshes only timestamps wakes nothing; what + // changes with time (an expiry, the pending grace's end) wakes the + // loop at its deadline. + var deadlineC <-chan time.Time + var timer *time.Timer + if at := h.store.NextDeadline(); !at.IsZero() { + d := at.Sub(h.store.now()) + if d < 10*time.Millisecond { + d = 10 * time.Millisecond + } + timer = time.NewTimer(d) + deadlineC = timer.C + } + stopTimer := func() { + if timer != nil { + timer.Stop() + } + } select { case <-ctx.Done(): + stopTimer() return case <-h.stop: + stopTimer() return case <-h.wake: + stopTimer() h.rebuildOnce() + case <-deadlineC: + if h.store.ExpireDue() { + h.rebuildOnce() + } case <-gcC: + stopTimer() h.store.GC(h.gcRetain) // GC may have set the mutation flag; that is OK — the // next iteration will pick up the wake. diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 4283ff4f82..12f26fb460 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -36,6 +36,15 @@ type ObservationStore struct { revision uint64 onMutation func() + // volServers: the servers reporting a slot of each volume (a volume + // two servers report is ordered by timestamps in a build). + volServers map[string]map[string]struct{} + // deadlines: each server's next expiry (lazily replaced: deadlineSeq); + // graceSeen: the pending grace's end was reported (observation_changes.go). + deadlines deadlineHeap + deadlineSeq map[string]uint64 + graceSeen bool + // supersededCount counts slot reports that were dropped because a // newer ObservedAt was stored for that server/volume/replica slot. // Diagnostic only — PCDD-DELAYED-HB-001 evidence @@ -377,9 +386,22 @@ func (s *ObservationStore) ingest(obs Observation) ([]SlotHealthTransition, erro obs.ObservedAt, obs.ExpiresAt, obs.Server = prev.ObservedAt, prev.ExpiresAt, prev.Server } } + now := s.now() + // A deadline passed since the last build is a change too (the build a + // heartbeat wakes then sees the expiry, as before). + changed := s.expireDueLocked(now) + if s.buildReadsChangedLocked(prev, hadPrev, obs, now) { + changed = true + } + s.indexServerLocked(obs.ServerID, prev.Slots, obs.Slots) + s.scheduleLocked(obs.ServerID, obs, now) s.observations[obs.ServerID] = obs s.revision++ - fn = s.onMutation + if changed { + // A heartbeat that refreshes only timestamps wakes no rebuild: its + // expiry is a deadline (NextDeadline) the host wakes at. + fn = s.onMutation + } s.mu.Unlock() if fn != nil { @@ -561,6 +583,10 @@ func (s *ObservationStore) GC(retain time.Duration) int { for id, obs := range s.observations { if now.Sub(obs.ObservedAt) > retain { delete(s.observations, id) + s.indexServerLocked(id, obs.Slots, nil) + if s.deadlineSeq != nil { + s.deadlineSeq[id]++ // its pending deadline is void + } removed++ } } diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ef00e39956..743de83b35 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -298,6 +298,9 @@ func New(cfg Config) (*Host, error) { Sink: sink, Reader: boot.Publisher, }) + // A published line changes what the observation build reads, and no + // heartbeat carries it: it wakes the build. + boot.Publisher.SetLineChangeHook(func(string) { obs.Wake() }) // An ask built outside the controller (a heal, a planned or workspace // move, an operator's request) is issued for the process its target // reports now. From 75bb94c46dc06bd53bf22557d012819d8c7606d0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:31:26 -0800 Subject: [PATCH 22/51] authority: the grace's end stays a deadline until consumed; the master's line wake is pinned NextDeadline keeps the pending grace's end until ExpireDue reports it, even once past, so a build taken just before it and submitted just after it is rebuilt with no heartbeat. The property test now fires the host's timer only at NextDeadline, so a dropped deadline shows. A master test pins the line-change wiring: a volume reported once is bound by the controller and the next build carries the line. Comments that promised a wake on every ingest now say what wakes. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_changes.go | 11 ++-- .../authority/observation_changes_test.go | 64 +++++++++++++++++-- .../core/authority/observation_host.go | 8 ++- .../core/authority/observation_store.go | 4 +- .../core/host/master/line_change_wake_test.go | 58 +++++++++++++++++ 5 files changed, 133 insertions(+), 12 deletions(-) create mode 100644 seaweed-block/core/host/master/line_change_wake_test.go diff --git a/seaweed-block/core/authority/observation_changes.go b/seaweed-block/core/authority/observation_changes.go index 0c499335ee..94e6f1a901 100644 --- a/seaweed-block/core/authority/observation_changes.go +++ b/seaweed-block/core/authority/observation_changes.go @@ -119,12 +119,12 @@ func (s *ObservationStore) scheduleLocked(id string, obs Observation, now time.T } // NextDeadline is the earliest time a build's input changes with no -// heartbeat: a server's or slot's expiry, or the pending grace's end; zero -// when none is ahead. +// heartbeat and ExpireDue has not reported yet: a server's or slot's expiry, +// or the pending grace's end (possibly already past); zero when none is +// left. func (s *ObservationStore) NextDeadline() time.Time { s.mu.Lock() defer s.mu.Unlock() - now := s.now() for s.deadlines.Len() > 0 { e := s.deadlines[0] if e.seq == s.deadlineSeq[e.server] { @@ -136,7 +136,10 @@ func (s *ObservationStore) NextDeadline() time.Time { if s.deadlines.Len() > 0 { at = s.deadlines[0].at } - if g := s.startedAt.Add(s.config.PendingGrace); g.After(now) && (at.IsZero() || g.Before(at)) { + // The grace's end stays a deadline until ExpireDue reports it, even once + // past: a build taken just before it, with the host's next look just + // after it, must still be rebuilt. + if g := s.startedAt.Add(s.config.PendingGrace); !s.graceSeen && (at.IsZero() || g.Before(at)) { at = g } return at diff --git a/seaweed-block/core/authority/observation_changes_test.go b/seaweed-block/core/authority/observation_changes_test.go index 29e1b77dc0..c48b97e55c 100644 --- a/seaweed-block/core/authority/observation_changes_test.go +++ b/seaweed-block/core/authority/observation_changes_test.go @@ -189,9 +189,9 @@ func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { _ = s.Ingest(obs) case 3: // time passes clk.Advance(time.Duration(rng.Intn(4000)) * time.Millisecond) - case 4: // the host's timer - if s.ExpireDue() { - woke = true + case 4: // time passes to the next deadline the host would wake at + if at := s.NextDeadline(); !at.IsZero() { + clk.Set(at.Add(time.Millisecond)) } case 5: s.GC(time.Duration(rng.Intn(20)) * time.Second) @@ -200,7 +200,9 @@ func TestObservationStoreNoWakeMeansTheSameBuild(t *testing.T) { clk.Set(at.Add(time.Duration(rng.Intn(2)))) } } - if s.ExpireDue() { // a deadline passed: the host's timer would wake + // The host's timer: it fires at NextDeadline (a deadline NextDeadline + // leaves out never fires). + if at := s.NextDeadline(); !at.IsZero() && !at.After(clk.Now()) && s.ExpireDue() { woke = true } now := BuildSnapshot(s.Snapshot(), topo, nil) @@ -236,3 +238,57 @@ func TestPublisherTellsItsLineChangeHook(t *testing.T) { t.Fatalf("hook told %v after a refused ask", told) } } + +// submitHook is a sink that runs a function at each submission (the +// submission is where a real build can cross a deadline). +type submitHook struct { + recordingSink + on func(n int) + n int +} + +func (s *submitHook) SubmitObservedState(snap ClusterSnapshot, report SupportabilityReport) error { + s.n++ + if s.on != nil { + s.on(s.n) + } + return s.recordingSink.SubmitObservedState(snap, report) +} + +// The pending grace's end is rebuilt even when a build taken just before it +// is submitted just after it, with no heartbeat ever arriving: the deadline +// stays until it is consumed. +func TestObservationHostRebuildsAfterTheGraceCrossedDuringASubmission(t *testing.T) { + start := time.Date(2026, 12, 1, 12, 0, 0, 0, time.UTC) + clk := newFakeClock(start) + grace := 100 * time.Millisecond + sink := &submitHook{} + sink.on = func(n int) { + if n == 1 { + clk.Set(start.Add(grace + time.Millisecond)) // the first build crosses the grace's end + } + } + host := NewObservationHost(ObservationHostConfig{ + Freshness: FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: grace}, + Topology: AcceptedTopology{Volumes: []VolumeExpected{threeSlotVolume("v1")}}, + Sink: sink, + Now: clk.Now, + }) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + host.Start(ctx) + defer host.Stop() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if b, ok := host.LastBuild(); ok { + if _, pending := b.Report.Pending["v1"]; !pending { + if _, unsupported := b.Report.Unsupported["v1"]; unsupported { + return + } + } + } + time.Sleep(10 * time.Millisecond) + } + b, _ := host.LastBuild() + t.Fatalf("v1 is still pending past the grace with no heartbeat: pending %v, unsupported %v", b.Report.Pending, b.Report.Unsupported) +} diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 1d1850f6df..3dbbc81085 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -16,9 +16,11 @@ import ( // Institution logic lives here, not in cmd/sparrow. The cmd // layer is only allowed to construct, start, and stop the host. // -// Default operation is build-on-change (sketch §11): every -// successful Ingest fires a non-blocking signal that wakes the -// rebuild goroutine. The goroutine drains the signal, takes one +// Default operation is build-on-change (sketch §11): an Ingest +// that changes what a build reads (observation_changes.go), a +// deadline passing (an expiry, the pending grace's end) or Wake (a +// published line) wakes the rebuild goroutine; a heartbeat that +// refreshes only timestamps does not. The goroutine drains the signal, takes one // store snapshot, runs BuildSnapshot, and hands the // ClusterSnapshot to the controller's SubmitClusterSnapshot. // Pending / Unsupported volumes are surfaced via the last diff --git a/seaweed-block/core/authority/observation_store.go b/seaweed-block/core/authority/observation_store.go index 12f26fb460..0081267ef4 100644 --- a/seaweed-block/core/authority/observation_store.go +++ b/seaweed-block/core/authority/observation_store.go @@ -246,7 +246,9 @@ func NewObservationStore(config FreshnessConfig, now func() time.Time) *Observat } // SetOnMutation registers a callback that fires whenever a -// successful ingest changes store contents. The callback must +// successful ingest changes what a snapshot build reads (not on a +// heartbeat that refreshes only timestamps; GC removing an entry fires it +// too). The callback must // NOT block; typical use is a non-blocking signal into the host's // rebuild goroutine. // diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go new file mode 100644 index 0000000000..5929ddadfb --- /dev/null +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -0,0 +1,58 @@ +package master + +import ( + "runtime" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" +) + +// A published line wakes the observation build, through the master's +// wiring of the publisher's line-change hook: a volume reported once (no +// heartbeat follows) is bound by the controller, and the next build carries +// that line. Timestamp-only heartbeats wake nothing, so without the wiring +// the build would keep the unbound basis until some unrelated change. +func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("the lifecycle stores need directory fsync") + } + h, err := New(Config{ + AuthorityStoreDir: t.TempDir(), + LifecycleStoreDir: t.TempDir(), + Listen: "127.0.0.1:0", + // No expiry and no GC wake within the test. + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour}, + Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ + VolumeID: "v1", + Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, + }}}, + }) + if err != nil { + t.Fatal(err) + } + h.Start() + defer closeTestMaster(t, h) + if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ + ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, + Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, + }); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { + if b, have := h.obs.LastBuild(); have { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return + } + } + } + } + time.Sleep(20 * time.Millisecond) + } + line, ok := h.Publisher().VolumeAuthorityLine("v1") + b, _ := h.obs.LastBuild() + t.Fatalf("published line %+v (%v), but the last build's volumes are %+v", line, ok, b.Snapshot.Volumes) +} From 1cb5e0e124fbcef3a3c6df84d691f1ec941983c7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:36:48 -0800 Subject: [PATCH 23/51] master: the line-wake test orders its builds so only the hook can wake the last The test now drains the initial build and the grace's rebuild before the one heartbeat, whose single wake is consumed by the build showing v1 supported; the controller binds after it, and with no heartbeat, expiry or GC tick left, the build carrying the line can only come from the hook. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 64 +++++++++++++------ 1 file changed, 44 insertions(+), 20 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 5929ddadfb..6f07a6bb50 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -9,10 +9,16 @@ import ( ) // A published line wakes the observation build, through the master's -// wiring of the publisher's line-change hook: a volume reported once (no -// heartbeat follows) is bound by the controller, and the next build carries -// that line. Timestamp-only heartbeats wake nothing, so without the wiring -// the build would keep the unbound basis until some unrelated change. +// wiring of the publisher's line-change hook. The order is made +// deterministic so no other wake can stand in for the hook: +// - the master starts with nothing ingested; its initial build runs, and +// the 1 ms pending grace's deadline is consumed (its rebuild runs too); +// - after the builds drain, one heartbeat is ingested: its single wake is +// consumed by one build whose snapshot already holds it (the snapshot is +// taken after the wake is received), showing v1 supported and unbound; +// - the controller binds v1 after that build. No heartbeat follows, no +// expiry is due (a one-hour window), and there is no GC tick: a later +// build carrying the line can only come from the hook. func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("the lifecycle stores need directory fsync") @@ -21,8 +27,7 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), Listen: "127.0.0.1:0", - // No expiry and no GC wake within the test. - Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour}, + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ VolumeID: "v1", Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, @@ -33,26 +38,45 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) + waitBuild := func(what string, ok func(authority.BuildResult) bool) authority.BuildResult { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if b, have := h.obs.LastBuild(); have && ok(b) { + return b + } + time.Sleep(10 * time.Millisecond) + } + b, _ := h.obs.LastBuild() + t.Fatalf("%s: last build %+v", what, b.Snapshot.Volumes) + return authority.BuildResult{} + } + waitBuild("the initial build", func(authority.BuildResult) bool { return true }) + time.Sleep(300 * time.Millisecond) // the grace's deadline fires and its rebuild drains if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { - if b, have := h.obs.LastBuild(); have { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return - } - } + waitBuild("the heartbeat's build (v1 supported)", func(b authority.BuildResult) bool { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" { + return true } } - time.Sleep(20 * time.Millisecond) - } - line, ok := h.Publisher().VolumeAuthorityLine("v1") - b, _ := h.obs.LastBuild() - t.Fatalf("published line %+v (%v), but the last build's volumes are %+v", line, ok, b.Snapshot.Volumes) + return false + }) + waitBuild("the build after the controller's publication", func(b authority.BuildResult) bool { + line, ok := h.Publisher().VolumeAuthorityLine("v1") + if !ok || !line.Assigned { + return false + } + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return true + } + } + return false + }) } From 5e1f9d11e4f9e6e23545da331eee725d4ebfc819 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:11:40 -0800 Subject: [PATCH 24/51] storage: no flat map on v1.1: HEAD's chunks live in the ref table On the v1.1 format the layer keeps HEAD's identity and its chunks in the ref table only: the attach reads HEAD one segment at a time from a segment reader (ChunkSegmentReader; the layout remote is one), every install fills the table from a HEAD read whole, and the paths that need the whole image (adoption, owning, the detach cancel, the publication report) build it from the table. A cut's result reports HEAD's identity only; no production code reads its chunks (a scan test guards it), and tests read the remote's installed HEAD. The held heap at 1 TiB's chunk count is 174 B/chunk (442 before) and is asserted at most 200. Co-Authored-By: Claude Opus 5.5 --- .../frontend/chunkstore/head_readers_test.go | 3 +- .../chunkstore/layout_head_read_root_test.go | 16 +- .../core/frontend/chunkstore/layout_remote.go | 3 + .../durable/commit_check_budget_test.go | 5 +- .../core/frontend/durable/provider_chunk.go | 23 ++ .../storage/chunk_attach_progress_test.go | 6 +- .../storage/chunk_attach_segments_test.go | 103 +++++++++ .../storage/chunk_cut_cow_spillcap_test.go | 5 +- .../core/storage/chunk_cut_image_test.go | 5 +- .../storage/chunk_cut_result_head_test.go | 64 ++++++ .../core/storage/chunk_fake_remote_test.go | 30 +++ .../core/storage/chunk_fresh_known_zero.go | 4 +- .../storage/chunk_head_test_helpers_test.go | 11 + .../chunk_hydration_concurrency_test.go | 4 +- seaweed-block/core/storage/chunk_layer.go | 205 +++++++++++------- .../core/storage/chunk_layer_cut_test.go | 6 + .../core/storage/chunk_layer_races_test.go | 2 +- seaweed-block/core/storage/chunk_own.go | 6 +- .../storage/chunk_proposal_by_change_test.go | 25 ++- .../core/storage/chunk_record_open.go | 2 +- .../storage/chunk_record_shadow_main_test.go | 10 - .../core/storage/chunk_record_shadow_test.go | 2 +- .../core/storage/chunk_record_upgrade.go | 12 +- .../storage/chunk_ref_table_mirror_test.go | 43 ---- .../core/storage/chunk_space_baseline_test.go | 18 +- 25 files changed, 449 insertions(+), 164 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_attach_segments_test.go create mode 100644 seaweed-block/core/storage/chunk_cut_result_head_test.go create mode 100644 seaweed-block/core/storage/chunk_head_test_helpers_test.go delete mode 100644 seaweed-block/core/storage/chunk_ref_table_mirror_test.go diff --git a/seaweed-block/core/frontend/chunkstore/head_readers_test.go b/seaweed-block/core/frontend/chunkstore/head_readers_test.go index 92280b3bba..0de1e71b95 100644 --- a/seaweed-block/core/frontend/chunkstore/head_readers_test.go +++ b/seaweed-block/core/frontend/chunkstore/head_readers_test.go @@ -64,12 +64,13 @@ var headReaders = map[string]string{ "cmd/sw-block/chunk_b.go chunkShowContext -> ReadHead": "found=false: prints a null head, including via the chunkShow wrapper (probe TestOpsChunk_AbsentVolume)", "cmd/sw-block/chunk_b.go chunkSnapshots -> ReadHead": "refuses volume_not_found (probe TestOpsChunk_AbsentVolume)", "core/frontend/durable/provider_chunk.go GetHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/frontend/durable/provider_chunk.go EachSegment -> GetHead": "a remote without a segment read: ErrHeadAbsent from its GetHead, as GetHead (probe LayoutRemote)", "core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", "core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", "core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)", "core/storage/chunk_head_belt.go readChunkHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", "core/storage/chunk_head_belt.go readChunkHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", - "core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)", + "core/storage/chunk_layer.go readAttachHead -> GetHead": "ErrHeadAbsent from the layout remote; its segment read (EachSegment) reads HEAD as GetHead does (headIdentityLocked) (probe LayoutRemote)", } // TestHeadReaders_Enumeration lists every HEAD reader in core/ and cmd/ from diff --git a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go index 3f79bbbedc..007e9ce6df 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_head_read_root_test.go @@ -89,7 +89,7 @@ func TestTheConfirmationAfterAHeadWriteReadsNoManifest(t *testing.T) { // already holds, it reads HEAD only and keeps its chunk list: no root and no // segment. func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) { - _, _, l, counting, reads := manifestReads(t) + _, remote, l, counting, reads := manifestReads(t) if _, err := l.Cut(context.Background()); err != nil { // publish the written chunks t.Fatal(err) } @@ -104,7 +104,19 @@ func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) { if n := reads.Load(); n != 0 { t.Fatalf("a no-op cut over an unchanged HEAD read %d roots or segments; want 0", n) } - if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks { + if res.Head.Chunks == nil { + // The v1.1 format: a cut's result reports HEAD's identity only. HEAD + // itself, read once the cut's reads are counted, still names every + // chunk at the result's generation. + counting.Store(false) + h, err := remote.GetHead(context.Background()) + if err != nil { + t.Fatal(err) + } + if h.Gen != res.Head.Gen || len(h.Chunks) != lrBlocks/lrChunkBlocks { + t.Fatalf("after the no-op cut HEAD is gen %d with %d chunks; want the result's gen %d with the %d it already held", h.Gen, len(h.Chunks), res.Head.Gen, lrBlocks/lrChunkBlocks) + } + } else if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks { t.Fatalf("the no-op cut's HEAD names %d chunks; want the %d it already held", len(res.Head.Chunks), lrBlocks/lrChunkBlocks) } } diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 70fa4906d6..e66ec45fbc 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -476,6 +476,9 @@ func boundedManifest(ctx context.Context, r *layout.Reader, rn layout.RootName, return m, err } +// The layer's v1.1 attach reads HEAD through it segment by segment. +var _ storage.ChunkSegmentReader = (*LayoutRemote)(nil) + // EachSegment is GetHead one segment at a time (storage.ChunkSegmentReader): // HEAD's identity as GetHead returns it (no chunk listed), and fn called for // each segment HEAD's root names with its chunk range [first, end) (a diff --git a/seaweed-block/core/frontend/durable/commit_check_budget_test.go b/seaweed-block/core/frontend/durable/commit_check_budget_test.go index 0cb93d2c58..1d9962a918 100644 --- a/seaweed-block/core/frontend/durable/commit_check_budget_test.go +++ b/seaweed-block/core/frontend/durable/commit_check_budget_test.go @@ -111,8 +111,9 @@ func TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces(t *testing b, ok := r.(storage.ChunkHeadStepBounder) return ok && b.BoundsHeadStep() }, - "ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok }, - "ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok }, + "ChunkKeyer": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkKeyer); return ok }, + "ChunkPutRounds": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkPutRounds); return ok }, + "ChunkSegmentReader": func(r storage.ChunkRemote) bool { _, ok := r.(storage.ChunkSegmentReader); return ok }, } for name, has := range checks { if has(lr) && !has(wrapped) { diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index a47cf57d84..43b1743e1d 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -7,6 +7,7 @@ import ( "errors" "fmt" "log" + "math" "math/rand/v2" "strings" "sync" @@ -728,6 +729,28 @@ func (r *closeBoundRemote) GetHead(ctx context.Context) (storage.ChunkHead, erro return r.ChunkRemote.GetHead(c) } +// EachSegment forwards HEAD's read one segment at a time +// (storage.ChunkSegmentReader) with GetHead's binding. A remote without it +// is read whole and handed over as one segment. +func (r *closeBoundRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]storage.ChunkRef) error) (storage.ChunkHead, error) { + c, end := r.bindManifest(ctx) + defer end() + if sr, ok := r.ChunkRemote.(storage.ChunkSegmentReader); ok { + return sr.EachSegment(c, fn) + } + h, err := r.ChunkRemote.GetHead(c) + if err != nil { + return storage.ChunkHead{}, err + } + if len(h.Chunks) > 0 { + if err := fn(0, math.MaxUint64, h.Chunks); err != nil { + return storage.ChunkHead{}, err + } + } + h.Chunks = nil + return h, nil +} + func (r *closeBoundRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) { c, end := r.bindManifest(ctx) defer end() diff --git a/seaweed-block/core/storage/chunk_attach_progress_test.go b/seaweed-block/core/storage/chunk_attach_progress_test.go index 6c8cece6a9..b6f833182b 100644 --- a/seaweed-block/core/storage/chunk_attach_progress_test.go +++ b/seaweed-block/core/storage/chunk_attach_progress_test.go @@ -56,9 +56,13 @@ func TestAttachReportsItsVolumeSizedLocalWork(t *testing.T) { // On the v1.1 format the presence save feeds the store's upgrade, // then the record's pages (one entry per chunk of the volume) are // written by the upgrade and judged at the open. + // The ref table holds the volume's chunks only: this HEAD names more + // than the store's, which the absent marking and the presence save + // then count per volume chunk. want := uint64(4 * n) if chunkV11Format { - want = 4*n + 2*uint64(s.NumBlocks()) + vol := uint64(s.NumBlocks()) + want = n + 3*min(n, vol) + 2*vol } if c.total != want { t.Fatalf("reported %d entries, want %d (the HEAD copy, the absent marking, then the presence save's keys and lines, or the record's pages written and judged)", c.total, want) diff --git a/seaweed-block/core/storage/chunk_attach_segments_test.go b/seaweed-block/core/storage/chunk_attach_segments_test.go new file mode 100644 index 0000000000..15afc5c156 --- /dev/null +++ b/seaweed-block/core/storage/chunk_attach_segments_test.go @@ -0,0 +1,103 @@ +package storage + +import ( + "context" + "fmt" + "reflect" + "sort" + "testing" +) + +// segmentRemote reads HEAD one segment at a time (ChunkSegmentReader), in +// segments of seg chunks, counting the segments it hands out and every +// whole read (GetHead) made through it. +type segmentRemote struct { + *fakeChunkRemote + seg uint64 + segments, wholeReads int +} + +func (r *segmentRemote) GetHead(ctx context.Context) (chunkHead, error) { + r.wholeReads++ + return r.fakeChunkRemote.GetHead(ctx) +} + +func (r *segmentRemote) EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]ChunkRef) error) (ChunkHead, error) { + h, err := r.fakeChunkRemote.GetHead(ctx) // the remote's own read: the layer sees segments + if err != nil { + return chunkHead{}, err + } + shards := map[uint64]map[uint64]chunkRef{} + for idx, ref := range h.Chunks { + sh := idx / r.seg + if shards[sh] == nil { + shards[sh] = map[uint64]chunkRef{} + } + shards[sh][idx] = ref + } + order := make([]uint64, 0, len(shards)) + for sh := range shards { + order = append(order, sh) + } + sort.Slice(order, func(i, j int) bool { return order[i] < order[j] }) + for _, sh := range order { + r.segments++ + if err := fn(sh*r.seg, (sh+1)*r.seg, shards[sh]); err != nil { + return chunkHead{}, err + } + } + h.Chunks = nil + return h, nil +} + +// On the v1.1 format a layer attaches to a remote that reads HEAD by segment +// one segment at a time: no whole read of HEAD, no flat map kept, and the +// ref table names exactly HEAD's chunks. A segment naming a chunk beyond +// the volume is refused (a malformed HEAD), as the whole read's install +// cannot tell. +func TestV11AttachReadsHeadOneSegmentAtATime(t *testing.T) { + withV11Format(t) + head := func(extra bool) chunkHead { + h := chunkHead{Gen: 3, Epoch: 1, Holder: "old", RemoteLSN: 0, Chunks: map[uint64]chunkRef{}} + for i := uint64(0); i < 16; i += 2 { // every other chunk of the 16-chunk store + h.Chunks[i] = chunkRef{Key: fmt.Sprintf("c%d", i), Encoding: "full"} + } + if extra { + h.Chunks[17] = chunkRef{Key: "beyond", Encoding: "full"} + } + return h + } + attach := func(t *testing.T, h chunkHead) (*segmentRemote, *chunkLayerImpl, error) { + s, _ := v11Store(t) + f := newFakeChunkRemote() + f.head = h + r := &segmentRemote{fakeChunkRemote: f, seg: 4} + cfg := ctConfig(1) + cfg.Bitmap, cfg.Epoch, cfg.FreshFromHead = nil, 2, true + l, err := attachChunkLayer(s, r, cfg) + if err != nil { + return r, nil, err + } + t.Cleanup(func() { _ = l.Close() }) + return r, l.(*chunkLayerImpl), nil + } + r, l, err := attach(t, head(false)) + if err != nil { + t.Fatal(err) + } + l.stMu.Lock() + flat, whole := l.head.Chunks, l.wholeHeadLocked() + l.stMu.Unlock() + if r.wholeReads != 0 || r.segments != 4 { + t.Fatalf("attach read HEAD whole %d times and %d segments, want none and 4", r.wholeReads, r.segments) + } + if flat != nil { + t.Fatalf("the attached layer keeps a flat map of %d chunks", len(flat)) + } + if want := head(false).Chunks; !reflect.DeepEqual(whole.Chunks, want) { + t.Fatalf("the ref table names %d chunks, HEAD %d", len(whole.Chunks), len(want)) + } + if _, _, err := attach(t, head(true)); err == nil { + t.Fatal("a segment naming a chunk beyond the volume was attached") + } +} diff --git a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go index 3adf5057c0..92b7e0800d 100644 --- a/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go +++ b/seaweed-block/core/storage/chunk_cut_cow_spillcap_test.go @@ -356,9 +356,10 @@ func TestCutCOWV3_RecentChunkUploadsFirst(t *testing.T) { if len(puts) != len(want) { t.Fatalf("PUTs=%v, want three uploads", puts) } + installed := f.headOf(t, result.Head) for i, idx := range want { - if puts[i] != result.Head.Chunks[idx].Key { - t.Fatalf("PUT %d=%q, want hot chunk %d key %q", i, puts[i], idx, result.Head.Chunks[idx].Key) + if puts[i] != installed.Chunks[idx].Key { + t.Fatalf("PUT %d=%q, want hot chunk %d key %q", i, puts[i], idx, installed.Chunks[idx].Key) } } } diff --git a/seaweed-block/core/storage/chunk_cut_image_test.go b/seaweed-block/core/storage/chunk_cut_image_test.go index 2e181ac838..aed92ec97d 100644 --- a/seaweed-block/core/storage/chunk_cut_image_test.go +++ b/seaweed-block/core/storage/chunk_cut_image_test.go @@ -89,7 +89,7 @@ func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) { if err != nil { t.Fatal(err) } - if first.Head.Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { + if f.headOf(t, first.Head).Chunks[0].Encoding != "full" || first.Head.RemoteLSN != y { t.Fatalf("first cut: %+v, want position %d", first.Head, y) } _, err = s.Write(ctChunkBlocks, makeBlock(ctBlockSize, 0x44)) @@ -100,7 +100,8 @@ func TestChunkCutKeepsColdChunksAndDeletesZeroChunks(t *testing.T) { if err != nil { t.Fatal(err) } - if second.Head.Chunks[0] != first.Head.Chunks[0] || second.Head.Chunks[1] == first.Head.Chunks[1] { + h1, h2 := f.headOf(t, first.Head), f.headOf(t, second.Head) + if h2.Chunks[0] != h1.Chunks[0] || h2.Chunks[1] == h1.Chunks[1] { t.Fatal("rewrite changed a cold chunk or did not publish the changed one") } for _, lba := range []uint32{ctChunkBlocks, ctChunkBlocks + 1} { diff --git a/seaweed-block/core/storage/chunk_cut_result_head_test.go b/seaweed-block/core/storage/chunk_cut_result_head_test.go new file mode 100644 index 0000000000..7455c397e4 --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_result_head_test.go @@ -0,0 +1,64 @@ +package storage + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +// On the v1.1 format a cut's result reports HEAD's identity only (its Chunks +// nil): no production code may read a cut or detach result's chunks. Every +// non-test Go file of the module is scanned for a read of .Head.Chunks or +// .Head.Segments; a reader added later fails here. The control: the pattern +// finds such a read. +func TestNoProductionReaderOfACutResultsChunks(t *testing.T) { + re := regexp.MustCompile(`\.Head\.(Chunks|Segments)\b`) + if !re.MatchString("ref := res.Head.Chunks[3]") || re.MatchString("gen := res.Head.Gen") { + t.Fatal("control: the scan's pattern does not tell a chunk read from an identity read") + } + root := filepath.Join("..", "..") + if _, err := os.Stat(filepath.Join(root, "go.mod")); err != nil { + t.Fatalf("module root not found from the package: %v", err) + } + var found []string + files := 0 + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + switch d.Name() { + case ".git", "vendor", "testdata", "node_modules": + 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 + } + files++ + for i, line := range strings.Split(string(b), "\n") { + if re.MatchString(line) { + found = append(found, fmt.Sprintf("%s:%d", p, i+1)) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + if files < 100 { + t.Fatalf("scanned only %d Go files: the walk did not cover the module", files) + } + if len(found) > 0 { + t.Fatalf("production code reads a cut result's chunks, which the v1.1 format does not report: %v", found) + } +} diff --git a/seaweed-block/core/storage/chunk_fake_remote_test.go b/seaweed-block/core/storage/chunk_fake_remote_test.go index 882f098ad6..063fa98807 100644 --- a/seaweed-block/core/storage/chunk_fake_remote_test.go +++ b/seaweed-block/core/storage/chunk_fake_remote_test.go @@ -389,6 +389,9 @@ func (f *fakeChunkRemote) imageOf(t *testing.T, h chunkHead) []byte { t.Helper() f.mu.Lock() defer f.mu.Unlock() + if h.Chunks == nil && h.Gen != 0 { + h = f.installedLocked(t, h) + } img := make([]byte, ctNumBlocks*ctBlockSize) for idx, ref := range h.Chunks { b, ok := f.objs[ref.Key] @@ -1178,3 +1181,30 @@ func deltaMatchesNext(h chunkHead, next chunkHead, changes map[uint64]*chunkRef) } return applied, nil } + +// headOf is h whole: h itself, or the HEAD this remote installed with h's +// identity when h reports identity only (a v1.1 cut's result). +func (f *fakeChunkRemote) headOf(t *testing.T, h chunkHead) chunkHead { + t.Helper() + if h.Chunks != nil || h.Gen == 0 { + return h + } + f.mu.Lock() + defer f.mu.Unlock() + return f.installedLocked(t, h) +} + +// installedLocked is the HEAD this remote installed with id's generation, +// epoch and holder: what a cut's result names when it reports identity only +// (the v1.1 format), read from the remote, the source of truth. Caller +// holds mu. +func (f *fakeChunkRemote) installedLocked(t *testing.T, id chunkHead) chunkHead { + t.Helper() + for i := len(f.heads) - 1; i >= 0; i-- { + if h := f.heads[i]; h.Gen == id.Gen && h.Epoch == id.Epoch && h.Holder == id.Holder { + return h + } + } + t.Fatalf("no installed HEAD has gen %d epoch %d holder %q", id.Gen, id.Epoch, id.Holder) + return chunkHead{} +} diff --git a/seaweed-block/core/storage/chunk_fresh_known_zero.go b/seaweed-block/core/storage/chunk_fresh_known_zero.go index 9f57e2b4f6..ba8783a0ae 100644 --- a/seaweed-block/core/storage/chunk_fresh_known_zero.go +++ b/seaweed-block/core/storage/chunk_fresh_known_zero.go @@ -22,7 +22,7 @@ import "log" // THEN the marking is made durable, THEN the volume serves. A crash between // the first two leaves no marker and every chunk UNKNOWN (one scan); a // failed map publication leaves them UNKNOWN on disk (conservative). -func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uint64 { +func (l *chunkLayerImpl) freshKnownZeroCandidates() map[uint64]uint64 { s := l.s if s.v3 == nil || s.v3.ownedMap == nil { return nil @@ -32,7 +32,7 @@ func (l *chunkLayerImpl) freshKnownZeroCandidates(head chunkHead) map[uint64]uin out := map[uint64]uint64{} for idx := uint64(0); idx < l.numChunks && idx < uint64(s.v3.mapEntries.len()); idx++ { l.attachProgress.add(1) // attach only (its one caller): every inspected entry, candidate or not - if _, named := head.Chunks[idx]; named { + if _, named := l.headRef(idx); named { continue } if e := s.v3.mapEntries.at(int(idx)); e.LSN != 0 || !e.Unknown { diff --git a/seaweed-block/core/storage/chunk_head_test_helpers_test.go b/seaweed-block/core/storage/chunk_head_test_helpers_test.go new file mode 100644 index 0000000000..3f43c5a594 --- /dev/null +++ b/seaweed-block/core/storage/chunk_head_test_helpers_test.go @@ -0,0 +1,11 @@ +package storage + +// setHeadChunkForTest replaces one chunk's reference in the layer's HEAD, as +// a HEAD install would: in the ref table on the v1.1 format, else the map. +func setHeadChunkForTest(l *chunkLayerImpl, idx uint64, ref chunkRef) { + if l.refs != nil { + _ = l.refs.Set(idx, ref) + return + } + l.head.Chunks[idx] = ref +} diff --git a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go index 71caa18817..a11cf11273 100644 --- a/seaweed-block/core/storage/chunk_hydration_concurrency_test.go +++ b/seaweed-block/core/storage/chunk_hydration_concurrency_test.go @@ -310,7 +310,7 @@ func (r *staleHydrationRemote) Get(ctx context.Context, key string) ([]byte, err func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { s, layer, remote, registered := hydrationFixture(t, 2, 64) layer.stMu.Lock() - oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + oldRef, newRef := layer.headChunk(2), layer.headChunk(3) layer.stMu.Unlock() r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{})} layer.remote = r @@ -350,7 +350,7 @@ func TestChunkHydration_NewGenerationDoesNotJoinStaleGet(t *testing.T) { func TestChunkHydration_StaleCompletionKeepsReplacement(t *testing.T) { s, layer, remote, registered := hydrationFixture(t, 2, 64) layer.stMu.Lock() - oldRef, newRef := layer.head.Chunks[2], layer.head.Chunks[3] + oldRef, newRef := layer.headChunk(2), layer.headChunk(3) layer.stMu.Unlock() r := &staleHydrationRemote{fakeChunkRemote: remote, oldKey: oldRef.Key, entered: make(chan struct{}), release: make(chan struct{}), newEntered: make(chan struct{}, 1), newRelease: make(chan struct{})} layer.remote = r diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index c53ca663a9..d8b08b7cab 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -334,12 +334,11 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.nonce = hex.EncodeToString(nb8[:]) l.ctx, l.cancel = context.WithCancel(context.Background()) - head, err := remote.GetHead(l.ctx) + head, err := l.readAttachHead(remote) if err != nil { l.cancel() return nil, fmt.Errorf("storage: chunk layer attach: read HEAD: %w", err) } - l.setHeadLocked(copyHeadEach(head, l.attachProgress.add)) // reports as it copies l.remoteLSN = head.RemoteLSN // A HEAD that already belongs to a newer epoch or a competing holder is // never used as this holder's publication guard. @@ -363,14 +362,14 @@ func attachChunkLayerImpl(s *WALStore, remote chunkRemote, cfg chunkLayerConfig) l.hdr = chunkBitmapHeader{BaseLSN: head.RemoteLSN, HeadGen: head.Gen, Epoch: cfg.Epoch} l.dirty = map[uint64]bool{} - for idx := range head.Chunks { + l.eachHeadChunkLocked(func(idx uint64) { l.absent[idx] = true l.absentGen[idx]++ l.attachProgress.add(1) - } + }) l.presenceVer++ if cfg.CreatedThisStart { - l.freshKnownZero = l.freshKnownZeroCandidates(head) + l.freshKnownZero = l.freshKnownZeroCandidates() } } else if marked, _ := s.ChunkStateMarker(); chunkV11Format && marked { // The v1.1 record and the store's bits hold presence: a leftover @@ -452,60 +451,104 @@ func (l *chunkLayerImpl) chunkOf(lba uint64) uint64 { return lba / l.chunkBlocks // flat map behind it can be replaced (V4-B PR 4). Caller holds stMu. func (l *chunkLayerImpl) headRef(idx uint64) (chunkRef, bool) { if l.refs != nil { - r, ok := l.refs.Get(idx) - if check := refTableCheck; check != nil { - if m, mok := l.head.Chunks[idx]; mok != ok || m != r { - check(fmt.Sprintf("chunk %d: the ref table names %+v (%v), the flat map %+v (%v)", idx, r, ok, m, mok)) - } - } - return r, ok + return l.refs.Get(idx) } r, ok := l.head.Chunks[idx] return r, ok } -// refTableCheck, set by tests only, compares every ref-table read with the -// flat map while both exist (a finding fails the package's tests). -var refTableCheck func(string) - -// refTableMirror keeps the ref table beside the flat map on the v1.1 format. -// Off until the flat map goes (V4-B PR 4 commit 4): both at once only add -// memory. Tests turn it on to check the table against the map through the -// layer's every HEAD install (TestRefTableMirrorsHeadThroughTheLayer). -var refTableMirror = false - -// setHeadLocked installs h as the layer's HEAD and, on the v1.1 format, -// refills the ref table from it whole (attach, settlement, adoption: the -// rare paths). Caller holds stMu or owns the layer. +// setHeadLocked installs h as the layer's HEAD. On the v1.1 format HEAD's +// chunks live in the ref table only: it is refilled from h whole (a HEAD +// read whole: settlement, adoption, a fence) and the layer keeps h's +// identity, no flat map (V4-B PR 4). Caller holds stMu or owns the layer. func (l *chunkLayerImpl) setHeadLocked(h chunkHead) { - l.head = h - if !chunkV11Format || !refTableMirror { - l.refs = nil + if !chunkV11Format { + l.head, l.refs = h, nil return } if l.refs == nil || uint64(len(l.refs.prefix)) != l.numChunks { l.refs = newRefTable(l.numChunks) } l.refs.fillAll(h.Chunks) + h.Chunks = nil + l.head = h } -// setHeadChangedLocked installs h after a commit whose changed chunks are -// changed: the ref table takes only those (O(C)), the rest is unchanged. -func (l *chunkLayerImpl) setHeadChangedLocked(h chunkHead, changed []uint64) { - if l.refs == nil { - l.setHeadLocked(h) +// readAttachHead reads HEAD at attach and installs it. On the v1.1 format, +// from a remote that reads HEAD one segment at a time (ChunkSegmentReader), +// each segment's references go to the ref table as it is read: no flat map +// is built, here or in the remote. Otherwise HEAD is read whole and +// installed (setHeadLocked). Every reference is reported as attach progress. +// It returns HEAD as installed (identity only on the v1.1 format). +func (l *chunkLayerImpl) readAttachHead(remote chunkRemote) (chunkHead, error) { + sr, segmented := remote.(ChunkSegmentReader) + if !chunkV11Format || !segmented { + head, err := remote.GetHead(l.ctx) + if err != nil { + return chunkHead{}, err + } + l.setHeadLocked(copyHeadEach(head, l.attachProgress.add)) // reports as it copies + return l.head, nil + } + refs := newRefTable(l.numChunks) + head, err := sr.EachSegment(l.ctx, func(first, end uint64, seg map[uint64]ChunkRef) error { + if first >= l.numChunks && len(seg) == 0 { + return nil + } + if err := refs.FillSegment(first, min(end, l.numChunks), seg); err != nil { + return err + } + l.attachProgress.add(uint64(len(seg))) + return nil + }) + if err != nil { + return chunkHead{}, err + } + head.Chunks = nil + l.head, l.refs = head, refs + return head, nil +} + +// ChunkSegmentReader is a remote that reads HEAD one segment at a time: +// HEAD's identity (no chunk listed), and fn called for each segment its +// root names with the segment's chunk range [first, end) and its +// references. A HEAD with no image calls fn never. +type ChunkSegmentReader interface { + EachSegment(ctx context.Context, fn func(first, end uint64, refs map[uint64]ChunkRef) error) (ChunkHead, error) +} + +// eachHeadChunkLocked calls f for every chunk HEAD names (O(S): whole-volume +// paths only). Caller holds stMu or owns the layer. +func (l *chunkLayerImpl) eachHeadChunkLocked(f func(idx uint64)) { + if l.refs != nil { + l.refs.each(func(i uint64, _ chunkRef) { f(i) }) return } - l.head = h - for _, idx := range changed { - if r, ok := h.Chunks[idx]; ok { - _ = l.refs.Set(idx, r) - } else { - l.refs.Delete(idx) - } + for idx := range l.head.Chunks { + f(idx) } } +// wholeHeadLocked is a copy of HEAD with every chunk listed: from the ref +// table on the v1.1 format (O(S): for the rare paths that need the whole +// image), else the flat map. Caller holds stMu. +func (l *chunkLayerImpl) wholeHeadLocked() chunkHead { + h := copyHead(l.head) + if l.refs != nil { + l.refs.each(func(i uint64, r chunkRef) { h.Chunks[i] = r }) + } + return h +} + +// headChunksLocked is HEAD's chunks as a map: the flat map itself, or on +// the v1.1 format a map built from the ref table (O(S)). Caller holds stMu. +func (l *chunkLayerImpl) headChunksLocked() map[uint64]chunkRef { + if l.refs == nil { + return l.head.Chunks + } + return l.wholeHeadLocked().Chunks +} + // headChunk is headRef's reference alone: the zero reference when HEAD names // none (a comparison with a named reference then fails, as a map read's // zero value did). Caller holds stMu. @@ -1514,7 +1557,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch inPlace := byChange && fromBase // cur is the cut's base: its candidates only finishCapturedCut(cur, h, nil, nil, inPlace) // nothing new: no CAS persistCapturedMap(capturedVersions) - return chunkCutResult{H: h, Head: l.cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil + return chunkCutResult{H: h, Head: cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} // On the v1.1 format the commit goes by change: one owned change set, @@ -1562,7 +1605,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch finishCapturedCut(next, h, changed, newKeys, changes != nil) l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) - return l.cutDone(chunkCutResult{H: h, Head: l.cutResultHead(next, changes != nil), FullHash: all}, detach), nil + return l.cutDone(chunkCutResult{H: h, Head: cutResultHead(next, changes != nil), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by // a blind retry. @@ -1666,7 +1709,7 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.stMu.Lock() fenced, pending, isDetach, base := l.fenced, l.pending, l.pendingDetach, l.pendingBase changes, marked := l.pendingChanges, l.pendingMarked - baseHead := copyHead(l.head) + baseHead := l.wholeHeadLocked() l.stMu.Unlock() if fenced { return detachFenced, chunkCutResult{}, nil @@ -1762,7 +1805,7 @@ func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { defer l.stMu.Unlock() if d := l.detached; d != nil { r := *d - r.Head = copyHead(d.Head) + r.Head = copyResultHead(d.Head) return r, true } return chunkCutResult{}, false @@ -1773,7 +1816,7 @@ func (l *chunkLayerImpl) cutDone(r chunkCutResult, detach bool) chunkCutResult { if detach { l.stMu.Lock() keep := r - keep.Head = copyHead(r.Head) + keep.Head = copyResultHead(r.Head) l.detached = &keep l.stMu.Unlock() } @@ -1938,7 +1981,7 @@ func proposalLanded(cur, next chunkHead, baseGen uint64, changes, marked map[uin // Caller holds stMu. func (l *chunkLayerImpl) cutBaseLocked(candidates map[uint64]bool) chunkHead { if !l.commitByChange() { - return copyHead(l.head) + return l.wholeHeadLocked() } b := l.head b.Chunks, b.Segments = nil, nil @@ -1962,17 +2005,23 @@ func proposalOf(next chunkHead, changes map[uint64]*chunkRef) chunkHead { return next } -// cutResultHead is the HEAD a cut reports, whole: h, or, when h names only -// the cut's chunks (byChange), the HEAD the commit installed (one copy, -// after the settlement, outside the barrier; it goes with the flat map in -// V4-B PR 4 commit 4). -func (l *chunkLayerImpl) cutResultHead(h chunkHead, byChange bool) chunkHead { - if !byChange { - return copyHead(h) +// cutResultHead is the HEAD a cut reports: h whole, or on the v1.1 format +// (byChange, h naming the cut's chunks only) HEAD's identity alone, Chunks +// nil: a cut's result is read for its generation, epoch and holder, and a +// whole copy per cut is the map the ref table replaces +// (TestNoProductionReaderOfACutResultsChunks). +func cutResultHead(h chunkHead, byChange bool) chunkHead { + out := copyHead(h) + if byChange { + out.Chunks, out.Segments = nil, nil } - l.stMu.Lock() - defer l.stMu.Unlock() - return copyHead(l.head) + return out +} + +// copyResultHead copies a cut's reported HEAD as it was reported: a result +// that reports identity only (Chunks nil) stays so. +func copyResultHead(h chunkHead) chunkHead { + return cutResultHead(h, h.Chunks == nil) } // changedIndices is a change set's indices. @@ -1996,9 +2045,10 @@ func headLookup(h chunkHead) func(uint64) (chunkRef, bool) { // it. The publication report, when one is wanted, gets whole HEADs. Caller // holds stMu. func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { - prev := l.head - if l.cfg.OnPublishSettled != nil { - prev = copyHead(l.head) + report := l.cfg.OnPublishSettled != nil && id.Gen != l.head.Gen + var prev chunkHead + if report { + prev = l.wholeHeadLocked() } h := l.head h.Gen, h.Epoch, h.Holder, h.RemoteLSN, h.State = id.Gen, id.Epoch, id.Holder, id.RemoteLSN, id.State @@ -2008,18 +2058,26 @@ func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { d := *id.DetachedBy h.DetachedBy = &d } - if h.Chunks == nil { - h.Chunks = map[uint64]chunkRef{} - } for _, idx := range changed { - if r, ok := id.Chunks[idx]; ok { + r, ok := id.Chunks[idx] + switch { + case l.refs != nil && ok: + _ = l.refs.Set(idx, r) + case l.refs != nil: + l.refs.Delete(idx) + case ok: + if h.Chunks == nil { + h.Chunks = map[uint64]chunkRef{} + } h.Chunks[idx] = r - } else { + default: delete(h.Chunks, idx) } } - l.setHeadChangedLocked(h, changed) - l.noteSettled(prev, l.head) + l.head = h + if report { + l.noteSettled(prev, l.wholeHeadLocked()) + } } func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { @@ -2098,10 +2156,7 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) if wasDetach { - cut.Head = copyHead(cur) - if inPlace { - cut.Head = copyHead(l.head) // cur names the cut's chunks only - } + cut.Head = cutResultHead(cur, inPlace) l.detached = &cut return errChunkLayerDetached } @@ -2131,7 +2186,7 @@ var errChunkForeignRoot = fmt.Errorf("%w: HEAD moved to a chunk root this holder // the one the layer holds; otherwise the layer is fenced // (errChunkForeignRoot). Caller holds stMu. func (l *chunkLayerImpl) adoptHeadLocked(cur chunkHead) error { - same := sameChunkRoot(l.head.Chunks, cur.Chunks) + same := sameChunkRoot(l.headChunksLocked(), cur.Chunks) l.setHeadLocked(copyHead(cur)) if !same { l.fenced = true @@ -2382,7 +2437,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap for _, idx := range batch { vers[idx] = l.chunkVersion(idx) // before the read: a later mutation raises it } - head := copyHead(l.head) + inBatch := make(map[uint64]bool, len(batch)) + for _, idx := range batch { + inBatch[idx] = true + } + head := l.cutBaseLocked(inBatch) l.stMu.Unlock() st.StageRounds++ st.CandidateChunks = max(st.CandidateChunks, len(batch)) @@ -2440,7 +2499,7 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n l.applyCommitLocked(head, changed) } else { l.noteSettled(l.head, head) - l.setHeadChangedLocked(copyHead(head), changed) + l.setHeadLocked(copyHead(head)) } l.remoteLSN, l.pending = h, nil l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil diff --git a/seaweed-block/core/storage/chunk_layer_cut_test.go b/seaweed-block/core/storage/chunk_layer_cut_test.go index 757f055eb0..e977270fe4 100644 --- a/seaweed-block/core/storage/chunk_layer_cut_test.go +++ b/seaweed-block/core/storage/chunk_layer_cut_test.go @@ -6,7 +6,13 @@ import ( "testing" ) +// A cut's result on the v1.1 format reports HEAD's identity only (Chunks +// nil): it is the same HEAD when that identity is b's. func sameHead(a, b chunkHead) bool { + if a.Chunks == nil && a.Gen != 0 { + return a.Gen == b.Gen && a.Epoch == b.Epoch && a.Holder == b.Holder && a.RemoteLSN == b.RemoteLSN && + a.State == b.State && (a.DetachedBy == nil) == (b.DetachedBy == nil) && (a.DetachedBy == nil || *a.DetachedBy == *b.DetachedBy) + } if a.Gen != b.Gen || a.Epoch != b.Epoch || a.Holder != b.Holder || a.RemoteLSN != b.RemoteLSN || len(a.Chunks) != len(b.Chunks) { return false } diff --git a/seaweed-block/core/storage/chunk_layer_races_test.go b/seaweed-block/core/storage/chunk_layer_races_test.go index 630db87880..38c8330cf3 100644 --- a/seaweed-block/core/storage/chunk_layer_races_test.go +++ b/seaweed-block/core/storage/chunk_layer_races_test.go @@ -134,7 +134,7 @@ func TestChunkLayer_StaleFillCannotInstallAfterReEviction(t *testing.T) { // share one flight, so two guest reads cannot create this overlap. impl := layer.(*chunkLayerImpl) impl.stMu.Lock() - oldGen, oldRef := impl.absentGen[2], impl.head.Chunks[2] + oldGen, oldRef := impl.absentGen[2], impl.headChunk(2) impl.stMu.Unlock() readA := make(chan error, 1) joinedA := make(chan struct{}) diff --git a/seaweed-block/core/storage/chunk_own.go b/seaweed-block/core/storage/chunk_own.go index 6b004e08ee..d4c2f5b6bd 100644 --- a/seaweed-block/core/storage/chunk_own.go +++ b/seaweed-block/core/storage/chunk_own.go @@ -30,7 +30,7 @@ func (l *chunkLayerImpl) OwnBatch(ctx context.Context, n int, foreign func(key s defer l.capMu.Unlock() l.stMu.Lock() var picked []uint64 - for _, idx := range sortedForeign(l.head.Chunks, foreign) { + for _, idx := range sortedForeign(l.headChunksLocked(), foreign) { if len(picked) < n && l.chunkLocalLocked(idx) { picked = append(picked, idx) } @@ -73,8 +73,8 @@ type ownCount struct { // ownProgressLocked counts HEAD's foreign chunks. Caller holds stMu. func (l *chunkLayerImpl) ownProgressLocked(foreign func(string) bool) ownCount { - c := ownCount{head: l.head.Chunks} - for _, idx := range sortedForeign(l.head.Chunks, foreign) { + c := ownCount{head: l.headChunksLocked()} + for _, idx := range sortedForeign(c.head, foreign) { c.Remaining++ if !l.chunkLocalLocked(idx) { c.NotLocal++ diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index 077c1f50cd..d29b006275 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -114,9 +114,9 @@ func TestV11LostCommitReplySettlesByChange(t *testing.T) { // On the v1.1 format a cut copies HEAD's chunks for its candidates only: its // base names those (at S and at S/16 chunks alike), and a landed commit -// changes HEAD in place (the same map, the changed chunk replaced), where -// the full form copied every chunk at the barrier, for the proposal and at -// the install. +// changes HEAD in place, its changed chunks only (a mark planted at an +// unchanged index survives it, where a whole install would replace it), with +// no flat map: the ref table is HEAD's chunks and equals the remote's. func TestV11CutCopiesOnlyItsCandidates(t *testing.T) { withV11Format(t) s, _ := v11Store(t) @@ -129,25 +129,32 @@ func TestV11CutCopiesOnlyItsCandidates(t *testing.T) { if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } + planted := chunkRef{Key: "planted", Encoding: "full"} l.stMu.Lock() - before := reflect.ValueOf(l.head.Chunks).Pointer() + real3, _ := l.headRef(3) + setHeadChunkForTest(l, 3, planted) // chunk 3 is not in the next cut l.stMu.Unlock() w.write(t, s, 2*ctChunkBlocks, 0x77) if _, err := l.Cut(ctTimeout(t)); err != nil { t.Fatal(err) } l.stMu.Lock() - after, n, ref2 := reflect.ValueOf(l.head.Chunks).Pointer(), len(l.head.Chunks), l.head.Chunks[2] + got3, _ := l.headRef(3) + setHeadChunkForTest(l, 3, real3) + whole, flat := l.wholeHeadLocked(), l.head.Chunks l.stMu.Unlock() - if after != before { - t.Fatal("a landed commit by change copied HEAD's chunk map instead of changing it in place") + if got3 != planted { + t.Fatal("a landed commit by change reinstalled HEAD whole instead of changing its changed chunks") + } + if flat != nil { + t.Fatalf("the layer keeps a flat map of %d chunks beside the ref table", len(flat)) } remote, err := f.GetHead(ctTimeout(t)) if err != nil { t.Fatal(err) } - if got := remote.Chunks; n != len(got) || ref2 != got[2] { - t.Fatalf("HEAD changed in place is not the remote's: %d chunks, chunk 2 %+v; remote %d, %+v", n, ref2, len(got), got[2]) + if !reflect.DeepEqual(whole.Chunks, remote.Chunks) { + t.Fatalf("HEAD changed in place is not the remote's: %d chunks, remote %d", len(whole.Chunks), len(remote.Chunks)) } for _, s := range []uint64{16384, 16384 / 16} { h := chunkHead{Gen: 5, Epoch: 1, Holder: "h", Chunks: make(map[uint64]chunkRef, s)} diff --git a/seaweed-block/core/storage/chunk_record_open.go b/seaweed-block/core/storage/chunk_record_open.go index 4574eabc93..803235fef6 100644 --- a/seaweed-block/core/storage/chunk_record_open.go +++ b/seaweed-block/core/storage/chunk_record_open.go @@ -52,7 +52,7 @@ func (l *chunkLayerImpl) openChunkRecordV11() (*chunkRecordShadow, error) { // the pages are valid through it). _, err := s.Sync() if err == nil { - seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, zero: l.zeroChunkSum()} + seed := &upgradeSeed{proof: l.cfg.CleanStop, head: l.head, ref: l.headRef, zero: l.zeroChunkSum()} err = upgradeChunkRecordSeeded(l.ctx, s, epoch, seed, l.attachProgress.add) } if h := testAfterChunkRecordUpgrade; h != nil { diff --git a/seaweed-block/core/storage/chunk_record_shadow_main_test.go b/seaweed-block/core/storage/chunk_record_shadow_main_test.go index 80a196dbe8..e8bbbd3493 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_main_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_main_test.go @@ -18,16 +18,6 @@ func TestMain(m *testing.M) { found = append(found, msg) mu.Unlock() } - // While the flat map and the ref table both exist (V4-B PR 4), every - // ref-table read is checked against the map: a difference is a finding. - if os.Getenv("REF_TABLE_MIRROR_CHILD") == "1" { - refTableMirror = true - } - refTableCheck = func(msg string) { - mu.Lock() - found = append(found, "ref table: "+msg) - mu.Unlock() - } // CHUNK_RECORD_V11=1 runs the whole package on the draft v1.1 store // format (the lab build's mode); it selects a format, it turns no check // off. diff --git a/seaweed-block/core/storage/chunk_record_shadow_test.go b/seaweed-block/core/storage/chunk_record_shadow_test.go index 1591befd2f..0252b6538e 100644 --- a/seaweed-block/core/storage/chunk_record_shadow_test.go +++ b/seaweed-block/core/storage/chunk_record_shadow_test.go @@ -158,7 +158,7 @@ func TestShadowFillRacedByAWriteEndsUnknown(t *testing.T) { t.Fatalf("an unraced fill: %s, want HP", k) } l.stMu.Lock() - want := l.head.Chunks[3].SHA256 + want := l.headChunk(3).SHA256 l.stMu.Unlock() l.shadow.rec.mu.Lock() got := l.shadow.rec.hashes[3] diff --git a/seaweed-block/core/storage/chunk_record_upgrade.go b/seaweed-block/core/storage/chunk_record_upgrade.go index 48bd87b7b1..e1f974b509 100644 --- a/seaweed-block/core/storage/chunk_record_upgrade.go +++ b/seaweed-block/core/storage/chunk_record_upgrade.go @@ -195,7 +195,10 @@ type ChunkCleanStop struct { type upgradeSeed struct { proof *ChunkCleanStop head chunkHead - zero [32]byte + // ref reads HEAD's chunks (the layer's ref table on the v1.1 format, + // where head lists none); nil: head.Chunks. + ref func(idx uint64) (chunkRef, bool) + zero [32]byte } // seedsLineage is the seed's lineage condition (the model's SameEpoch, by @@ -232,9 +235,12 @@ func cleanStopHashes(seed *upgradeSeed, pos uint64) func(uint64) [32]byte { return nil } log.Printf("level=INFO storage: chunk record upgrade: clean-stop seed at %d: whole local chunks take HEAD's hash", pos) - head, zero := seed.head, seed.zero + ref, zero := seed.ref, seed.zero + if ref == nil { + ref = headLookup(seed.head) + } return func(chunk uint64) [32]byte { - if ref, ok := head.Chunks[chunk]; ok { + if ref, ok := ref(chunk); ok { return ref.SHA256 } return zero diff --git a/seaweed-block/core/storage/chunk_ref_table_mirror_test.go b/seaweed-block/core/storage/chunk_ref_table_mirror_test.go deleted file mode 100644 index 7f36d0b55e..0000000000 --- a/seaweed-block/core/storage/chunk_ref_table_mirror_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package storage - -import ( - "os" - "os/exec" - "strings" - "testing" -) - -// setHeadChunkForTest replaces one chunk's reference in the layer's HEAD, as -// a HEAD install would (the ref table follows when it is kept). -func setHeadChunkForTest(l *chunkLayerImpl, idx uint64, ref chunkRef) { - l.head.Chunks[idx] = ref - if l.refs != nil { - _ = l.refs.Set(idx, ref) - } -} - -// The ref table, kept beside the flat map, names exactly what the map names -// through every HEAD install the layer makes: attach, cuts (the changed -// chunks only), settlement, adoption, a fence. The package's cut, settle, -// hydration and fill suites run on the v1.1 format with the table kept and -// every table read checked against the map (refTableCheck: a difference is -// a finding, which fails the run). A child run, so the table's switch and -// the format are this test's alone. -func TestRefTableMirrorsHeadThroughTheLayer(t *testing.T) { - if os.Getenv("REF_TABLE_MIRROR_CHILD") == "1" { - t.Skip("the child run itself") - } - if testing.Short() { - t.Skip("runs the cut suites in a child process") - } - cmd := exec.Command(os.Args[0], "-test.run", "Cut|Settle|Pending|Hydrat|Fill|Evict|Adopt|Detach|Fresh|Clean|V11|Shadow|RefTable", "-test.count=1") - cmd.Env = append(os.Environ(), "REF_TABLE_MIRROR_CHILD=1", "CHUNK_RECORD_V11=1") - out, _ := cmd.CombinedOutput() - if strings.Contains(string(out), "ref table: ") { - i := strings.Index(string(out), "ref table: ") - t.Fatalf("the ref table and the flat map differ: %s", string(out)[i:min(len(out), i+400)]) - } - if !strings.Contains(string(out), "ok") && !strings.Contains(string(out), "FAIL") { - t.Fatalf("the child run reported nothing: %s", out) - } -} diff --git a/seaweed-block/core/storage/chunk_space_baseline_test.go b/seaweed-block/core/storage/chunk_space_baseline_test.go index c885a0ccc9..03c493a2eb 100644 --- a/seaweed-block/core/storage/chunk_space_baseline_test.go +++ b/seaweed-block/core/storage/chunk_space_baseline_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/sha256" "fmt" - "os" "runtime" "strings" "testing" @@ -130,7 +129,13 @@ func TestSpaceMeasurementControls(t *testing.T) { long := strings.Repeat("v", 101) // a 100-byte longer owner name longer := heldPerChunk(t, chunks, 1, long) t.Logf("held per chunk with keys 100 B longer: %.0f B (+%.0f)", longer, longer-geo[1]) - if longer-geo[1] < 60 || longer-geo[1] > 160 { + if chunkV11Format { + // The ref table derives canonical keys from an interned owner prefix: + // a longer owner name costs once, not per chunk. + if d := longer - geo[1]; d > 10 || d < -10 { + t.Fatalf("keys 100 B longer moved the ref table's held heap by %.0f B/chunk, want about 0 (owner prefix interned)", d) + } + } else if longer-geo[1] < 60 || longer-geo[1] > 160 { t.Fatalf("keys 100 B longer moved the held heap by %.0f B/chunk, want about 100", longer-geo[1]) } } @@ -139,9 +144,10 @@ func TestSpaceMeasurementControls(t *testing.T) { // chunk for a 1 TiB volume's chunk count (262,144; one-block chunks, which // TestSpaceMeasurementControls shows stand for 4 MiB ones), every chunk // named by HEAD with canonical keys owned by the layer, after GC once the -// layer is attached. With CHUNK_SPACE_RED=1 it asserts the target, at most -// 200 B per chunk, which fails until PR 4 drops the flat map. +// layer is attached, on the v1.1 format (the layer keeps HEAD's chunks in +// the ref table, no flat map): at most 200 B per chunk. func TestSpacePerChunkAt1TiBShape(t *testing.T) { + withV11Format(t) const chunks = 262144 m0 := heapNow() oneMap := fullHead(chunks, "v1") @@ -151,8 +157,8 @@ func TestSpacePerChunkAt1TiBShape(t *testing.T) { per := heldPerChunk(t, chunks, 1, "v1") t.Logf("SPACE at 1 TiB's chunk count (%d chunks, v1.1 format %v, canonical %d-byte keys): %.0f B/chunk held after attach; one flat map with its keys is %.0f B/chunk", chunks, chunkV11Format, len(canonicalKey("v1", "309016fbc5b31531e1e7c44585851c7d", chunks-1, [32]byte{})), per, flat) - if os.Getenv("CHUNK_SPACE_RED") == "1" && per > 200 { - t.Fatalf("SPACE red: %.0f B/chunk, want at most 200", per) + if per > 200 { + t.Fatalf("SPACE: %.0f B/chunk held, want at most 200", per) } } From 2caed63f04d05b3b20927e0c19858e5d5ec01bea Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:41:47 -0800 Subject: [PATCH 25/51] master: the line-wake test waits on a settled observation host, not a sleep ObservationHost.BuildsForTest reports the builds completed and whether a wake is buffered or a build is running. The test settles the host before the heartbeat, requires the heartbeat's build to be a new one, settles again after the controller's publication, and then requires the line in a build after that point (or in the settled last build, which can only have come after the publication). Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_host.go | 21 ++++++- .../core/host/master/line_change_wake_test.go | 61 +++++++++++++++---- 2 files changed, 68 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 3dbbc81085..301a271be4 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -3,6 +3,7 @@ package authority import ( "context" "sync" + "sync/atomic" "time" ) @@ -57,8 +58,12 @@ type ObservationHost struct { sink ControllerSink reader AuthorityBasisReader - mu sync.Mutex - lastBuild *BuildResult + mu sync.Mutex + lastBuild *BuildResult + // builds counts completed rebuilds and building is set while one runs + // (BuildsForTest). + builds atomic.Uint64 + building atomic.Bool sinkErrors []error wake chan struct{} @@ -118,6 +123,13 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } +// BuildsForTest reports the rebuilds completed and whether the host is +// settled (no wake buffered, no rebuild running), so a test can order a +// change after every earlier build. Production code MUST NOT call this. +func (h *ObservationHost) BuildsForTest() (builds uint64, settled bool) { + return h.builds.Load(), len(h.wake) == 0 && !h.building.Load() +} + // Wake asks for a rebuild: a change a build reads that no heartbeat // carries (a published authority line, a topology change). Non-blocking; // wakes coalesce. @@ -281,6 +293,11 @@ func (h *ObservationHost) run(ctx context.Context) { // AND no report entries is a genuine no-op (e.g. start-up // before any ingest) and is skipped. func (h *ObservationHost) rebuildOnce() { + h.building.Store(true) + defer func() { + h.builds.Add(1) + h.building.Store(false) + }() snap := h.store.Snapshot() result := BuildSnapshot(snap, h.topology, h.reader) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 6f07a6bb50..347f75b417 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -38,28 +38,47 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) - waitBuild := func(what string, ok func(authority.BuildResult) bool) authority.BuildResult { + // settle waits until no wake is buffered and no rebuild runs, twice in a + // row with the same count (a deadline timer could fire in between), and + // returns the count. + settle := func(what string) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - if b, have := h.obs.LastBuild(); have && ok(b) { - return b + n1, ok1 := h.obs.BuildsForTest() + time.Sleep(50 * time.Millisecond) + n2, ok2 := h.obs.BuildsForTest() + if ok1 && ok2 && n1 == n2 && n1 > 0 { + return n2 + } + } + t.Fatalf("%s: the observation host did not settle", what) + return 0 + } + waitAfter := func(what string, after uint64, ok func(authority.BuildResult) bool) uint64 { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + n, _ := h.obs.BuildsForTest() + if b, have := h.obs.LastBuild(); have && n > after && ok(b) { + return n } time.Sleep(10 * time.Millisecond) } b, _ := h.obs.LastBuild() - t.Fatalf("%s: last build %+v", what, b.Snapshot.Volumes) - return authority.BuildResult{} + t.Fatalf("%s: no build after #%d satisfied it; last build %+v", what, after, b.Snapshot.Volumes) + return 0 } - waitBuild("the initial build", func(authority.BuildResult) bool { return true }) - time.Sleep(300 * time.Millisecond) // the grace's deadline fires and its rebuild drains + // The initial build and the 1 ms grace's rebuild, drained. + before := settle("startup") if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - waitBuild("the heartbeat's build (v1 supported)", func(b authority.BuildResult) bool { + // The heartbeat's build: a new build, v1 supported. + waitAfter("the heartbeat's build", before, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" { return true @@ -67,11 +86,29 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } return false }) - waitBuild("the build after the controller's publication", func(b authority.BuildResult) bool { - line, ok := h.Publisher().VolumeAuthorityLine("v1") - if !ok || !line.Assigned { - return false + // The controller binds v1; its publication is the only wake left. + for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { + break } + if time.Now().After(wait) { + t.Fatal("the controller did not bind v1") + } + } + line, _ := h.Publisher().VolumeAuthorityLine("v1") + // Settled again: any build the heartbeat's wake caused has run. If the + // last build already carries the line, it came after the publication, + // so from the hook (the heartbeat's single wake was consumed by a build + // that saw no line); otherwise a later build must bring it. + settled := settle("after the publication") + if b, have := h.obs.LastBuild(); have { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { + return + } + } + } + waitAfter("the build after the publication", settled, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { return true From db7f6530a3c43322e8451ef8d84218d68e6da960 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:48:58 -0800 Subject: [PATCH 26/51] authority: a counter handshake orders the master's line-wake test The observation host counts the rebuilds it takes (in the step that takes the wake) and the rebuilds it finishes, and records when its armed deadline timer fires, all under its lock; BuildsForTest returns them with whether a wake is buffered. The master test settles on started == done with no buffered wake and no timer due, records N, ingests one heartbeat (build N+1, v1 supported and unbound), and after the controller's publication requires build N+2 to carry the line: only the hook can take it. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/observation_host.go | 49 +++++++++---- .../core/host/master/line_change_wake_test.go | 70 ++++++++----------- 2 files changed, 66 insertions(+), 53 deletions(-) diff --git a/seaweed-block/core/authority/observation_host.go b/seaweed-block/core/authority/observation_host.go index 301a271be4..d1d851bbe7 100644 --- a/seaweed-block/core/authority/observation_host.go +++ b/seaweed-block/core/authority/observation_host.go @@ -3,7 +3,6 @@ package authority import ( "context" "sync" - "sync/atomic" "time" ) @@ -60,11 +59,12 @@ type ObservationHost struct { mu sync.Mutex lastBuild *BuildResult - // builds counts completed rebuilds and building is set while one runs - // (BuildsForTest). - builds atomic.Uint64 - building atomic.Bool - sinkErrors []error + // buildsStarted counts rebuilds the loop took (in the step that takes + // their wake), buildsDone the rebuilds finished, timerAt when the armed deadline + // timer fires (zero: none); all under mu (BuildsForTest). + buildsStarted, buildsDone uint64 + timerAt time.Time + sinkErrors []error wake chan struct{} stop chan struct{} @@ -123,11 +123,22 @@ func NewObservationHost(cfg ObservationHostConfig) *ObservationHost { return h } -// BuildsForTest reports the rebuilds completed and whether the host is -// settled (no wake buffered, no rebuild running), so a test can order a -// change after every earlier build. Production code MUST NOT call this. -func (h *ObservationHost) BuildsForTest() (builds uint64, settled bool) { - return h.builds.Load(), len(h.wake) == 0 && !h.building.Load() +// BuildsForTest reports, under one lock, the rebuilds the loop took and +// finished, whether a wake is buffered, and when the armed deadline timer +// fires (zero: none), so a test can order a change after every earlier +// build. Production code MUST NOT call this. +func (h *ObservationHost) BuildsForTest() (started, done uint64, wakeBuffered bool, timerAt time.Time) { + h.mu.Lock() + defer h.mu.Unlock() + return h.buildsStarted, h.buildsDone, len(h.wake) > 0, h.timerAt +} + +// takeBuild counts a rebuild the loop takes, in the step that takes it. +func (h *ObservationHost) takeBuild() { + h.mu.Lock() + h.buildsStarted++ + h.timerAt = time.Time{} + h.mu.Unlock() } // Wake asks for a rebuild: a change a build reads that no heartbeat @@ -237,6 +248,7 @@ func (h *ObservationHost) run(ctx context.Context) { // First build on start — so consumers see an initial empty // snapshot rather than waiting for the first ingest. + h.takeBuild() h.rebuildOnce() for { @@ -252,6 +264,9 @@ func (h *ObservationHost) run(ctx context.Context) { } timer = time.NewTimer(d) deadlineC = timer.C + h.mu.Lock() + h.timerAt = time.Now().Add(d) + h.mu.Unlock() } stopTimer := func() { if timer != nil { @@ -267,10 +282,16 @@ func (h *ObservationHost) run(ctx context.Context) { return case <-h.wake: stopTimer() + h.takeBuild() h.rebuildOnce() case <-deadlineC: if h.store.ExpireDue() { + h.takeBuild() h.rebuildOnce() + } else { + h.mu.Lock() + h.timerAt = time.Time{} + h.mu.Unlock() } case <-gcC: stopTimer() @@ -293,10 +314,10 @@ func (h *ObservationHost) run(ctx context.Context) { // AND no report entries is a genuine no-op (e.g. start-up // before any ingest) and is skipped. func (h *ObservationHost) rebuildOnce() { - h.building.Store(true) defer func() { - h.builds.Add(1) - h.building.Store(false) + h.mu.Lock() + h.buildsDone++ + h.mu.Unlock() }() snap := h.store.Snapshot() result := BuildSnapshot(snap, h.topology, h.reader) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 347f75b417..3e9d47fef5 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -38,47 +38,57 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } h.Start() defer closeTestMaster(t, h) - // settle waits until no wake is buffered and no rebuild runs, twice in a - // row with the same count (a deadline timer could fire in between), and - // returns the count. + // settle waits until every build the loop took has finished, no wake is + // buffered and no deadline timer fires within the test (the one-hour + // expiry timer stays armed), all read under the host's lock; it returns + // the builds done. settle := func(what string) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - n1, ok1 := h.obs.BuildsForTest() - time.Sleep(50 * time.Millisecond) - n2, ok2 := h.obs.BuildsForTest() - if ok1 && ok2 && n1 == n2 && n1 > 0 { - return n2 + started, done, buffered, timerAt := h.obs.BuildsForTest() + if started == done && done > 0 && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { + return done } + time.Sleep(10 * time.Millisecond) } t.Fatalf("%s: the observation host did not settle", what) return 0 } - waitAfter := func(what string, after uint64, ok func(authority.BuildResult) bool) uint64 { + waitDone := func(what string, n uint64, ok func(authority.BuildResult) bool) { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { - n, _ := h.obs.BuildsForTest() - if b, have := h.obs.LastBuild(); have && n > after && ok(b) { - return n + _, done, _, _ := h.obs.BuildsForTest() + if b, have := h.obs.LastBuild(); have && done >= n && ok(b) { + return } time.Sleep(10 * time.Millisecond) } b, _ := h.obs.LastBuild() - t.Fatalf("%s: no build after #%d satisfied it; last build %+v", what, after, b.Snapshot.Volumes) - return 0 + t.Fatalf("%s: no build #%d satisfied it; last build %+v", what, n, b.Snapshot.Volumes) } - // The initial build and the 1 ms grace's rebuild, drained. - before := settle("startup") + carriesLine := func(epoch uint64) func(authority.BuildResult) bool { + return func(b authority.BuildResult) bool { + for _, v := range b.Snapshot.Volumes { + if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == epoch { + return true + } + } + return false + } + } + // The initial build and the 1 ms grace's rebuild, finished. + n := settle("startup") if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, }); err != nil { t.Fatal(err) } - // The heartbeat's build: a new build, v1 supported. - waitAfter("the heartbeat's build", before, func(b authority.BuildResult) bool { + // The heartbeat's one build (#n+1) shows v1 supported and unbound: the + // controller binds only after it. + waitDone("the heartbeat's build", n+1, func(b authority.BuildResult) bool { for _, v := range b.Snapshot.Volumes { if v.VolumeID == "v1" { return true @@ -86,7 +96,6 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } return false }) - // The controller binds v1; its publication is the only wake left. for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { break @@ -96,24 +105,7 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { } } line, _ := h.Publisher().VolumeAuthorityLine("v1") - // Settled again: any build the heartbeat's wake caused has run. If the - // last build already carries the line, it came after the publication, - // so from the hook (the heartbeat's single wake was consumed by a build - // that saw no line); otherwise a later build must bring it. - settled := settle("after the publication") - if b, have := h.obs.LastBuild(); have { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return - } - } - } - waitAfter("the build after the publication", settled, func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == line.Epoch { - return true - } - } - return false - }) + // Every build after the heartbeat's was taken after the publication (no + // other wake was left): the hook's. One must come and carry the line. + waitDone("the hook's build", n+2, carriesLine(line.Epoch)) } From d17696d1ea4e45604a35d892ebb6e8a31b76a088 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:52:35 -0800 Subject: [PATCH 27/51] master: the line-wake test waits for the grace's rebuild (build 2) before the heartbeat Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 3e9d47fef5..44fbc9c9f4 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -42,12 +42,12 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { // buffered and no deadline timer fires within the test (the one-hour // expiry timer stays armed), all read under the host's lock; it returns // the builds done. - settle := func(what string) uint64 { + settle := func(what string, atLeast uint64) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) for time.Now().Before(deadline) { started, done, buffered, timerAt := h.obs.BuildsForTest() - if started == done && done > 0 && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { + if started == done && done >= atLeast && !buffered && (timerAt.IsZero() || timerAt.After(time.Now().Add(time.Minute))) { return done } time.Sleep(10 * time.Millisecond) @@ -78,8 +78,10 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { return false } } - // The initial build and the 1 ms grace's rebuild, finished. - n := settle("startup") + // The initial build (#1) and the 1 ms grace's rebuild (#2, with nothing + // ingested yet) both finished: the grace's deadline is consumed, so no + // timer can arm after this point and see the heartbeat. + n := settle("startup", 2) if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, From 774f2ef4a4639d963f96fc78fbbbed0a6adcf0ed Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:47:49 -0800 Subject: [PATCH 28/51] storage: v1.1 settlements report the whole previous image; results keep no map On the v1.1 format the layer's HEAD keeps no chunk map, so a settlement that installs a HEAD read whole (a lost reply read back, a re-proposal read back, a detach settled) now reports the previous image built from the ref table, and every cut, settlement and detach outcome reports and keeps HEAD's identity only (a no-op cut and a settled detach returned and kept whole maps). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 33 +++- .../storage/chunk_proposal_by_change_test.go | 12 +- .../core/storage/chunk_v11_outcomes_test.go | 174 ++++++++++++++++++ 3 files changed, 209 insertions(+), 10 deletions(-) create mode 100644 seaweed-block/core/storage/chunk_v11_outcomes_test.go diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index d8b08b7cab..9f4d6c18f3 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1557,7 +1557,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch inPlace := byChange && fromBase // cur is the cut's base: its candidates only finishCapturedCut(cur, h, nil, nil, inPlace) // nothing new: no CAS persistCapturedMap(capturedVersions) - return chunkCutResult{H: h, Head: cutResultHead(cur, inPlace), Noop: true, FullHash: all}, nil + return chunkCutResult{H: h, Head: resultHead(cur), Noop: true, FullHash: all}, nil } expected := chunkHeadVersion{Gen: baseHead.Gen, Epoch: baseHead.Epoch} // On the v1.1 format the commit goes by change: one owned change set, @@ -1605,7 +1605,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch finishCapturedCut(next, h, changed, newKeys, changes != nil) l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) - return l.cutDone(chunkCutResult{H: h, Head: cutResultHead(next, changes != nil), FullHash: all}, detach), nil + return l.cutDone(chunkCutResult{H: h, Head: resultHead(next), FullHash: all}, detach), nil } // Precondition or unknown outcome: resolve by re-reading HEAD, never by // a blind retry. @@ -1649,7 +1649,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch finishCapturedCut(cur, h, changed, newKeys, false) // cur is HEAD as read: whole l.shadowCommit(captured, capturedVersions) persistCapturedMap(capturedVersions) - return l.cutDone(chunkCutResult{H: h, Head: copyHead(cur), FullHash: all}, detach), nil + return l.cutDone(chunkCutResult{H: h, Head: resultHead(cur), FullHash: all}, detach), nil } // HEAD moved past the CAS's base without it: it can never land, and // what it staged was compared against a HEAD that is gone. @@ -1761,14 +1761,14 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.pendingCaptured, l.pendingChanges, l.pendingMarked = nil, nil, nil switch { case proposalLanded(cur, *pending, base.Gen, changes, marked): - l.noteSettled(l.head, cur) + l.noteSettledFromHeadLocked(cur) l.setHeadLocked(copyHead(cur)) l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) - cut.Head = copyHead(cur) + cut.Head = resultHead(cur) l.detached = &cut r := cut - r.Head = copyHead(cur) + r.Head = resultHead(cur) return detachApplied, r, nil case l.supersededBy(cur): l.fenced = true @@ -2018,6 +2018,21 @@ func cutResultHead(h chunkHead, byChange bool) chunkHead { return out } +// resultHead is the HEAD every cut, settlement and detach outcome reports and +// keeps: identity only on the v1.1 format, on every path (a whole read's, +// a re-proposal's, a no-op's), so no result holds a chunk map; whole before. +func resultHead(h chunkHead) chunkHead { return cutResultHead(h, chunkV11Format) } + +// noteSettledFromHeadLocked records the publication from the layer's HEAD, +// whole (the ref table's image on the v1.1 format), to next, before next is +// installed. Caller holds stMu. +func (l *chunkLayerImpl) noteSettledFromHeadLocked(next chunkHead) { + if l.cfg.OnPublishSettled == nil || next.Gen == l.head.Gen { + return + } + l.noteSettled(l.wholeHeadLocked(), next) +} + // copyResultHead copies a cut's reported HEAD as it was reported: a result // that reports identity only (Chunks nil) stays so. func copyResultHead(h chunkHead) chunkHead { @@ -2150,13 +2165,13 @@ func (l *chunkLayerImpl) resolvePending(ctx context.Context) (err error) { if inPlace { l.applyCommitLocked(cur, changedIndices(changes)) } else { - l.noteSettled(l.head, cur) + l.noteSettledFromHeadLocked(cur) l.setHeadLocked(copyHead(cur)) } l.remoteLSN = cur.RemoteLSN l.shadowCommitCaptured(landed, true) if wasDetach { - cut.Head = cutResultHead(cur, inPlace) + cut.Head = resultHead(cur) l.detached = &cut return errChunkLayerDetached } @@ -2498,7 +2513,7 @@ func (l *chunkLayerImpl) finishCut(head chunkHead, h uint64, changed []uint64, n if inPlace { l.applyCommitLocked(head, changed) } else { - l.noteSettled(l.head, head) + l.noteSettledFromHeadLocked(head) l.setHeadLocked(copyHead(head)) } l.remoteLSN, l.pending = h, nil diff --git a/seaweed-block/core/storage/chunk_proposal_by_change_test.go b/seaweed-block/core/storage/chunk_proposal_by_change_test.go index d29b006275..b0c574ccdd 100644 --- a/seaweed-block/core/storage/chunk_proposal_by_change_test.go +++ b/seaweed-block/core/storage/chunk_proposal_by_change_test.go @@ -107,9 +107,19 @@ func TestV11LostCommitReplySettlesByChange(t *testing.T) { if err != nil { t.Fatalf("a landed commit by change whose reply was lost: %v", err) } - if res.Head.Chunks[9] != res.Head.Chunks[2] { + cur, err := f.GetHead(ctTimeout(t)) // HEAD as read back (the hook changed it after the install) + if err != nil { + t.Fatal(err) + } + if res.Head.Gen != cur.Gen || cur.Chunks[9] != cur.Chunks[2] { t.Fatal("the settled HEAD is not the one read back") } + l.stMu.Lock() + got9 := l.headChunk(9) + l.stMu.Unlock() + if got9 != cur.Chunks[9] { + t.Fatal("the layer did not install the HEAD it read back") + } } // On the v1.1 format a cut copies HEAD's chunks for its candidates only: its diff --git a/seaweed-block/core/storage/chunk_v11_outcomes_test.go b/seaweed-block/core/storage/chunk_v11_outcomes_test.go new file mode 100644 index 0000000000..e0d660c7c5 --- /dev/null +++ b/seaweed-block/core/storage/chunk_v11_outcomes_test.go @@ -0,0 +1,174 @@ +package storage + +import ( + "context" + "errors" + "reflect" + "sync" + "testing" +) + +// v11ReportLayer is a v1.1 layer over a fake remote with chunks 0 and 1 +// published, recording every publication report from then on. +func v11ReportLayer(t *testing.T) (*WALStore, *fakeChunkRemote, *chunkLayerImpl, *writeLog, func() [][2]chunkHead) { + t.Helper() + withV11Format(t) + s, _ := v11Store(t) + f := newFakeChunkRemote() + l := v11Attach(t, s, f) + w := newWriteLog() + w.write(t, s, 0, 0x10) + w.write(t, s, ctChunkBlocks, 0x11) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var got [][2]chunkHead + l.cfg.OnPublishSettled = func(_ context.Context, prev, next ChunkHead) { + mu.Lock() + got = append(got, [2]chunkHead{prev, next}) + mu.Unlock() + } + return s, f, l, w, func() [][2]chunkHead { mu.Lock(); defer mu.Unlock(); return append([][2]chunkHead(nil), got...) } +} + +// checkReportedWhole: the first report after the hook went on names the +// remote's HEAD before the settled one as prev, whole, and the settled one +// as next, whole. +func checkReportedWhole(t *testing.T, f *fakeChunkRemote, reports [][2]chunkHead) { + t.Helper() + if len(reports) == 0 { + t.Fatal("the settlement reported no publication") + } + prev, next := reports[0][0], reports[0][1] + heads := f.installedHeads() + var before, settled chunkHead + for _, h := range heads { + if h.Gen == next.Gen { + settled = h + } + if h.Gen == prev.Gen { + before = h + } + } + if len(before.Chunks) == 0 || !reflect.DeepEqual(prev.Chunks, before.Chunks) { + t.Fatalf("the report's prev (gen %d) names %d chunks; the remote's HEAD then named %d", prev.Gen, len(prev.Chunks), len(before.Chunks)) + } + if !reflect.DeepEqual(next.Chunks, settled.Chunks) { + t.Fatalf("the report's next (gen %d) names %d chunks; the remote's HEAD names %d", next.Gen, len(next.Chunks), len(settled.Chunks)) + } +} + +// On the v1.1 format, where the layer's HEAD keeps no chunk map, every +// settlement that installs a HEAD read whole reports the previous image +// whole, from the ref table: a lost reply read back, a re-proposal read +// back, a detach settled. +func TestV11SettlementsReportTheWholePreviousImage(t *testing.T) { + t.Run("lost reply read back", func(t *testing.T) { + s, f, l, w, reports := v11ReportLayer(t) + w.write(t, s, 2*ctChunkBlocks, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + checkReportedWhole(t, f, reports()) + }) + t.Run("re-proposal read back", func(t *testing.T) { + s, f, l, w, reports := v11ReportLayer(t) + w.write(t, s, 2*ctChunkBlocks, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casUnknownNotApplied, casAppliedLost} + f.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("cut with an unknown outcome: %v", err) + } + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatalf("settling cut: %v", err) + } + checkReportedWhole(t, f, reports()) + }) + t.Run("detach settled", func(t *testing.T) { + s, f, l, w, reports := v11ReportLayer(t) + w.write(t, s, 2*ctChunkBlocks, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } + f.mu.Unlock() + if _, err := l.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("detach with an unresolved CAS: %v", err) + } + healRemote(f) + if settled, _, err := l.SettleDetach(ctTimeout(t)); err != nil || settled != detachApplied { + t.Fatalf("SettleDetach: %v %v, want applied", settled, err) + } + checkReportedWhole(t, f, reports()) + }) +} + +// On the v1.1 format every outcome reports and keeps HEAD's identity only: +// a no-op cut, a lost reply read back, a detach and its repeat, a settled +// detach; a detached layer holds no chunk map. +func TestV11OutcomesKeepNoChunkMap(t *testing.T) { + noMap := func(t *testing.T, what string, h chunkHead) { + t.Helper() + if h.Gen == 0 || h.Chunks != nil || h.Segments != nil { + t.Fatalf("%s: gen %d, %d chunks, %d segments; want HEAD's identity only", what, h.Gen, len(h.Chunks), len(h.Segments)) + } + } + t.Run("no-op and read back", func(t *testing.T) { + s, f, l, w, _ := v11ReportLayer(t) + r, err := l.Cut(ctTimeout(t)) + if err != nil || !r.Noop { + t.Fatalf("no-op cut: %+v %v", r, err) + } + noMap(t, "a no-op cut", r.Head) + w.write(t, s, 2*ctChunkBlocks, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.mu.Unlock() + if r, err = l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + noMap(t, "a lost reply read back", r.Head) + }) + t.Run("detach", func(t *testing.T) { + _, _, l, _, _ := v11ReportLayer(t) + r, err := l.Detach(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + noMap(t, "a detach", r.Head) + again, err := l.Detach(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + noMap(t, "a repeated detach", again.Head) + l.stMu.Lock() + kept := l.detached.Head + l.stMu.Unlock() + noMap(t, "the detached layer's kept result", kept) + }) + t.Run("detach settled", func(t *testing.T) { + s, f, l, w, _ := v11ReportLayer(t) + w.write(t, s, 2*ctChunkBlocks, 0x22) + f.mu.Lock() + f.casModes = []fakeCASMode{casAppliedLost} + f.beforeCAS = func(f *fakeChunkRemote) { f.failGet = errFakeRemoteDown } + f.mu.Unlock() + if _, err := l.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("detach with an unresolved CAS: %v", err) + } + healRemote(f) + _, r, err := l.SettleDetach(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + noMap(t, "a settled detach", r.Head) + l.stMu.Lock() + kept := l.detached.Head + l.stMu.Unlock() + noMap(t, "the settled layer's kept result", kept) + }) +} From a8d2a6e6c6a1e40ac6f0996e529a80c2c9b77c45 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 13:55:23 -0800 Subject: [PATCH 29/51] authority: renewals write nothing; waits use the master's own deadline; records are version 2 A renewal grants now+TTL from memory and writes nothing: the persisted horizon, its clamp, its background extension and its counters are gone. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew (its latest grant, or after a restart the restart floor it already set at load); no lease value an earlier process wrote is read. An authority record's envelope is now version 2, which a v1.0.x master refuses (it would trust the record's stale lease expiry); this master reads versions 1 and 2. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/authority.go | 10 +- .../core/authority/authority_store.go | 12 +- .../core/authority/golden_v100_test.go | 11 + seaweed-block/core/authority/workspace.go | 20 +- .../authority/workspace_delete_guard_test.go | 3 +- .../workspace_delete_reservation_test.go | 20 +- .../authority/workspace_issue_publish_test.go | 1 - .../authority/workspace_lease_horizon_test.go | 776 ------------------ .../core/authority/workspace_lease_stats.go | 229 ------ .../authority/workspace_lease_stats_test.go | 393 --------- .../core/authority/workspace_lease_view.go | 181 +--- .../workspace_outcome_uncertain_test.go | 1 - .../core/authority/workspace_regrant_test.go | 3 - .../workspace_renewal_slowstore_test.go | 5 - .../workspace_restart_barrier_test.go | 2 - .../authority/workspace_restart_grace_test.go | 82 ++ .../workspace_unclaimed_grant_test.go | 1 - seaweed-block/core/host/master/host.go | 4 - .../core/host/master/journal_isolation.go | 37 +- .../host/master/journal_isolation_test.go | 12 +- .../master/workspace_lease_horizon_test.go | 32 +- .../workspace_renewal_slowstore_test.go | 1 - .../docs/design/agent-workspace-design.md | 14 +- seaweed-block/docs/design/invariants.md | 24 +- 24 files changed, 199 insertions(+), 1675 deletions(-) delete mode 100644 seaweed-block/core/authority/workspace_lease_stats.go delete mode 100644 seaweed-block/core/authority/workspace_lease_stats_test.go create mode 100644 seaweed-block/core/authority/workspace_restart_grace_test.go diff --git a/seaweed-block/core/authority/authority.go b/seaweed-block/core/authority/authority.go index 30cafb9342..8dc3081f13 100644 --- a/seaweed-block/core/authority/authority.go +++ b/seaweed-block/core/authority/authority.go @@ -175,13 +175,8 @@ type Publisher struct { // Lease renewal state (workspace_lease_view.go). leaseMu is a memory-only // leaf: lock order p.mu -> leaseMu, never the reverse, and nothing is // acquired, waited on or written while it is held. - leaseMu sync.Mutex - leaseViews map[string]*leaseView - leaseClosing bool - leaseStats leaseCounters // guarded by leaseMu - leaseLog func(string) // renewal-path notes; nil = log.Print (test seam) - extWG sync.WaitGroup - extendFailures map[string]int // guarded by mu + leaseMu sync.Mutex + leaseViews map[string]*leaseView // testAfterIssuePublish, when set by a test, runs under mu right after // an issued move's lease view is published. @@ -256,7 +251,6 @@ func NewPublisher(dir Directive, opts ...PublisherOption) *Publisher { workspaceNow: time.Now, workspaceTTL: 30 * time.Second, leaseViews: map[string]*leaseView{}, - extendFailures: map[string]int{}, } for _, opt := range opts { if opt != nil { diff --git a/seaweed-block/core/authority/authority_store.go b/seaweed-block/core/authority/authority_store.go index 4972747943..42e31125c0 100644 --- a/seaweed-block/core/authority/authority_store.go +++ b/seaweed-block/core/authority/authority_store.go @@ -117,7 +117,15 @@ type storeEnvelope struct { Checksum string `json:"checksum"` } -const storeEnvelopeVersion = 1 +// storeEnvelopeVersion is the envelope version this master writes. Version 2 +// (v1.1) no longer keeps the lease horizon current (a restarted master waits +// one period plus skew from its own start instead), so a v1.0.x master, +// which trusts that horizon, must refuse such a record: it refuses every +// version but 1. This master reads both. +const ( + storeEnvelopeVersion = 2 + storeEnvelopeVersionV100 = 1 +) // ErrCorruptRecord indicates a single record failed integrity // checks. Callers skip the record and continue — per-volume fail @@ -164,7 +172,7 @@ func decodeEnvelope(raw []byte, expectedVolumeID string) (DurableRecord, error) if err := json.Unmarshal(raw, &env); err != nil { return DurableRecord{}, fmt.Errorf("%w: decode: %v", ErrCorruptRecord, err) } - if env.Version != storeEnvelopeVersion { + if env.Version != storeEnvelopeVersion && env.Version != storeEnvelopeVersionV100 { return DurableRecord{}, fmt.Errorf("%w: envelope version %d unsupported", ErrCorruptRecord, env.Version) } want := computeChecksum(env.Body) diff --git a/seaweed-block/core/authority/golden_v100_test.go b/seaweed-block/core/authority/golden_v100_test.go index c2eaa7d0b0..c5dcc76721 100644 --- a/seaweed-block/core/authority/golden_v100_test.go +++ b/seaweed-block/core/authority/golden_v100_test.go @@ -188,6 +188,17 @@ func TestAuthorityStoreWritesTheV100Files(t *testing.T) { dir := t.TempDir() goldenAuthority(t, dir) got, want := goldenAuthorityFiles(t, dir), goldenAuthorityFiles(t, goldenAuthorityDir) + // The one change since v1.0.0, by the format path: an authority record's + // envelope version is 2 (a v1.0.x master refuses it; the body and its + // checksum are unchanged, and today's master still reads version 1). + for n, b := range want { + if strings.HasSuffix(n, ".v3auth.json") { + if !bytes.HasPrefix(b, []byte(`{"v":1,`)) { + t.Fatalf("%s: the v1.0.0 fixture does not start with envelope version 1", n) + } + want[n] = append([]byte(`{"v":2,`), b[len(`{"v":1,`):]...) + } + } var names []string for n := range want { names = append(names, n) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 3bd2de600c..8963f3479a 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -337,7 +337,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a return fmt.Errorf("workspace revoke ACK: stale or unsolicited") } lease := *s.Lease - lease.ExpiresAtNS = min(lease.ExpiresAtNS, p.leaseDeadlineLocked(volume).UnixNano()) + lease.ExpiresAtNS = p.leaseDeadlineLocked(volume).UnixNano() if p.WorkspaceLeaseValidity(lease) == 0 { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } @@ -473,21 +473,17 @@ func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLea } // forcedMoveBarrierLocked evaluates forced admission at master time now. It -// returns the barrier (the audit bound of the lost range, wall time: the -// later of lease expiry and the granted or restart deadline, each plus -// skew) whether or not it has passed, and an error while it has not. -// Caller holds p.mu. +// returns the barrier (the audit bound of the lost range: the granted or +// restart deadline plus skew) whether or not it has passed, and an error +// while it has not. The deadline is this process's own (the latest grant it +// made, or after a restart the restart floor, restart + TTL + skew); no +// value written by an earlier process is read. Caller holds p.mu. func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease) (lostUntil int64, now time.Time, err error) { now = p.workspaceNow() skew := p.workspaceSkew(lease) deadline := p.leaseDeadlineLocked(volume) - // The audit bound only, in wall time: the admission below keeps both - // predicates (the deadline's monotonic reading included). - lostUntil = time.Unix(0, lease.ExpiresAtNS).Add(skew).UnixNano() - if d := deadline.Add(skew).UnixNano(); d > lostUntil { - lostUntil = d - } - if now.Before(time.Unix(0, lease.ExpiresAtNS).Add(skew)) || now.Before(deadline.Add(skew)) { + lostUntil = deadline.Add(skew).UnixNano() + if now.Before(deadline.Add(skew)) { return lostUntil, now, fmt.Errorf("workspace forced move lease expiry plus clock-skew margin has not elapsed") } return lostUntil, now, nil diff --git a/seaweed-block/core/authority/workspace_delete_guard_test.go b/seaweed-block/core/authority/workspace_delete_guard_test.go index 6d88fbfa13..1253646bb5 100644 --- a/seaweed-block/core/authority/workspace_delete_guard_test.go +++ b/seaweed-block/core/authority/workspace_delete_guard_test.go @@ -16,12 +16,11 @@ func TestDeletionReservationGuardSites(t *testing.T) { "reserveWorkspaceDeletion": true, "NoLiveWorkspaceLease": true, "applyWithWorkspaceMove": true, "MoveWorkspace": true, "RenewWorkspaceLease": true, "firstWorkspaceGrant": true, - "regrantWorkspaceLease": true, "extendWorkspaceLease": true, + "regrantWorkspaceLease": true, } boundSites := map[string]bool{ "publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true, "RenewWorkspaceLease": true, "regrantWorkspaceLease": true, - "extendWorkspaceLease": true, // Reply-only copies never increase published validity. "WorkspaceLeaseReply": true, "AckWorkspaceRevocation": true, // Copies the published horizon into the leaf view under mu -> leaseMu. diff --git a/seaweed-block/core/authority/workspace_delete_reservation_test.go b/seaweed-block/core/authority/workspace_delete_reservation_test.go index 38a30ae11f..7b05d08872 100644 --- a/seaweed-block/core/authority/workspace_delete_reservation_test.go +++ b/seaweed-block/core/authority/workspace_delete_reservation_test.go @@ -67,13 +67,15 @@ func TestCommittedDeleteStopsGrantsAndWaitsForTheWholeLease(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { t.Fatal("committed delete extended a holder lease") } - // First horizon is 45 s, plus the default skew of 20 s. Host validity - // expiring earlier is insufficient evidence for deleting remote data. - c.at(64) + // The grant is 30 s, plus the default skew of 20 s: no grant this master + // made can be valid after 50 s (a restarted master waits for its restart + // floor instead). Host validity expiring earlier (30 s minus half the + // skew) is insufficient evidence for deleting remote data. + c.at(49) if err := p.NoLiveWorkspaceLease(ctx, "v"); err == nil || !strings.Contains(err.Error(), "live until") { - t.Fatalf("before durable horizon + skew: %v", err) + t.Fatalf("before the grant + skew: %v", err) } - c.at(65) + c.at(50) if err := p.NoLiveWorkspaceLease(ctx, "v"); err != nil { t.Fatal(err) } @@ -129,7 +131,7 @@ func TestDeleteReservationPersistenceDoesNotBlockLiveRenewal(t *testing.T) { func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) { ctx := context.Background() - for _, site := range []string{"publication", "first grant", "regrant", "renewal", "extension", "move"} { + for _, site := range []string{"publication", "first grant", "regrant", "renewal", "move"} { t.Run(site, func(t *testing.T) { c := newTestClock() store := &deleteGrantStore{} @@ -159,10 +161,6 @@ func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) { switch site { case "publication": done <- p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}) - case "extension": - p.extWG.Add(1) - p.extendWorkspaceLease("v", "r", 1, c.sec(100)) - done <- nil case "move": _, err := p.MoveWorkspace(ctx, WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "a", TargetHost: "b", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}, WorkspaceHead{Gen: 1, Epoch: 1, Holder: "a/r"}) done <- err @@ -189,7 +187,7 @@ func TestDeleteReservationClosesPausedGrantWriters(t *testing.T) { writes := len(store.records) close(resume) err := <-done - if site != "extension" && !errors.Is(err, ErrWorkspaceDeleteReserved) { + if !errors.Is(err, ErrWorkspaceDeleteReserved) { t.Fatalf("paused %s: %v", site, err) } if len(store.records) != writes { diff --git a/seaweed-block/core/authority/workspace_issue_publish_test.go b/seaweed-block/core/authority/workspace_issue_publish_test.go index a28b5538f3..8a8dbf2972 100644 --- a/seaweed-block/core/authority/workspace_issue_publish_test.go +++ b/seaweed-block/core/authority/workspace_issue_publish_test.go @@ -58,5 +58,4 @@ func TestWorkspaceIssuePublishNeverLowersARenewedDeadline(t *testing.T) { t.Fatal("renewal inside the outstanding grant:", err) } assertLeaseViewMatches(t, p, "after issue and renewal") - p.CloseWorkspaceExtenders() } diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 4854429616..53e1837b77 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "runtime" - "strings" "sync" "sync/atomic" "testing" @@ -40,12 +39,6 @@ func (s *hookStore) Put(r DurableRecord) error { func (s *hookStore) setBefore(f func(DurableRecord) error) { s.before.Store(&f) } func (s *hookStore) setAfter(f func(DurableRecord) error) { s.after.Store(&f) } -// isExtension reports a lease write that raises the horizon above firstH and -// is not a revocation: the extender's write. -func isExtension(r DurableRecord, volume string, firstH int64) bool { - return r.VolumeID == volume && r.Workspace != nil && r.Workspace.Lease != nil && !r.Workspace.Lease.Revoking && r.Workspace.Lease.ExpiresAtNS > firstH -} - type testClock struct{ ns atomic.Int64 } func newTestClock() *testClock { @@ -66,7 +59,6 @@ func (c *testClock) sec(sec float64) time.Time { func newLeasePublisher(t *testing.T, store AuthorityStore, ttl time.Duration, c *testClock) *Publisher { t.Helper() p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, c.now)) - t.Cleanup(p.CloseWorkspaceExtenders) return p } @@ -82,16 +74,6 @@ func bindAndGrant(t *testing.T, p *Publisher, volume, replica string) WorkspaceL return l } -// waitExtenders joins every admitted extender (tests only; no concurrent -// admission while waiting). -// waitExtenders joins every admitted extender. No wall-clock bound (#227): -// extenders are finite (each makes at most one store write), so the join is -// the progress condition; a hang is reported by the go test timeout. -func waitExtenders(t *testing.T, p *Publisher) { - t.Helper() - p.extWG.Wait() -} - // assertLeaseViewMatches checks INV-LEASE-VIEW-001: with p.mu held, every // volume's view equals derive(published state). func assertLeaseViewMatches(t *testing.T, p *Publisher, what string) { @@ -165,7 +147,6 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - waitExtenders(t, p) if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() || got <= firstH { t.Fatalf("extension did not publish trigger+1.5*TTL: %d", got) } @@ -208,29 +189,6 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { if st := p.WorkspaceState("w"); len(st.Moves) != 1 || st.Moves[0].Issued { t.Fatalf("reservation not published: %+v", st) } - // x: a failed extension latches uncertainty. - c.at(0) - p2Disk, _ := newTempStore(t) - hs2 := &hookStore{AuthorityStore: p2Disk} - p2 := newLeasePublisher(t, hs2, 30*time.Second, c) - bindAndGrant(t, p2, "x", "r") - firstX := p2.WorkspaceState("x").Lease.ExpiresAtNS - hs2.setBefore(func(r DurableRecord) error { - if isExtension(r, "x", firstX) { - return errors.New("injected extension write failure") - } - return nil - }) - c.at(10) - if _, err := p2.RenewWorkspaceLease(ctx, "x", "r", 1); err != nil { - t.Fatal(err) - } - waitExtenders(t, p2) - assertLeaseViewMatches(t, p2, "failed extension (uncertain via persistWorkspaceLocked)") - if !p2.workspaceUncertainForTest("x") { - t.Fatal("failed extension did not latch uncertainty") - } - p.CloseWorkspaceExtenders() check("close") reloaded := newLeasePublisher(t, disk, 30*time.Second, c) assertLeaseViewMatches(t, reloaded, "reload") @@ -248,237 +206,6 @@ func (p *Publisher) workspaceUncertainForTest(v string) bool { return p.workspaceUncertain[v] } -// Control 1: with the store stalled for good, grants shrink to the durable -// horizon, a renewal that would leave no host validity is refused, and a -// renewal at the horizon is refused. The stall is exercised by the extender -// (puts > 0), so a green cannot bypass it. -func TestWorkspaceLeaseClampsToHorizonUnderStalledStore(t *testing.T) { - disk, _ := newTempStore(t) - hs := &hookStore{AuthorityStore: disk} - c := newTestClock() - p := newLeasePublisher(t, hs, 30*time.Second, c) - bindAndGrant(t, p, "v", "r") - horizon := p.WorkspaceState("v").Lease.ExpiresAtNS // 1045 - var puts atomic.Int64 - entered, release := make(chan struct{}), make(chan struct{}) - var enterOnce, releaseOnce sync.Once - hs.setBefore(func(r DurableRecord) error { - if isExtension(r, "v", horizon) { - puts.Add(1) - enterOnce.Do(func() { close(entered) }) - <-release - } - return nil - }) - t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) }) // before Close joins - ctx := context.Background() - c.at(10) - if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { - t.Fatal(err) - } - select { - case <-entered: - case <-time.After(3 * time.Second): - t.Fatal("extender never reached the store") - } - c.at(20) - start := time.Now() - l, err := p.RenewWorkspaceLease(ctx, "v", "r", 1) - if err != nil { - t.Fatal(err) - } - if took := time.Since(start); took > time.Second { - t.Fatalf("renewal waited %s behind the stalled extender", took) - } - if l.ExpiresAtNS > horizon { - t.Fatalf("grant %s beyond the durable horizon %s", time.Unix(0, l.ExpiresAtNS), time.Unix(0, horizon)) - } - if l.ExpiresAtNS != horizon { - t.Fatalf("grant not clamped to the horizon: %s", time.Unix(0, l.ExpiresAtNS)) - } - c.at(35) // horizon - skew/2 = 1035: no positive host validity - if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil || !strings.Contains(err.Error(), "no host validity") { - t.Fatalf("renewal without host validity: %v", err) - } - c.at(45) - if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { - t.Fatal("renewal at the durable horizon accepted") - } - if puts.Load() == 0 { - t.Fatal("the stall was never exercised by an extender write") - } -} - -// Control 2: a restarted master honours the persisted (extended) horizon in -// the forced barrier: max(horizon, restart+TTL) + skew. -func TestWorkspaceRestartForcedBarrierHonoursHorizon(t *testing.T) { - disk, _ := newTempStore(t) - c := newTestClock() - p := newLeasePublisher(t, disk, 30*time.Second, c) - bindAndGrant(t, p, "v", "r") - c.at(10) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - waitExtenders(t, p) - if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() { - t.Fatalf("extension not durable: %s", time.Unix(0, got)) - } - p.CloseWorkspaceExtenders() - c.at(12) - r := newLeasePublisher(t, disk, 30*time.Second, c) // reload deadline 1042 < horizon 1055 - q, h := forcedMove("v", "forced") - c.ns.Store(c.sec(75).UnixNano() - 1) - if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil { - t.Fatal("forced move before persisted horizon + skew after restart") - } - c.at(75) - if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil { - t.Fatal("forced move at horizon + skew refused:", err) - } -} - -// Control 3: an extension whose rename landed but whose directory sync -// failed is an unknown write: the volume is uncertain, the next renewal is -// refused (INV-AUTH-UNCERTAIN-001), and a reload finds the landed horizon and -// bars a forced move until that horizon + skew. -func TestWorkspaceAmbiguousExtensionLatchesUncertainty(t *testing.T) { - disk, _ := newTempStore(t) - hs := &hookStore{AuthorityStore: disk} - c := newTestClock() - p := newLeasePublisher(t, hs, 30*time.Second, c) - bindAndGrant(t, p, "v", "r") - first := p.WorkspaceState("v").Lease.ExpiresAtNS - hs.setAfter(func(r DurableRecord) error { - if isExtension(r, "v", first) { - return errors.New("injected: failure after the rename") - } - return nil - }) - c.at(10) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - waitExtenders(t, p) - if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != first { - t.Fatalf("an unknown write was published: %s", time.Unix(0, got)) - } - c.at(11) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "uncertain") { - t.Fatalf("renewal after an unknown write: %v; want refused as uncertain", err) - } - // INV-AUTH-UNCERTAIN-001: every further authority change of the volume - // is refused until a restart. - if err := p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1); err == nil { - t.Fatal("revocation accepted on an uncertain volume") - } - if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err == nil { - t.Fatal("authority change accepted on an uncertain volume") - } - p.CloseWorkspaceExtenders() - c.at(12) - r := newLeasePublisher(t, disk, 30*time.Second, c) - landed := r.WorkspaceState("v").Lease.ExpiresAtNS - if landed != c.sec(55).UnixNano() { - t.Fatalf("reload did not find the landed horizon: %s", time.Unix(0, landed)) - } - q, h := forcedMove("v", "forced") - c.ns.Store(time.Unix(0, landed).Add(20*time.Second).UnixNano() - 1) - if _, err := r.MoveWorkspace(context.Background(), q, h); err == nil { - t.Fatal("forced move before the landed horizon + skew") - } - c.ns.Store(time.Unix(0, landed).Add(20 * time.Second).UnixNano()) - if _, err := r.MoveWorkspace(context.Background(), q, h); err != nil { - t.Fatal(err) - } -} - -// Control 4: an extender held inside its Put holds p.mu; a revocation or a -// forced move of the same volume waits, then runs after the extension is -// published, so its record carries the extended horizon (ordered). -func TestWorkspaceExtenderHeldOrdersSameVolumeWriters(t *testing.T) { - for _, op := range []string{"revocation", "forced-move"} { - t.Run(op, func(t *testing.T) { - disk, _ := newTempStore(t) - hs := &hookStore{AuthorityStore: disk} - c := newTestClock() - p := newLeasePublisher(t, hs, 30*time.Second, c) - bindAndGrant(t, p, "v", "r") - first := p.WorkspaceState("v").Lease.ExpiresAtNS - entered, release := make(chan struct{}), make(chan struct{}) - var enterOnce, releaseOnce sync.Once - releaseFn := func() { releaseOnce.Do(func() { close(release) }) } - hs.setBefore(func(r DurableRecord) error { - if isExtension(r, "v", first) { - enterOnce.Do(func() { close(entered) }) - <-release - } - return nil - }) - done := make(chan error, 1) - started := false - // Installed before the extender is triggered: on any failure the - // held write is released and the writer settled (bounded) before - // the publisher joins its extenders and the store closes. - t.Cleanup(func() { - releaseFn() - if started { - select { - case <-done: - case <-time.After(5 * time.Second): - t.Error("writer did not settle") - } - } - }) - c.at(10) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - select { - case <-entered: - case <-time.After(3 * time.Second): - t.Fatal("extender never reached the store") - } - started = true - if op == "revocation" { - go func() { done <- p.BeginWorkspaceRevocation(context.Background(), "v", "r", 1) }() - } else { - c.at(66) // past the OLD barrier max(1045, 1040) + 20 - q, h := forcedMove("v", "forced") - go func() { _, err := p.MoveWorkspace(context.Background(), q, h); done <- err }() - } - select { - case err := <-done: - done <- err // keep it for the cleanup join - t.Fatalf("%s ran while the extender held p.mu: %v", op, err) - case <-time.After(200 * time.Millisecond): - } - releaseFn() - var err error - select { - case err = <-done: - done <- err - case <-time.After(5 * time.Second): - t.Fatalf("%s did not finish after the extender", op) - } - want := c.sec(55).UnixNano() - st := p.WorkspaceState("v") - if op == "revocation" { - if err != nil || st.Lease == nil || !st.Lease.Revoking || st.Lease.ExpiresAtNS != want { - t.Fatalf("revocation not ordered after the extension: %v %+v", err, st.Lease) - } - } else if err == nil || len(st.Moves) != 0 || st.Lease.ExpiresAtNS != want { - t.Fatalf("forced move did not see the extended horizon: %v %+v", err, st) - } - p.CloseWorkspaceExtenders() - r := newLeasePublisher(t, disk, 30*time.Second, c) - if got := r.WorkspaceState("v").Lease; got.ExpiresAtNS != want || got.Revoking != (op == "revocation") { - t.Fatalf("reload: %+v", got) - } - }) - } -} - // Control 5: a renewal of the same volume during a held revocation write sees // the last published state (a grant under the horizon), then the revoking // lease with the granted expiry and no extension. During a held forced-move @@ -595,509 +322,6 @@ func TestWorkspaceSameVolumeRenewalDuringHeldWrite(t *testing.T) { }) } -// Control 7 (run with -race): N volumes renew while apply, revocation, ACK, -// a clean move, a forced move, extenders and Close run. A bounded handshake -// holds the first horizon-extension write inside the store while renewals -// keep succeeding and the writers and Close are in flight (queued on the -// publisher lock behind it); then it is released. Required afterwards: every -// eligible volume had successful grants, at least one extension write was -// observed (classified by content: a raised horizon at the same epoch, not -// an ordinary writer's record), no renewal waited 2 s, nothing deadlocked, -// every live lease keeps disk >= published horizon >= every grant (S1), and -// the view equals derive. -func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { - const n = 8 - vol := func(i int) string { return fmt.Sprintf("v%d", i) } - const forcedVol, cleanVol = 2, 1 - eligible := []int{0, 3, 4, 5, 6, 7} // stay leased throughout; v0 also takes endpoint refreshes - disk, _ := newTempStore(t) - hs := &hookStore{AuthorityStore: disk} - - // Extension classification and the overlap hold. - var classMu sync.Mutex - lastH := map[string]int64{} - lastEpoch := map[string]uint64{} - var extensions atomic.Int64 - heldEntered, heldRelease := make(chan struct{}), make(chan struct{}) - var releaseOnce sync.Once - // The publisher clock is frozen while the extension write is held (#247 - // hang): the held write holds p.mu, so every other volume's extender queues - // and no horizon can move. With a running clock a late test goroutine could - // let horizons expire before each volume got a grant under the hold (the - // progress condition never holds), or before the writers run after the - // release (a revoke ACK finds the lease expired). This test is about lock - // and store ordering, not about lease expiry. - // The clock stays frozen after the release until the clean volume's revoke - // ACK: the endpoint refreshes, the revocation and the ACK queue on p.mu - // behind every volume's extension write (fsync), which on a loaded machine - // can outlast the clean volume's grant, and a revoking lease is never - // extended (in-time ACK has its own tests). The writer then resumes the - // clock from the frozen instant, so it neither jumps over a horizon nor runs - // backwards; extensions run in real time alongside the moves and Close. - // Now/Freeze/Resume are one transaction each. - clock := &leaseTestClock{} - releaseHold := func() { - releaseOnce.Do(func() { close(heldRelease) }) - } - var classifying atomic.Bool - var holding atomic.Bool // set when the extension write is held, before it blocks - var heldVol atomic.Value // string: the volume whose extension write is held - var holdTaken atomic.Bool - var holdMu sync.Mutex - var skippedHolds atomic.Int64 // extension writes not held: some eligible volume lacked headroom - var p *Publisher - // headroom witnesses, at the frozen instant and from each volume's own - // renewal view (the fields RenewWorkspaceLease reads, under the leaf - // leaseMu), that a renewal of every eligible volume and of the clean volume - // grants positive host validity: lease present and live, durable horizon - // minus half the skew after now, and now before the granted deadline. The - // frozen clock and the queued extenders keep it so for the whole hold and, - // for the clean volume, through its revocation and ACK. - var noHeadroom atomic.Value // string: the last volume found without headroom, and why - headroom := func() bool { - now := clock.Now().UnixNano() - p.leaseMu.Lock() - defer p.leaseMu.Unlock() - for _, i := range append(append([]int{}, eligible...), cleanVol) { // the clean volume is revoked and ACKed frozen - lv := p.leaseViews[vol(i)] - if lv == nil || !lv.d.bound || !lv.d.leasePresent || lv.d.revoking || lv.d.movePending || - lv.d.uncertain || lv.d.storeless || lv.d.horizon-lv.d.maxSkewNS/2 <= now || now >= lv.deadline.UnixNano() { - why := "no view" - if lv != nil { - why = fmt.Sprintf("bound=%v present=%v revoking=%v pending=%v uncertain=%v validity=%v deadline-now=%v", - lv.d.bound, lv.d.leasePresent, lv.d.revoking, lv.d.movePending, lv.d.uncertain, - time.Duration(lv.d.horizon-lv.d.maxSkewNS/2-now), time.Duration(lv.deadline.UnixNano()-now)) - } - noHeadroom.Store(vol(i) + ": " + why) - return false - } - } - return true - } - hs.setBefore(func(r DurableRecord) error { - time.Sleep(5 * time.Millisecond) // a slow store - if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { - return nil - } - l := r.Workspace.Lease - pending := len(r.Workspace.Moves) > 0 && !r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued - classMu.Lock() - ext := !l.Revoking && !pending && l.Epoch == lastEpoch[r.VolumeID] && l.ExpiresAtNS > lastH[r.VolumeID] - if ext { - lastH[r.VolumeID] = l.ExpiresAtNS - } - classMu.Unlock() - if ext { - extensions.Add(1) - first := false - if !holdTaken.Load() { - holdMu.Lock() - if !holdTaken.Load() { - clock.Freeze() - if headroom() { - holdTaken.Store(true) - first = true - } else { - clock.Resume() // try again at a later extension write - skippedHolds.Add(1) - } - } - holdMu.Unlock() - } - if first { - heldVol.Store(r.VolumeID) // the volume whose extension write is held - holding.Store(true) // before the hold: a renewal started after this saw it - close(heldEntered) - <-heldRelease - } - } - return nil - }) - // The publisher clock is real time plus an offset. The forced-move volume - // is granted at offset -10 s, so by offset 0 its horizon + skew barrier has - // passed; the clock only moves forward. - clock.SetOffset(-10 * time.Second) - p = NewPublisher(nil, WithStore(hs), WithWorkspaceLeaseConfig(2*time.Second, clock.Now)) - t.Cleanup(p.CloseWorkspaceExtenders) - ctx := context.Background() - bindAndGrant(t, p, vol(forcedVol), "r") // never renewed again - clock.SetOffset(0) - // Set-up writes are real store writes (fsync): on a loaded machine binding - // the volumes can take longer than a TTL, and the first-bound volume would - // expire before its renewer starts (by design it never recovers). The clock - // stays frozen through the set-up and resumes just before the renewers. - clock.Freeze() - for i := 0; i < n; i++ { - if i != forcedVol { - bindAndGrant(t, p, vol(i), "r") - } - } - for i := 0; i < n; i++ { - st := p.WorkspaceState(vol(i)) - lastH[vol(i)], lastEpoch[vol(i)] = st.Lease.ExpiresAtNS, st.Lease.Epoch - } - clock.Resume() - classifying.Store(true) - - var grants [n]atomic.Int64 - var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held - var returnedUnderHold [n]atomic.Int64 // calls (any outcome) that started while the extension write was held - var refusedUnderHold atomic.Value // string: a refusal of a call started under the hold, before the writers - var writersGo atomic.Bool // set before the writers start - var maxGrant [n]atomic.Int64 - var slowest atomic.Int64 - stop := make(chan struct{}) - var stopOnce sync.Once - stopRenewers := func() { stopOnce.Do(func() { close(stop) }) } - var wg sync.WaitGroup - writersDone := make(chan error, 1) - closed := make(chan struct{}) - writersStarted, closeStarted := false, false - // Bounded cleanup on every path: release the hold, stop renewers, settle - // every worker, and only then let the fixtures close. - t.Cleanup(func() { - releaseHold() - clock.Resume() - stopRenewers() - settled := make(chan struct{}) - go func() { wg.Wait(); close(settled) }() - select { - case <-settled: - case <-time.After(10 * time.Second): - t.Error("renewers did not settle") - } - if writersStarted { - select { - case <-writersDone: - case <-time.After(10 * time.Second): - t.Error("writers did not settle") - } - } - if closeStarted { - select { - case <-closed: - case <-time.After(10 * time.Second): - t.Error("Close did not settle") - } - } - }) - for _, i := range append(append([]int{}, eligible...), cleanVol) { - wg.Add(1) - go func(i int) { - defer wg.Done() - for { - select { - case <-stop: - return - default: - } - fresh := holding.Load() // the call starts while the extension write is held - beforeWriters := !writersGo.Load() - start := time.Now() - l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) - if d := int64(time.Since(start)); d > slowest.Load() { - slowest.Store(d) - } - if fresh { - returnedUnderHold[i].Add(1) - // Headroom was witnessed at the frozen instant: until the - // writers start, every such renewal must grant (any refusal, - // a horizon error included, fails). - if beforeWriters && (err != nil || l.Revoking) { - refusedUnderHold.CompareAndSwap(nil, fmt.Sprintf("%s: %+v %v", vol(i), l, err)) - } - } - if err == nil && !l.Revoking { - grants[i].Add(1) - if fresh { - underHold[i].Add(1) - } - if l.ExpiresAtNS > maxGrant[i].Load() { - maxGrant[i].Store(l.ExpiresAtNS) - } - } - time.Sleep(5 * time.Millisecond) - } - }(i) - } - - // Handshake 1: the first extension write is held inside the store. - // Progress handshakes (#227) with a real-time failure exit (never a pass): - // the cleanup releases the hold and joins every worker. - select { - case <-heldEntered: // renewers keep triggering extensions - case <-time.After(30 * time.Second): - nh, _ := noHeadroom.Load().(string) - t.Fatalf("no extension write was held within 30 s (%d extension writes, %d not held for lack of headroom; last: %s)", - extensions.Load(), skippedHolds.Load(), nh) - } - // A late test goroutine (machine load), longer than a horizon (1.5 x TTL): - // with the clock frozen under the hold, no volume can lose its lease here. - time.Sleep(3500 * time.Millisecond) - // Handshake 2: renewals keep succeeding while it is held. - // Progress, no timer (#227): every eligible volume gains a grant from a call - // that STARTED while the extension write was held (a reply computed before - // the hold does not count); renewals that waited for it would never return. - // The hold was taken only with headroom witnessed for every eligible volume - // at the frozen instant, so no refusal is allowed here. - held, _ := heldVol.Load().(string) - for give := time.Now().Add(30 * time.Second); ; time.Sleep(5 * time.Millisecond) { - if r, _ := refusedUnderHold.Load().(string); r != "" { - t.Fatalf("under the held extension of %s, with headroom witnessed: refused %s", held, r) - } - all := true - for _, i := range eligible { - if underHold[i].Load() == 0 { - all = false - } - } - if all { - break - } - if time.Now().After(give) { - t.Fatalf("under the held extension of %s within 30 s: grants %v, returned calls %v", held, - underHoldCounts(&underHold, eligible), underHoldCounts(&returnedUnderHold, eligible)) - } - } - t.Logf("under the held extension of %s (%d extension writes not held for lack of headroom): grants %v", held, - skippedHolds.Load(), underHoldCounts(&underHold, eligible)) - // Writers and Close start while the extension write is held. - writersGo.Store(true) - writersStarted = true - go func() { - for k := 0; k < 5; k++ { - if err := p.apply(AssignmentAsk{VolumeID: vol(0), ReplicaID: "r", DataAddr: fmt.Sprintf("d%d", k), CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { - writersDone <- fmt.Errorf("endpoint refresh: %w", err) - return - } - } - // Still frozen since the hold (the refreshes above needed p.mu, which the - // held write owned); the clean volume's headroom was witnessed then. - if err := p.BeginWorkspaceRevocation(ctx, vol(cleanVol), "r", 1); err != nil { - clock.Resume() - writersDone <- fmt.Errorf("revocation: %w", err) - return - } - err := p.AckWorkspaceRevocation(ctx, vol(cleanVol), WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7, Holder: "old/r", RemoteLSN: 42}, WorkspaceHead{Detached: true, Epoch: 1, Holder: "old/r", RemoteLSN: 42}) - clock.Resume() - if err != nil { - writersDone <- fmt.Errorf("ack: %w", err) - return - } - clean := WorkspaceMoveRequest{RequestID: "clean", VolumeID: vol(cleanVol), ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "clean"} - if _, err := p.MoveWorkspace(ctx, clean, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42, Detached: true}); err != nil { - writersDone <- fmt.Errorf("clean move: %w", err) - return - } - q, h := forcedMove(vol(forcedVol), "forced") - if _, err := p.MoveWorkspace(ctx, q, h); err != nil { - writersDone <- fmt.Errorf("forced move: %w", err) - return - } - writersDone <- nil - }() - closeStarted = true - go func() { p.CloseWorkspaceExtenders(); close(closed) }() - select { - case err := <-writersDone: - writersDone <- err // keep it for the cleanup join - t.Fatalf("writers finished while the extension write held the publisher lock: %v", err) - case <-closed: - t.Fatal("Close finished while an extension write was held") - case <-time.After(150 * time.Millisecond): - } - releaseHold() - var werr error - select { - case werr = <-writersDone: - writersDone <- werr // keep it for the cleanup join - case <-time.After(20 * time.Second): - t.Fatal("deadlock: writers did not finish after the release", allGoroutineStacks()) - } - if werr != nil { - t.Fatal("writer:", werr) - } - select { - case <-closed: - case <-time.After(20 * time.Second): - t.Fatal("deadlock: Close did not finish after the release", allGoroutineStacks()) - } - time.Sleep(50 * time.Millisecond) // renewals continue after Close - stopRenewers() - settled := make(chan struct{}) - go func() { wg.Wait(); close(settled) }() - select { - case <-settled: - case <-time.After(20 * time.Second): - t.Fatal("deadlock: renewers did not finish", allGoroutineStacks()) - } - - if s := time.Duration(slowest.Load()); s >= 2*time.Second { - t.Fatalf("slowest renewal %s", s) - } - for _, i := range eligible { - if grants[i].Load() == 0 { - t.Fatalf("%s had no successful grant", vol(i)) - } - } - if extensions.Load() == 0 { - t.Fatal("no horizon-extension write was observed") - } - // An issued move starts the new holder's lease at the new epoch. - if st := p.WorkspaceState(vol(forcedVol)); st == nil || len(st.Moves) != 1 || !st.Moves[0].Issued || st.Moves[0].Kind != "forced" || - st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { - t.Fatalf("forced move not issued: %+v", st) - } - if st := p.WorkspaceState(vol(cleanVol)); st == nil || len(st.Moves) != 1 || st.Moves[0].Kind != "clean" || - st.Lease == nil || st.Lease.Epoch != st.Moves[0].NewEpoch || st.Lease.Revoking { - t.Fatalf("clean move not issued: %+v", st) - } - assertLeaseViewMatches(t, p, "after concurrency") - recs, err := disk.Load() - if err != nil { - t.Fatal(err) - } - onDisk := map[string]int64{} - for _, r := range recs { - if r.Workspace != nil && r.Workspace.Lease != nil { - onDisk[r.VolumeID] = r.Workspace.Lease.ExpiresAtNS - } - } - for i := 0; i < n; i++ { - st := p.WorkspaceState(vol(i)) - if st == nil || st.Lease == nil || st.Lease.Epoch != 1 { - continue // a completed move started the next epoch's lease (out of S1's scope) - } - if onDisk[vol(i)] < st.Lease.ExpiresAtNS || st.Lease.ExpiresAtNS < maxGrant[i].Load() { - t.Fatalf("%s: S1 broken: disk %d, published horizon %d, max grant %d", vol(i), onDisk[vol(i)], st.Lease.ExpiresAtNS, maxGrant[i].Load()) - } - } - t.Logf("extension writes %d; grants per eligible volume %v", extensions.Load(), func() []int64 { - out := []int64{} - for _, i := range eligible { - out = append(out, grants[i].Load()) - } - return out - }()) -} - -// Control 10a: Close waits for an extender held inside its Put; after Close -// no extension is admitted or written. -func TestWorkspaceCloseJoinsHeldExtender(t *testing.T) { - disk, _ := newTempStore(t) - hs := &hookStore{AuthorityStore: disk} - c := newTestClock() - p := newLeasePublisher(t, hs, 30*time.Second, c) - bindAndGrant(t, p, "v", "r") - first := p.WorkspaceState("v").Lease.ExpiresAtNS - var puts atomic.Int64 - entered, release := make(chan struct{}), make(chan struct{}) - var enterOnce, releaseOnce sync.Once - releaseFn := func() { releaseOnce.Do(func() { close(release) }) } - hs.setBefore(func(r DurableRecord) error { - if isExtension(r, "v", first) { - puts.Add(1) - enterOnce.Do(func() { close(entered) }) - <-release - } - return nil - }) - closed := make(chan struct{}) - closeStarted := false - t.Cleanup(func() { // bounded: release, then settle Close before the store closes - releaseFn() - if closeStarted { - select { - case <-closed: - case <-time.After(5 * time.Second): - t.Error("Close did not settle") - } - } - }) - c.at(10) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - select { - case <-entered: - case <-time.After(3 * time.Second): - t.Fatal("extender never reached the store") - } - closeStarted = true - go func() { p.CloseWorkspaceExtenders(); close(closed) }() - select { - case <-closed: - t.Fatal("Close returned while an extender was inside its write") - case <-time.After(200 * time.Millisecond): - } - releaseFn() - select { - case <-closed: - case <-time.After(5 * time.Second): - t.Fatal("Close did not return after the extender finished") - } - before := puts.Load() - c.at(20) // would trigger an extension (horizon 1055 < 1020 + 37.5) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - waitExtenders(t, p) - if puts.Load() != before { - t.Fatal("an extension was written after Close") - } -} - -// Control 10b: an extender admitted before Close that reaches p.mu after -// closing is set aborts with a known no-write. The test holds p.mu itself, so -// the renewal also shows it never needs p.mu. -func TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite(t *testing.T) { - disk, _ := newTempStore(t) - hs := &hookStore{AuthorityStore: disk} - c := newTestClock() - p := newLeasePublisher(t, hs, 30*time.Second, c) - bindAndGrant(t, p, "v", "r") - first := p.WorkspaceState("v").Lease.ExpiresAtNS - var puts atomic.Int64 - hs.setBefore(func(r DurableRecord) error { - if isExtension(r, "v", first) { - puts.Add(1) - } - return nil - }) - c.at(10) - p.mu.Lock() - renewed := make(chan error, 1) - go func() { _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); renewed <- err }() - select { - case err := <-renewed: - if err != nil { - p.mu.Unlock() - t.Fatal(err) - } - case <-time.After(2 * time.Second): - p.mu.Unlock() - t.Fatal("renewal waited on p.mu") - } - p.leaseMu.Lock() - admitted := p.leaseViews["v"].extending - p.leaseClosing = true // Close's first step, while the extender waits for p.mu - p.leaseMu.Unlock() - p.mu.Unlock() - if !admitted { - t.Fatal("no extender was admitted") - } - waitExtenders(t, p) - if puts.Load() != 0 || p.WorkspaceState("v").Lease.ExpiresAtNS != first { - t.Fatal("an extender admitted before closing wrote after closing") - } - p.leaseMu.Lock() - extending := p.leaseViews["v"].extending - p.leaseMu.Unlock() - if extending { - t.Fatal("aborted extender left the single-flight flag set") - } -} - // leaseTestClock is a test publisher clock: real time plus an offset, or a // frozen instant. Now, Freeze, Resume and SetOffset are each one transaction // under mu, and Now never returns an earlier time than a previous Now. diff --git a/seaweed-block/core/authority/workspace_lease_stats.go b/seaweed-block/core/authority/workspace_lease_stats.go deleted file mode 100644 index f4ebf532d8..0000000000 --- a/seaweed-block/core/authority/workspace_lease_stats.go +++ /dev/null @@ -1,229 +0,0 @@ -package authority - -import ( - "fmt" - "log" - "time" -) - -// Lease headroom observability. Headroom is the durable horizon minus now: -// how long the published lease still covers a holder if no extension lands. -// Extensions start below 1.25 TTL of headroom and grants are clamped below -// 1 TTL, so a lagging authority store shows first as an extension in flight -// with headroom under 1.125 TTL, and only later as clamps. -// -// The extension store write latency (LeaseStats.ExtensionWrite*) is -// completed-write telemetry: a write is sampled when its Put returns, so a -// write that is still blocked shows up only after it returns, possibly after -// headroom is already lost; it is not an early warning by itself. The alarm -// is sampled at renewals, never by a timer: it fires at the latest -// together with the first clamped grant of a streak (logged before the clamp -// line), and earlier only if a renewal lands in the 1-1.125 TTL band while an -// extension is pending. A renewer slower than that band may see both on one -// renewal. - -// LeaseStats is a snapshot of the workspace lease renewal counters. -type LeaseStats struct { - // HeadroomAlarms counts alarm streaks, once per volume per streak: a - // renewal that found headroom below 1.125 TTL with an extension in - // flight, or the first clamped grant (headroom below 1 TTL) of a streak. - HeadroomAlarms uint64 - // ClampsTotal counts grants clamped to the durable horizon. - ClampsTotal uint64 - // ClampsLastMinute counts clamped grants in the last minute. - ClampsLastMinute uint64 - // MinHeadroom is the smallest headroom observed at a grant; valid only - // when MinHeadroomObserved. - MinHeadroom time.Duration - MinHeadroomObserved bool - // ExtensionWriteLast is the duration of the latest lease extension's - // durable store write (the write alone, failed or not); valid only when - // ExtensionWriteObserved. Completed-write telemetry: recorded when the - // Put returns, so a write still blocked is not visible here yet. - ExtensionWriteLast time.Duration - ExtensionWriteObserved bool - // ExtensionWriteMaxLastMinute is the slowest extension write in the last - // minute (rolling, one bucket per second like ClampsLastMinute); valid - // only when ExtensionWriteInLastMinute. - ExtensionWriteMaxLastMinute time.Duration - ExtensionWriteInLastMinute bool -} - -const clampBuckets = 60 // one per second of the last minute - -// leaseCounters is guarded by Publisher.leaseMu. -type leaseCounters struct { - alarms uint64 - clamps uint64 - buckets [clampBuckets]struct{ sec, n int64 } // clamps by unix second - minHeadroom int64 - minObserved bool - // Extension store writes: the latest, and the slowest per second of the - // last minute. - writeLast int64 - writeObserved bool - writeBuckets [clampBuckets]struct { - sec, max int64 - set bool - } - // Per-minute summary, emitted by the first renewal attempt after the - // window, granted or refused: no goroutine or timer of its own. With no - // renewal attempts at all nothing is emitted; the counters above (the - // status endpoint) still show the clamps. - windowStart time.Time - windowClamps uint64 - windowMin int64 - windowMinSet bool -} - -func (c *leaseCounters) clampsSince(now time.Time) uint64 { - cut := now.Unix() - clampBuckets - var n uint64 - for _, b := range c.buckets { - if b.n > 0 && b.sec > cut && b.sec <= now.Unix() { - n += uint64(b.n) - } - } - return n -} - -func (c *leaseCounters) recordClamp(now time.Time) { - c.clamps++ - c.windowClamps++ - sec := now.Unix() - b := &c.buckets[uint64(sec)%clampBuckets] - if b.sec != sec { - b.sec, b.n = sec, 0 - } - b.n++ -} - -// recordExtensionWrite records the duration of one extension store write -// that returned at now. -func (c *leaseCounters) recordExtensionWrite(now time.Time, d time.Duration) { - c.writeLast, c.writeObserved = int64(d), true - sec := now.Unix() - b := &c.writeBuckets[uint64(sec)%clampBuckets] - if !b.set || b.sec != sec { - b.sec, b.max, b.set = sec, int64(d), true - } else if int64(d) > b.max { - b.max = int64(d) - } -} - -// extensionWriteMaxSince returns the slowest extension write of the last -// minute, and whether there was one. -func (c *leaseCounters) extensionWriteMaxSince(now time.Time) (int64, bool) { - cut := now.Unix() - clampBuckets - max, ok := int64(0), false - for _, b := range c.writeBuckets { - if b.set && b.sec > cut && b.sec <= now.Unix() && (!ok || b.max > max) { - max, ok = b.max, true - } - } - return max, ok -} - -// summaryDue closes a window that has lasted a minute and returns its summary -// note when it had clamps. Every renewal attempt calls it, granted or refused, -// so a stall through expiry (only refusals after the clamps) is still -// summarized. It opens no window: the first grant does. -func (c *leaseCounters) summaryDue(now time.Time) string { - if c.windowStart.IsZero() || now.Sub(c.windowStart) < time.Minute { - return "" - } - var note string - if c.windowClamps > 0 { - note = fmt.Sprintf("workspace lease: %d clamped grants in the last %s (total %d, min headroom %s); the authority store is lagging", - c.windowClamps, now.Sub(c.windowStart).Round(time.Second), c.clamps, time.Duration(c.windowMin).Round(time.Millisecond)) - } - c.windowStart, c.windowClamps, c.windowMinSet = now, 0, false - return note -} - -// observeGrant records the headroom of a grant and returns a per-minute -// summary note when a window with clamps has just ended. Call it before -// recordClamp of the same grant (it may open a new window). -func (c *leaseCounters) observeGrant(now time.Time, headroom int64) string { - if c.windowStart.IsZero() { - c.windowStart = now - } - note := c.summaryDue(now) - if !c.windowMinSet || headroom < c.windowMin { - c.windowMin, c.windowMinSet = headroom, true - } - if !c.minObserved || headroom < c.minHeadroom { - c.minHeadroom, c.minObserved = headroom, true - } - return note -} - -// WorkspaceLeaseStats returns a snapshot of the lease renewal counters. -func (p *Publisher) WorkspaceLeaseStats() LeaseStats { - p.leaseMu.Lock() - defer p.leaseMu.Unlock() - c := &p.leaseStats - now := p.workspaceNow() - writeMax, writeRecent := c.extensionWriteMaxSince(now) - return LeaseStats{ - HeadroomAlarms: c.alarms, - ClampsTotal: c.clamps, - ClampsLastMinute: c.clampsSince(now), - MinHeadroom: time.Duration(c.minHeadroom), - MinHeadroomObserved: c.minObserved, - ExtensionWriteLast: time.Duration(c.writeLast), - ExtensionWriteObserved: c.writeObserved, - ExtensionWriteMaxLastMinute: time.Duration(writeMax), - ExtensionWriteInLastMinute: writeRecent, - } -} - -// headroomAlarmLocked runs the alarm state machine of one renewal, before the -// renewal clamps (a grant clamps exactly when headroom < 1 TTL). Caller holds -// leaseMu. It returns a note to log after the unlock, before the clamp note. -// -// state | condition at a renewal | next | effect -// -----------+-----------------------------------------------+------------+------------------ -// quiet | extending && headroom < 1.125 TTL | alarmed | count + log once -// quiet | headroom < 1 TTL (this grant clamps) | alarmed | count + log once -// quiet | otherwise | quiet | - -// alarmed | headroom >= 1.25 TTL | quiet | streak ends -// alarmed | !extending && headroom >= 1.125 TTL | quiet | streak ends -// alarmed | otherwise | alarmed | - -// -// A clamp streak (headroom < 1 TTL) therefore never starts without an alarm -// on the same or an earlier renewal, and never re-alarms while it lasts. -func (p *Publisher) headroomAlarmLocked(volume string, lv *leaseView, headroom int64) string { - ttl := int64(p.workspaceTTL) - low, high := ttl+ttl/8, ttl+ttl/4 - if lv.alarmed { - if headroom >= high || (!lv.extending && headroom >= low) { - lv.alarmed = false - } - return "" - } - var why string - switch { - case lv.extending && headroom < low: - why = "below 1.125 TTL while the extension write is pending" - case headroom < ttl: - why = "below 1 TTL: this grant is the first clamped to the durable horizon" - default: - return "" - } - lv.alarmed = true - p.leaseStats.alarms++ - return fmt.Sprintf("workspace lease: volume=%s headroom %s %s; the authority store is lagging", - volume, time.Duration(headroom).Round(time.Millisecond), why) -} - -func (p *Publisher) logLease(note string) { - if note == "" { - return - } - if p.leaseLog != nil { - p.leaseLog(note) - return - } - log.Print(note) -} diff --git a/seaweed-block/core/authority/workspace_lease_stats_test.go b/seaweed-block/core/authority/workspace_lease_stats_test.go deleted file mode 100644 index 0ab9ac7036..0000000000 --- a/seaweed-block/core/authority/workspace_lease_stats_test.go +++ /dev/null @@ -1,393 +0,0 @@ -package authority - -import ( - "context" - "strings" - "sync" - "sync/atomic" - "testing" - "time" -) - -// blockedLeaseStore holds every armed workspace-lease write until release -// closes, standing in for an authority journal stuck behind other fsyncs. -type blockedLeaseStore struct { - AuthorityStore - armed atomic.Bool - entered chan struct{} - once sync.Once - release chan struct{} -} - -func (s *blockedLeaseStore) Put(r DurableRecord) error { - if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil { - s.once.Do(func() { close(s.entered) }) - <-s.release - } - return s.AuthorityStore.Put(r) -} - -type noteLog struct { - mu sync.Mutex - lines []string -} - -func (l *noteLog) add(s string) { - l.mu.Lock() - defer l.mu.Unlock() - l.lines = append(l.lines, s) -} - -func (l *noteLog) snapshot() []string { - l.mu.Lock() - defer l.mu.Unlock() - return append([]string(nil), l.lines...) -} - -func indexOf(lines []string, sub string) int { - for i, s := range lines { - if strings.Contains(s, sub) { - return i - } - } - return -1 -} - -// With the authority store's lease write stuck, renewals at an advancing -// clock must raise the headroom alarm on a renewal strictly before the first -// clamped grant, then count clamps (total and last minute) and the minimum -// headroom, and log a per-minute summary once a minute with clamps ends. -func TestWorkspaceLeaseHeadroomAlarmPrecedesFirstClamp(t *testing.T) { - disk, _ := newTempStore(t) - store := &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})} - var nowNS atomic.Int64 - t0 := time.Unix(1000, 0) - nowNS.Store(t0.UnixNano()) - at := func(d time.Duration) { nowNS.Store(t0.Add(d).UnixNano()) } - const ttl = 30 * time.Second - p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(ttl, func() time.Time { return time.Unix(0, nowNS.Load()) })) - notes := ¬eLog{} - p.leaseLog = notes.add - var releaseOnce sync.Once - release := func() { releaseOnce.Do(func() { close(store.release) }) } - t.Cleanup(p.CloseWorkspaceExtenders) // runs after release (LIFO) - t.Cleanup(release) - if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { - t.Fatal(err) - } - // First grant: synchronous write, horizon t0+45s. - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - if s := p.WorkspaceLeaseStats(); s.HeadroomAlarms != 0 || s.ClampsTotal != 0 || s.MinHeadroomObserved { - t.Fatalf("stats after the first grant: %+v", s) - } - store.armed.Store(true) - renew := func(d time.Duration) (WorkspaceLease, LeaseStats) { - t.Helper() - at(d) - l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1) - if err != nil { - t.Fatalf("renewal at +%s: %v", d, err) - } - return l, p.WorkspaceLeaseStats() - } - - // +10s: headroom 35s < 1.25 TTL starts the extension, which blocks. - _, s := renew(10 * time.Second) - if s.HeadroomAlarms != 0 || s.ClampsTotal != 0 { - t.Fatalf("+10s (headroom 35s, extension just started): %+v", s) - } - select { - case <-store.entered: - case <-time.After(5 * time.Second): - t.Fatal("the extension write never reached the store") - } - // +12s: headroom 33s < 33.75s (1.125 TTL), extension pending: alarm, no clamp. - l, s := renew(12 * time.Second) - if s.HeadroomAlarms != 1 || s.ClampsTotal != 0 { - t.Fatalf("+12s (headroom 33s, extension pending): want 1 alarm and 0 clamps, got %+v", s) - } - if want := t0.Add(12*time.Second + ttl).UnixNano(); l.ExpiresAtNS != want { - t.Fatalf("+12s grant %d, want unclamped %d", l.ExpiresAtNS, want) - } - // +13s: same streak, no second alarm. - if _, s = renew(13 * time.Second); s.HeadroomAlarms != 1 { - t.Fatalf("+13s: alarm repeated within one streak: %+v", s) - } - // +20s, +25s: headroom 25s, 20s < TTL: clamped grants. - l, s = renew(20 * time.Second) - if want := t0.Add(45 * time.Second).UnixNano(); l.ExpiresAtNS != want { - t.Fatalf("+20s grant %d, want clamped to horizon %d", l.ExpiresAtNS, want) - } - if s.ClampsTotal != 1 || s.ClampsLastMinute != 1 || s.HeadroomAlarms != 1 { - t.Fatalf("+20s: %+v", s) - } - _, s = renew(25 * time.Second) - if s.ClampsTotal != 2 || s.ClampsLastMinute != 2 || !s.MinHeadroomObserved || s.MinHeadroom != 20*time.Second { - t.Fatalf("+25s: want 2 clamps, min headroom 20s; got %+v", s) - } - lines := notes.snapshot() - alarmAt, clampAt := indexOf(lines, "below 1.125 TTL while the extension write is pending"), indexOf(lines, "are clamped to the durable horizon") - if alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt { - t.Fatalf("alarm line must precede the first clamp line: alarm=%d clamp=%d\n%s", alarmAt, clampAt, strings.Join(lines, "\n")) - } - if !strings.Contains(lines[alarmAt], "volume=v headroom 33s") { - t.Fatalf("alarm line: %q", lines[alarmAt]) - } - - // The store recovers: the extension lands (horizon +10s+45s = +55s). - release() - waitExtenders(t, p) - // +26s: horizon +55s, headroom 29s < TTL: one more clamp; a new extension - // starts (trigger +26s, horizon +71s) and lands at once. - _, s = renew(26 * time.Second) - waitExtenders(t, p) - if s.ClampsTotal != 3 { - t.Fatalf("+26s: %+v", s) - } - // +27s: headroom 44s >= 1.25 TTL: unclamped, the alarm streak ends. - if _, s = renew(27 * time.Second); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 { - t.Fatalf("+27s: %+v", s) - } - // Healthy renewals keep the lease ahead: no clamps, no alarms. - for _, d := range []time.Duration{40 * time.Second, 55 * time.Second} { - if _, s = renew(d); s.ClampsTotal != 3 || s.HeadroomAlarms != 1 { - t.Fatalf("+%s: %+v", d, s) - } - waitExtenders(t, p) - } - if indexOf(notes.snapshot(), "clamped grants in the last") >= 0 { - t.Fatal("summary logged before the minute ended") - } - // +70s: a minute after the window's first renewal (+10s): the window with - // clamps ends and its summary is logged by this renewal. - if _, s = renew(70 * time.Second); s.ClampsTotal != 3 { - t.Fatalf("+70s: %+v", s) - } - waitExtenders(t, p) - lines = notes.snapshot() - if i := indexOf(lines, "workspace lease: 3 clamped grants in the last 1m0s (total 3, min headroom 20s)"); i < 0 { - t.Fatalf("no per-minute summary:\n%s", strings.Join(lines, "\n")) - } - // The +20s/+25s/+26s clamps are older than a minute at +87s. - at(87 * time.Second) - if s = p.WorkspaceLeaseStats(); s.ClampsLastMinute != 0 || s.ClampsTotal != 3 || s.MinHeadroom != 20*time.Second { - t.Fatalf("+87s: clamps should age out of the last minute: %+v", s) - } -} - -// stalledLeaseRig is a publisher whose lease writes, once armed, block until -// release, with a settable clock (t0 = first grant, TTL 30s, horizon +45s). -type stalledLeaseRig struct { - p *Publisher - store *blockedLeaseStore - notes *noteLog - t0 time.Time - nowNS atomic.Int64 - release func() -} - -func newStalledLeaseRig(t *testing.T) *stalledLeaseRig { - t.Helper() - disk, _ := newTempStore(t) - r := &stalledLeaseRig{store: &blockedLeaseStore{AuthorityStore: disk, entered: make(chan struct{}), release: make(chan struct{})}, notes: ¬eLog{}, t0: time.Unix(1000, 0)} - r.nowNS.Store(r.t0.UnixNano()) - r.p = NewPublisher(nil, WithStore(r.store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, r.nowNS.Load()) })) - r.p.leaseLog = r.notes.add - var once sync.Once - r.release = func() { once.Do(func() { close(r.store.release) }) } - t.Cleanup(r.p.CloseWorkspaceExtenders) // runs after release (LIFO) - t.Cleanup(r.release) - if err := r.p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { - t.Fatal(err) - } - if _, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatal(err) - } - r.store.armed.Store(true) - return r -} - -func (r *stalledLeaseRig) renew(d time.Duration) (WorkspaceLease, LeaseStats, error) { - r.nowNS.Store(r.t0.Add(d).UnixNano()) - l, err := r.p.RenewWorkspaceLease(context.Background(), "v", "r", 1) - return l, r.p.WorkspaceLeaseStats(), err -} - -func (r *stalledLeaseRig) waitEntered(t *testing.T) { - t.Helper() - select { - case <-r.store.entered: - case <-time.After(5 * time.Second): - t.Fatal("the extension write never reached the store") - } -} - -// assertAlarmBeforeClamp checks exactly one alarm line containing want, logged -// before the first clamp line. -func assertAlarmBeforeClamp(t *testing.T, lines []string, want string) { - t.Helper() - alarms := 0 - for _, s := range lines { - if strings.Contains(s, "the authority store is lagging") && strings.Contains(s, "headroom") && strings.Contains(s, "volume=v") { - alarms++ - } - } - alarmAt, clampAt := indexOf(lines, want), indexOf(lines, "are clamped to the durable horizon") - if alarms != 1 || alarmAt < 0 || clampAt < 0 || alarmAt >= clampAt { - t.Fatalf("want one alarm %q before the first clamp line: alarms=%d alarm=%d clamp=%d\n%s", want, alarms, alarmAt, clampAt, strings.Join(lines, "\n")) - } -} - -// Skipped band: the extension starts and stalls at +10s, and the next renewal -// (+20s) lands already clamped, never in the 1-1.125 TTL band. The alarm fires -// on that same renewal, logged before the clamp line, and counts once. -func TestWorkspaceLeaseAlarmWhenTheBandIsSkipped(t *testing.T) { - r := newStalledLeaseRig(t) - if _, s, err := r.renew(10 * time.Second); err != nil || s.HeadroomAlarms != 0 { - t.Fatalf("+10s: %+v %v", s, err) - } - r.waitEntered(t) - l, s, err := r.renew(20 * time.Second) - if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() { - t.Fatalf("+20s: want a grant clamped to the horizon, got %+v %v", l, err) - } - if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 { - t.Fatalf("+20s: want 1 alarm and 1 clamp, got %+v", s) - } - if _, s, err = r.renew(25 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 { - t.Fatalf("+25s: alarm repeated or clamp missed: %+v %v", s, err) - } - assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 25s below 1.125 TTL while the extension write is pending") -} - -// First renewal below one TTL: no extension has started yet (the renewal -// itself starts it), and the grant clamps. The alarm still fires with that -// first clamp, before the clamp line, and does not repeat in the streak. -func TestWorkspaceLeaseAlarmWithAFirstRenewalBelowTTL(t *testing.T) { - r := newStalledLeaseRig(t) - l, s, err := r.renew(16 * time.Second) - if err != nil || l.ExpiresAtNS != r.t0.Add(45*time.Second).UnixNano() { - t.Fatalf("+16s: want a grant clamped to the horizon, got %+v %v", l, err) - } - if s.HeadroomAlarms != 1 || s.ClampsTotal != 1 { - t.Fatalf("+16s: want 1 alarm with the first clamp, got %+v", s) - } - r.waitEntered(t) // the renewal started the extension; it stalls - if _, s, err = r.renew(18 * time.Second); err != nil || s.HeadroomAlarms != 1 || s.ClampsTotal != 2 { - t.Fatalf("+18s: %+v %v", s, err) - } - assertAlarmBeforeClamp(t, r.notes.snapshot(), "volume=v headroom 29s below 1 TTL: this grant is the first clamped to the durable horizon") -} - -// Stall through expiry: after the clamps, every renewal is refused (no host -// validity, then expired) and none is granted again. The per-minute summary -// is still logged, by the first refused renewal after the minute, once. -func TestWorkspaceLeaseSummaryWithoutALaterGrant(t *testing.T) { - r := newStalledLeaseRig(t) - if _, _, err := r.renew(10 * time.Second); err != nil { // opens the window, starts the extension - t.Fatal(err) - } - r.waitEntered(t) - for _, d := range []time.Duration{20 * time.Second, 25 * time.Second} { - if _, _, err := r.renew(d); err != nil { - t.Fatalf("+%s: %v", d, err) - } - } - for _, d := range []time.Duration{36 * time.Second, 46 * time.Second, 60 * time.Second} { - if l, _, err := r.renew(d); err == nil { - t.Fatalf("+%s: granted %+v through a stalled store past the horizon", d, l) - } - } - if indexOf(r.notes.snapshot(), "clamped grants in the last") >= 0 { - t.Fatal("summary logged before the minute ended") - } - if _, s, err := r.renew(71 * time.Second); err == nil || s.ClampsTotal != 2 { - t.Fatalf("+71s: %+v %v, want a refusal", s, err) - } - if _, _, err := r.renew(72 * time.Second); err == nil { - t.Fatal("+72s granted") - } - lines := r.notes.snapshot() - want := "workspace lease: 2 clamped grants in the last 1m1s (total 2, min headroom 20s)" - n := 0 - for _, s := range lines { - if strings.Contains(s, "clamped grants in the last") { - n++ - } - } - if indexOf(lines, want) < 0 || n != 1 { - t.Fatalf("want the summary %q once from refused renewals, got %d summaries:\n%s", want, n, strings.Join(lines, "\n")) - } -} - -// delayedLeaseStore makes every lease write take delay (when set): a slow -// authority journal that still completes. -type delayedLeaseStore struct { - AuthorityStore - delay atomic.Int64 -} - -func (s *delayedLeaseStore) Put(r DurableRecord) error { - if d := time.Duration(s.delay.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil { - time.Sleep(d) - } - return s.AuthorityStore.Put(r) -} - -// The extension's store write latency is recorded at every extension write: -// the latest one, and the slowest of the last minute (rolling per second), -// which ages out a minute after the write. The first grant's write is not an -// extension and records nothing. -func TestWorkspaceLeaseExtensionWriteLatency(t *testing.T) { - disk, _ := newTempStore(t) - store := &delayedLeaseStore{AuthorityStore: disk} - var nowNS atomic.Int64 - t0 := time.Unix(1000, 0) - nowNS.Store(t0.UnixNano()) - p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) - p.leaseLog = func(string) {} - t.Cleanup(p.CloseWorkspaceExtenders) - if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { - t.Fatal(err) - } - renew := func(d time.Duration) LeaseStats { - t.Helper() - nowNS.Store(t0.Add(d).UnixNano()) - if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil { - t.Fatalf("renewal at +%s: %v", d, err) - } - waitExtenders(t, p) - return p.WorkspaceLeaseStats() - } - if s := renew(0); s.ExtensionWriteObserved || s.ExtensionWriteInLastMinute { // first grant - t.Fatalf("the first grant recorded an extension write: %+v", s) - } - const slow = 300 * time.Millisecond - store.delay.Store(int64(slow)) - // +10s: headroom 35s < 1.25 TTL starts an extension; its write takes 300 ms. - s := renew(10 * time.Second) - if !s.ExtensionWriteObserved || s.ExtensionWriteLast < slow || s.ExtensionWriteLast > slow+time.Second { - t.Fatalf("+10s: want the last extension write ~%s, got %+v", slow, s) - } - if !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute < slow { - t.Fatalf("+10s: want max >= %s in the last minute, got %+v", slow, s) - } - store.delay.Store(0) - // +20s: horizon +55s, headroom 35s: a fast extension write. - s = renew(20 * time.Second) - if s.ExtensionWriteLast >= slow || s.ExtensionWriteMaxLastMinute < slow { - t.Fatalf("+20s: want a fast last write and the 300 ms max kept, got %+v", s) - } - // +71s: the +10s write is older than a minute; the +20s one is not. - nowNS.Store(t0.Add(71 * time.Second).UnixNano()) - if s = p.WorkspaceLeaseStats(); !s.ExtensionWriteInLastMinute || s.ExtensionWriteMaxLastMinute >= slow || s.ExtensionWriteLast >= slow { - t.Fatalf("+71s: the 300 ms max must age out, got %+v", s) - } - // +81s: no write in the last minute; the last write stays reported. - nowNS.Store(t0.Add(81 * time.Second).UnixNano()) - if s = p.WorkspaceLeaseStats(); s.ExtensionWriteInLastMinute || !s.ExtensionWriteObserved { - t.Fatalf("+81s: want no write in the last minute, last still observed; got %+v", s) - } -} diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index e07a5f74e1..f4c92d2306 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "log" "time" ) @@ -28,20 +27,17 @@ type leaseDerived struct { movePending bool // the last workspace move is reserved, not issued uncertain bool // a workspace write of the volume failed (INV-AUTH-UNCERTAIN-001) storeless bool - horizon int64 // published Lease.ExpiresAtNS: durable upper bound of every grant + horizon int64 // published Lease.ExpiresAtNS: read by nothing but replyExpiryNS's unreachable fallback maxSkewNS int64 lease WorkspaceLease // the published (durable) lease } // leaseView is one volume's renewal state. Guarded by Publisher.leaseMu. -// deadline (the latest grant, or the restart rule's now+TTL) and extending -// are owned by the view; d is derived. +// deadline (the latest grant, or the restart rule's now+TTL+skew) is owned +// by the view; d is derived. type leaseView struct { - d leaseDerived - deadline time.Time - extending bool - clamped bool // a renewal was clamped below now+TTL; logged once per streak - alarmed bool // a headroom alarm streak is open (headroomAlarmLocked) + d leaseDerived + deadline time.Time } // deriveLeaseLocked computes the derived lease view from published state. @@ -124,21 +120,18 @@ func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise boo } } -// replyExpiryNS is the expiry reported to a host: never the raw durable -// horizon, only what was granted (min(horizon, deadline)). +// replyExpiryNS is the expiry reported to a host: what was granted (the +// deadline), never a persisted value. func (lv *leaseView) replyExpiryNS() int64 { if lv.deadline.IsZero() { return lv.d.horizon // unreachable: a published lease always has a deadline } - if dl := lv.deadline.UnixNano(); dl < lv.d.horizon { - return dl - } - return lv.d.horizon + return lv.deadline.UnixNano() } -// WorkspaceLeaseReply returns the published lease with its expiry clamped to -// what was granted (min(durable horizon, granted deadline)), for replies that -// report a lease to a host or operator. ok is false without a lease. +// WorkspaceLeaseReply returns the published lease with its expiry set to +// what was granted (the deadline), for replies that report a lease to a host +// or operator. ok is false without a lease. func (p *Publisher) WorkspaceLeaseReply(volume string) (WorkspaceLease, bool) { p.leaseMu.Lock() defer p.leaseMu.Unlock() @@ -222,9 +215,10 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine { // RenewWorkspaceLease answers a live holder from memory: it takes only the // leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant -// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu -// writer) pushes the horizon ahead. A first grant and an expired re-grant -// after the shared move barrier write synchronously. +// is now+TTL; nothing is written. A restarted master does not trust any +// earlier grant to have ended before its restart floor (restart + TTL + +// skew, set at load), so no durable horizon is needed. A first grant and an +// expired re-grant after the shared move barrier write synchronously. func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { if err := ctx.Err(); err != nil { return WorkspaceLease{}, err @@ -232,14 +226,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri p.beforeWorkspaceGrantLock("renewal") p.leaseMu.Lock() now := p.workspaceNow() // read under leaseMu: the forced-barrier argument needs it - // unlock releases leaseMu on a path that grants nothing and logs a due - // per-minute summary after the unlock: every renewal attempt, granted or - // refused, may close the window (a stall through expiry refuses only). - unlock := func() { - summary := p.leaseStats.summaryDue(now) - p.leaseMu.Unlock() - p.logLease(summary) - } + unlock := p.leaseMu.Unlock if p.deleteReserved[volume] { unlock() return WorkspaceLease{}, ErrWorkspaceDeleteReserved @@ -267,7 +254,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri unlock() return l, nil } - if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) { + if !now.Before(lv.deadline) { unlock() return p.regrantWorkspaceLease(ctx, volume, holder, epoch) } @@ -277,53 +264,19 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri unlock() return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") } - // The headroom alarm is sampled here, before the clamp: at the latest it - // fires on the first clamped grant of a streak (headroomAlarmLocked). - headroom := lv.d.horizon - now.UnixNano() - alarm := p.headroomAlarmLocked(volume, lv, headroom) grant := now.Add(p.workspaceTTL).UnixNano() - clamped := grant > lv.d.horizon - if clamped { - grant = lv.d.horizon - } // A grant without positive host validity (expiry minus half the skew // bound, leaseFact) would make the host fence on an invalid reply and lose // its remaining validity; refuse with an error instead. if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 { - horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242) - summary := p.leaseStats.summaryDue(now) - p.leaseMu.Unlock() - p.logLease(alarm) - p.logLease(summary) - return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano)) + unlock() + return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(lv.d.maxSkewNS)) } if g := time.Unix(0, grant); g.After(lv.deadline) { lv.deadline = g } - summary := p.leaseStats.observeGrant(now, headroom) - if clamped { - p.leaseStats.recordClamp(now) - } - var note string - switch { - case clamped && !lv.clamped: - lv.clamped = true - note = fmt.Sprintf("workspace lease: grants of volume=%s are clamped to the durable horizon %s (%s remaining); extensions are behind", - volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano), time.Duration(lv.d.horizon-now.UnixNano()).Round(time.Millisecond)) - case !clamped && lv.clamped: - lv.clamped = false - note = fmt.Sprintf("workspace lease: grants of volume=%s are no longer clamped (horizon %s)", volume, time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano)) - } - if lv.d.horizon < now.Add(p.workspaceTTL+p.workspaceTTL/4).UnixNano() && !lv.extending && !p.leaseClosing { - lv.extending = true - p.extWG.Add(1) // under leaseMu with !closing: no Add can follow CloseWorkspaceExtenders - go p.extendWorkspaceLease(volume, holder, epoch, now) - } l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS} p.leaseMu.Unlock() - p.logLease(alarm) - p.logLease(note) - p.logLease(summary) return l, nil } @@ -401,16 +354,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st } _, now, err := p.forcedMoveBarrierLocked(volume, s.Lease) if err != nil { - // The same two predicates as admission: lease expiry plus skew (wall - // time, persisted) and the grant deadline plus skew (this process's - // monotonic clock), each measured from now. A client adds the result - // to its own request start; it never compares clocks. + // The admission's predicate: the grant deadline plus skew (this + // process's monotonic clock; after a restart, the restart floor), + // measured from now. A client adds the result to its own request + // start; it never compares clocks. skew := p.workspaceSkew(s.Lease) - retry := max(time.Unix(0, s.Lease.ExpiresAtNS).Add(skew).Sub(now), p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0) + retry := max(p.leaseDeadlineLocked(volume).Add(skew).Sub(now), 0) return WorkspaceLease{}, &LeaseBarrierError{Until: now.Add(retry), RetryAfter: retry, err: err} } lease, grant := p.newWorkspaceLease(holder, epoch, now) - lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS) lease.MaxClockSkewNS = int64(p.workspaceSkew(s.Lease)) s.Lease = lease if err := p.persistWorkspaceLocked(volume, s); err != nil { @@ -420,90 +372,15 @@ func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder st return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil } -// newWorkspaceLease starts a lease at now: the durable horizon is -// now+1.5*TTL and the grant (the deadline) now+TTL. A first grant, expired -// re-grant and move issue start a lease this way. +// newWorkspaceLease starts a lease at now: the grant (the deadline) is +// now+TTL. The record's ExpiresAtNS (now+1.5*TTL) is kept for the record's +// shape and is read by nothing: a v1.0.x master would trust it, which is why +// the record's envelope version is 2. A first grant, expired re-grant and +// move issue start a lease this way. func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) { return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } -// extendWorkspaceLease is an ordinary writer: under p.mu it rechecks the -// lease and writes horizon H = trigger + 1.5*TTL through -// persistWorkspaceLocked, so its write and its publication are one p.mu -// section. Any write error is an unknown write and latches uncertainty -// (INV-AUTH-UNCERTAIN-001); a failed recheck is a known no-write. -func (p *Publisher) extendWorkspaceLease(volume, holder string, epoch uint64, trigger time.Time) { - defer p.extWG.Done() - p.beforeWorkspaceGrantLock("extension") - var note string - defer func() { - if note != "" { - log.Print(note) - } - }() - p.mu.Lock() - defer p.mu.Unlock() - defer func() { - p.leaseMu.Lock() - if lv := p.leaseViews[volume]; lv != nil { - lv.extending = false - } - p.leaseMu.Unlock() - }() - p.leaseMu.Lock() - closing := p.leaseClosing - p.leaseMu.Unlock() - if closing || p.deleteReserved[volume] { - return - } - _, line, ok := p.workspaceLineLocked(volume) - s := cloneWorkspace(p.workspace[volume]) - if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil || s.Lease.Revoking || - s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) || - p.workspaceUncertain[volume] || p.store == nil { - return - } - h := trigger.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano() - old := s.Lease.ExpiresAtNS - if h <= old { - return - } - s.Lease.ExpiresAtNS = h - write, wrote, err := p.persistWorkspaceTimedLocked(volume, s) - if wrote { - // The store write alone, failed or not, recorded when it returns - // (completed-write telemetry; a blocked write is not seen until then). - p.leaseMu.Lock() - p.leaseStats.recordExtensionWrite(p.workspaceNow(), write) - p.leaseMu.Unlock() - } - took := write.Round(time.Millisecond) - if err != nil { - if p.extendFailures[volume] == 0 { - note = fmt.Sprintf("workspace lease: extension of volume=%s failed after %s (horizon %s, %s remaining); the volume is now uncertain and its renewals are refused: %v", - volume, took, time.Unix(0, old).UTC().Format(time.RFC3339Nano), time.Until(time.Unix(0, old)).Round(time.Millisecond), err) - } - p.extendFailures[volume]++ - return - } - if n := p.extendFailures[volume]; n > 0 { - note = fmt.Sprintf("workspace lease: extension of volume=%s recovered after %d failures, took %s, horizon now %s", volume, n, took, time.Unix(0, h).UTC().Format(time.RFC3339Nano)) - delete(p.extendFailures, volume) - } -} - -// CloseWorkspaceExtenders stops admitting lease extensions and joins every -// admitted extender. Owners call it before closing the authority store: -// closing is set under p.mu -> leaseMu, so an extender either finished its -// write before or sees closing and does not write. -func (p *Publisher) CloseWorkspaceExtenders() { - p.mu.Lock() - p.leaseMu.Lock() - p.leaseClosing = true - p.leaseMu.Unlock() - p.mu.Unlock() - p.extWG.Wait() -} // LeaseBarrierError is an expired re-grant refused because the forced-move // barrier has not passed. Until is when it passes (master wall time) and diff --git a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go index 46d9050b3c..77ff5fae5c 100644 --- a/seaweed-block/core/authority/workspace_outcome_uncertain_test.go +++ b/seaweed-block/core/authority/workspace_outcome_uncertain_test.go @@ -73,7 +73,6 @@ func TestWorkspaceUncertaintyPrecedesRequestRefusal(t *testing.T) { ctx := context.Background() disk, _ := newTempStore(t) p, _, _ := forcedLostRangeFixture(t, disk, false) - t.Cleanup(p.CloseWorkspaceExtenders) bad := forcedLostRangeReq bad.TargetReplicaID = "other-slot" if _, err := p.MoveWorkspace(ctx, bad, forcedLostRangeHead); err == nil || errors.Is(err, ErrWorkspaceOutcomeUncertain) { diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 3a562bb09e..3ab7d5849c 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -214,7 +214,6 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) { clock := newTestClock() store := &hookStore{AuthorityStore: disk} p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(10*time.Second, clock.now), WithWorkspaceMaxClockSkew(4*time.Second)) - t.Cleanup(p.CloseWorkspaceExtenders) grant := bindAndGrant(t, p, "v", "r") if grant.ExpiresAtNS != clock.sec(10).UnixNano() || p.WorkspaceState("v").Lease.ExpiresAtNS != clock.sec(15).UnixNano() { t.Fatal("fixture did not create the declared grant/horizon", grant) @@ -251,10 +250,8 @@ func TestWorkspaceLeaseRegrantRetainsPersistedSkewAfterRestart(t *testing.T) { clock := newTestClock() first := newLeasePublisher(t, disk, time.Second, clock) before := bindAndGrant(t, first, "v", "r") - first.CloseWorkspaceExtenders() clock.at(3) returned := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock.now), WithWorkspaceMaxClockSkew(time.Millisecond)) - t.Cleanup(returned.CloseWorkspaceExtenders) // Restart deadline is 4 s. The newly configured 1 ms bound has passed, // but the original persisted bound still protects the previous process. clock.at(4.5) diff --git a/seaweed-block/core/authority/workspace_renewal_slowstore_test.go b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go index 6d7ddf652e..41b7a9a822 100644 --- a/seaweed-block/core/authority/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go @@ -34,7 +34,6 @@ func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) { var nowNS atomic.Int64 nowNS.Store(time.Unix(1000, 0).UnixNano()) p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) - t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "old", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { t.Fatal(err) } @@ -58,7 +57,6 @@ func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) { t.Fatalf("renewal of a live lease took %s behind a 2.5 s store write; the host's renewal RPC times out at 2 s", took.Round(time.Millisecond)) } t.Logf("renewal took %s", took) - waitExtenders(t, p) if slow.puts.Load() == 0 { t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it") } @@ -73,7 +71,6 @@ func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) { var nowNS atomic.Int64 nowNS.Store(time.Unix(1000, 0).UnixNano()) p := NewPublisher(nil, WithStore(slow), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) - t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes const n = 6 for i := 0; i < n; i++ { v := fmt.Sprintf("v%d", i) @@ -116,7 +113,6 @@ func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) { t.Fatalf("slowest of %d concurrent renewals took %s (all: %v); renewals serialize behind each other's store writes", n, slowest.Round(time.Millisecond), took) } t.Logf("slowest of %d concurrent renewals took %s", n, slowest) - waitExtenders(t, p) if slow.puts.Load() == 0 { t.Fatal("no lease write went through the 0.5 s stall: the test did not exercise it") } @@ -156,7 +152,6 @@ func TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite(t *testing.T) { var nowNS atomic.Int64 nowNS.Store(time.Unix(1000, 0).UnixNano()) p := NewPublisher(nil, WithStore(held), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return time.Unix(0, nowNS.Load()) })) - t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes for _, v := range []string{"a", "b"} { if err := p.apply(AssignmentAsk{VolumeID: v, ReplicaID: "r", DataAddr: "d", CtrlAddr: "c", Intent: IntentBind}); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/authority/workspace_restart_barrier_test.go b/seaweed-block/core/authority/workspace_restart_barrier_test.go index 0c925399b3..17fcf09ef0 100644 --- a/seaweed-block/core/authority/workspace_restart_barrier_test.go +++ b/seaweed-block/core/authority/workspace_restart_barrier_test.go @@ -16,7 +16,6 @@ func TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor(t *testing.T c := newTestClock() p := newLeasePublisher(t, disk, 30*time.Second, c) bindAndGrant(t, p, "v", "r") // t=0: lease horizon t=45 (1.5 TTL), grant deadline t=30 - p.CloseWorkspaceExtenders() c.at(40) // the master restarts while the lease is still live p2 := newLeasePublisher(t, disk, 30*time.Second, c) @@ -45,7 +44,6 @@ func TestAfterARestartTheSameLiveHolderRenewsAtOnce(t *testing.T) { c := newTestClock() p := newLeasePublisher(t, disk, 30*time.Second, c) bindAndGrant(t, p, "v", "r") - p.CloseWorkspaceExtenders() c.at(20) p2 := newLeasePublisher(t, disk, 30*time.Second, c) diff --git a/seaweed-block/core/authority/workspace_restart_grace_test.go b/seaweed-block/core/authority/workspace_restart_grace_test.go new file mode 100644 index 0000000000..f0ab695d49 --- /dev/null +++ b/seaweed-block/core/authority/workspace_restart_grace_test.go @@ -0,0 +1,82 @@ +package authority + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" +) + +// Renewals write nothing durable: a grant is now+TTL from memory, and no +// horizon is kept current behind it. 1,000 renewals over 100 volumes (50 s +// at TTL 30 s) add no record. (The horizon design wrote one extension per +// volume about every quarter TTL.) +func TestRenewalWritesNothingDurable(t *testing.T) { + ctx := context.Background() + c := newTestClock() + st := &deleteGrantStore{} + p := newLeasePublisher(t, st, 30*time.Second, c) + for i := 0; i < 100; i++ { + bindAndGrant(t, p, fmt.Sprintf("v%03d", i), "r") + } + base := len(st.records) + for round := 1; round <= 10; round++ { + c.at(float64(round * 5)) + for i := 0; i < 100; i++ { + if _, err := p.RenewWorkspaceLease(ctx, fmt.Sprintf("v%03d", i), "r", 1); err != nil { + t.Fatalf("round %d, v%03d: %v", round, i, err) + } + } + } + time.Sleep(50 * time.Millisecond) // an asynchronous writer, had one started, would have written + if n := len(st.records) - base; n != 0 { + t.Fatalf("1,000 renewals wrote %d records, want 0", n) + } +} + +// After a restart, a different holder is admitted at the restart floor +// (restart + TTL + skew, on the new process's own clock), whatever wall +// value an earlier process wrote: here the clock was stepped back an hour +// across the restart, and the old record's horizon lies an hour ahead. +func TestForcedAdmissionIgnoresAPersistedHorizon(t *testing.T) { + ctx := context.Background() + c := newTestClock() + st := &deleteGrantStore{} + p := newLeasePublisher(t, st, 30*time.Second, c) + bindAndGrant(t, p, "v", "r") // t=0: the record's ExpiresAtNS is t=45 s (wall) + c.at(-3600) // the clock steps back an hour; the master restarts + p2 := newLeasePublisher(t, st, 30*time.Second, c) + c.at(-3600 + 49) + if err := p2.WorkspaceForcedMoveAdmitted(ctx, "v", "fm-early", "r", 1); err == nil { + t.Fatal("a forced move was admitted before the restart floor (restart + TTL + skew)") + } + c.at(-3600 + 50) + if err := p2.WorkspaceForcedMoveAdmitted(ctx, "v", "fm-floor", "r", 1); err != nil { + t.Fatalf("a forced move at the restart floor was refused (it waited for a wall value an earlier process wrote): %v", err) + } +} + +// The authority record's envelope is version 2: a v1.0.x master, which +// trusts the persisted horizon a v1.1 master no longer keeps current, +// refuses every envelope version but 1. Today's decoder reads both. +func TestARecordWrittenNowIsRefusedByAV100Master(t *testing.T) { + r := DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1} + raw, err := encodeEnvelope(r) + if err != nil { + t.Fatal(err) + } + var env struct { + Version int `json:"v"` + } + if err := json.Unmarshal(raw, &env); err != nil { + t.Fatal(err) + } + // v1.0.x's decodeEnvelope: "if env.Version != 1 { ErrCorruptRecord }". + if env.Version == storeEnvelopeVersionV100 { + t.Fatalf("a record written now carries envelope version %d, which a v1.0.x master accepts", env.Version) + } + if _, err := decodeEnvelope(raw, "v"); err != nil { + t.Fatalf("today's decoder refuses today's record: %v", err) + } +} diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go index 3635d94ea2..bbc19d9c75 100644 --- a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -223,7 +223,6 @@ func TestWorkspaceUnclaimedGrantGranteeRenewsNormally(t *testing.T) { for wait := time.Now().Add(5 * time.Second); time.Now().Before(wait) && (st.Lease == nil || st.Lease.ExpiresAtNS == issued.Add(grantTTL+grantTTL/2).UnixNano()); st = p.WorkspaceState("v") { time.Sleep(5 * time.Millisecond) } - p.CloseWorkspaceExtenders() if st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { t.Fatalf("issued lease not extended: %+v", st.Lease) } diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index ef00e39956..e2979f3207 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -624,10 +624,6 @@ func (h *Host) Close(ctx context.Context) error { } h.wg.Wait() - // Join lease extenders (authority writers) before the store closes. - if h.boot != nil && h.boot.Publisher != nil { - h.boot.Publisher.CloseWorkspaceExtenders() - } return errors.Join(statusErr, h.boot.Close()) } diff --git a/seaweed-block/core/host/master/journal_isolation.go b/seaweed-block/core/host/master/journal_isolation.go index fe6996584e..3fa3589884 100644 --- a/seaweed-block/core/host/master/journal_isolation.go +++ b/seaweed-block/core/host/master/journal_isolation.go @@ -189,38 +189,19 @@ func ValidateControlListen(flag, addr string) error { return fmt.Errorf("--%s %q is not a loopback address: an unauthenticated listener stays on loopback", flag, addr) } -// WorkspaceLeaseStatus is the GET /status/workspace-lease body. +// WorkspaceLeaseStatus is the GET /status/workspace-lease body: the +// journal-isolation counters. (The lease horizon's headroom, clamp and +// extension-write counters are gone with the horizon: renewals write +// nothing.) type WorkspaceLeaseStatus struct { - ColocatedNodes int `json:"colocated_nodes"` - HeadroomAlarms uint64 `json:"headroom_alarms"` - ClampsTotal uint64 `json:"clamps_total"` - ClampsLastMinute uint64 `json:"clamps_last_minute"` - MinHeadroomMS int64 `json:"min_headroom_ms"` // -1: no grant observed yet - StrictJournalIsolation bool `json:"strict_journal_isolation"` - // Lease extension store write latency, the earliest lag signal. - ExtensionWriteLastMS int64 `json:"extension_write_last_ms"` // -1: no extension write yet - ExtensionWriteMaxLastMinuteMS int64 `json:"extension_write_max_last_minute_ms"` // -1: none in the last minute + ColocatedNodes int `json:"colocated_nodes"` + StrictJournalIsolation bool `json:"strict_journal_isolation"` } -// WorkspaceLeaseStatus returns the journal-isolation and lease headroom -// counters served by the status endpoint. +// WorkspaceLeaseStatus returns the journal-isolation counters served by the +// status endpoint. func (h *Host) WorkspaceLeaseStatus() WorkspaceLeaseStatus { - st := WorkspaceLeaseStatus{ColocatedNodes: h.journal.count(), MinHeadroomMS: -1, StrictJournalIsolation: h.cfg.StrictJournalIsolation, - ExtensionWriteLastMS: -1, ExtensionWriteMaxLastMinuteMS: -1} - if p := h.Publisher(); p != nil { - s := p.WorkspaceLeaseStats() - st.HeadroomAlarms, st.ClampsTotal, st.ClampsLastMinute = s.HeadroomAlarms, s.ClampsTotal, s.ClampsLastMinute - if s.MinHeadroomObserved { - st.MinHeadroomMS = s.MinHeadroom.Milliseconds() - } - if s.ExtensionWriteObserved { - st.ExtensionWriteLastMS = s.ExtensionWriteLast.Milliseconds() - } - if s.ExtensionWriteInLastMinute { - st.ExtensionWriteMaxLastMinuteMS = s.ExtensionWriteMaxLastMinute.Milliseconds() - } - } - return st + return WorkspaceLeaseStatus{ColocatedNodes: h.journal.count(), StrictJournalIsolation: h.cfg.StrictJournalIsolation} } func (h *Host) statusHandler() http.Handler { diff --git a/seaweed-block/core/host/master/journal_isolation_test.go b/seaweed-block/core/host/master/journal_isolation_test.go index 8793449521..b56b5bec24 100644 --- a/seaweed-block/core/host/master/journal_isolation_test.go +++ b/seaweed-block/core/host/master/journal_isolation_test.go @@ -316,14 +316,18 @@ func TestStatusEndpointLoopbackOnlyAndServesJSON(t *testing.T) { if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { t.Fatal(err) } - for _, k := range []string{"colocated_nodes", "headroom_alarms", "clamps_total", "clamps_last_minute", "min_headroom_ms", "strict_journal_isolation", - "extension_write_last_ms", "extension_write_max_last_minute_ms"} { + for _, k := range []string{"colocated_nodes", "strict_journal_isolation"} { if _, ok := body[k]; !ok { t.Fatalf("status JSON lacks %q: %v", k, body) } } - if body["strict_journal_isolation"] != true || body["colocated_nodes"] != float64(0) || body["min_headroom_ms"] != float64(-1) || - body["extension_write_last_ms"] != float64(-1) || body["extension_write_max_last_minute_ms"] != float64(-1) { + // The lease horizon's counters are gone with the horizon. + for _, k := range []string{"headroom_alarms", "clamps_total", "min_headroom_ms", "extension_write_last_ms"} { + if _, ok := body[k]; ok { + t.Fatalf("status JSON still serves %q: %v", k, body) + } + } + if body["strict_journal_isolation"] != true || body["colocated_nodes"] != float64(0) { t.Fatalf("status JSON values: %v", body) } if post, err := http.Post("http://"+m.StatusAddr()+"/status/workspace-lease", "application/json", nil); err != nil || post.StatusCode != http.StatusMethodNotAllowed { diff --git a/seaweed-block/core/host/master/workspace_lease_horizon_test.go b/seaweed-block/core/host/master/workspace_lease_horizon_test.go index 45aabdfb6e..01235d2b41 100644 --- a/seaweed-block/core/host/master/workspace_lease_horizon_test.go +++ b/seaweed-block/core/host/master/workspace_lease_horizon_test.go @@ -32,9 +32,10 @@ func (s *stalledGuardStore) Put(r authority.DurableRecord) error { } // Control 1 (host side): with the master's store stalled for good, a real -// guard keeps serving on clamped grants and fences by the durable horizon -// minus half the skew bound, not earlier and not later than the horizon. -func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) { +// guard keeps serving: a renewal writes nothing, so a stalled store cannot +// make a grant short or late. The guard stays healthy for more than two TTLs +// and no lease write reaches the stalled store. +func TestWorkspaceLeaseGuardServesThroughAStalledStore(t *testing.T) { disk, err := authority.NewFileAuthorityStore(t.TempDir()) if err != nil { t.Fatal(err) @@ -50,7 +51,6 @@ func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) { dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} p := authority.NewPublisher(dir, authority.WithStore(stall), authority.WithWorkspaceLeaseConfig(3*time.Second, nil)) seedSkewPublisher(t, p, dir) - t.Cleanup(p.CloseWorkspaceExtenders) var releaseOnce sync.Once t.Cleanup(func() { releaseOnce.Do(func() { close(stall.release) }) }) // runs first: unblock the extender var stops atomic.Int32 @@ -76,30 +76,18 @@ func TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore(t *testing.T) { t.Fatal("first grant did not arrive") } } - lease := p.WorkspaceState("v").Lease - horizon := time.Unix(0, lease.ExpiresAtNS) - halfSkew := time.Duration(lease.MaxClockSkewNS) / 2 stall.armed.Store(true) - var fencedAt time.Time - for deadline := horizon.Add(2 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { + for end := time.Now().Add(2*3*time.Second + time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) { if !g.Projection().Healthy { - fencedAt = time.Now() - break + t.Fatal("the guard fenced while the master's store was stalled: a renewal waited on the store") } } - if fencedAt.IsZero() { - t.Fatalf("guard still serving 2 s past the durable horizon %s", horizon.Format(time.RFC3339Nano)) + if n := stall.puts.Load(); n != 0 { + t.Fatalf("%d lease writes reached the stalled store during renewals, want 0", n) } - if fencedAt.After(horizon.Add(300 * time.Millisecond)) { - t.Fatalf("guard fenced %s after the durable horizon", fencedAt.Sub(horizon)) + if stops.Load() != 0 { + t.Fatalf("the guard stopped the volume %d times", stops.Load()) } - if early := horizon.Add(-halfSkew - 500*time.Millisecond); fencedAt.Before(early) { - t.Fatalf("guard fenced %s before horizon - skew/2: grants did not clamp to the horizon", early.Sub(fencedAt)) - } - if stall.puts.Load() == 0 { - t.Fatal("no extender write reached the stalled store") - } - t.Logf("guard fenced %s before the durable horizon (half skew %s)", horizon.Sub(fencedAt).Round(time.Millisecond), halfSkew) } // Control 6a and the reply clamp: through the services layer, QueryWorkspace diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go index c02ed5a927..774b7b93e5 100644 --- a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -149,7 +149,6 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { }) dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil)) - t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes t.Cleanup(slow.release) // runs before the join above: frees a held Put first seedSkewPublisher(t, p, dir) var stops atomic.Int32 diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 82687d170d..f7ef1f50ac 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -313,7 +313,7 @@ intents remain rooted after restart; elapsed TTL is not a settlement proof. **Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`). -**Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is min(now + TTL, durable horizon), where the horizon is the lease expiry stored on disk; a background extension, an ordinary authority write, keeps the horizon about 1.5·TTL ahead of the last renewal that triggered it. Only the first grant of a lease is written synchronously. If extensions fall behind, grants shrink and the host fences by the horizon minus half the skew bound; a failed extension write makes the volume uncertain and refuses renewals that would issue a new or extended grant (a Revoking lease still gets its bounded drain reply). +**Master side of a renewal** (`core/authority/workspace_lease_view.go`): blockmaster answers a renewal of an established lease from memory, under a small leaf lock, with no disk write and without waiting for other authority writes. The grant is now + TTL, and nothing is written: a restarted blockmaster does not need a stored expiry, because it grants a different holder only after its restart floor (its own start + TTL + the skew bound, on its own clock), by which time every grant an earlier process made has ended. Only the first grant of a lease (and an expired re-grant, a move issue) is written synchronously. A volume whose authority write failed is uncertain and refuses renewals that would issue a new grant (a Revoking lease still gets its bounded drain reply). **Uncertain move outcomes** (`INV-AUTH-UNCERTAIN-001`): at a failed move's reply boundary, the publisher's per-volume persistence latch takes precedence over request, forced-admission, HEAD-read and target refusals. Such a reply is UNKNOWN with same-request recovery after reload, without another authority write. Only an ended request context preserves typed cancellation/deadline; dependency context errors with a live request are UNKNOWN. A known successful issued replay remains valid. @@ -328,9 +328,9 @@ flowchart LR **CLEAN move:** Detach publishes the final cut with `State = detached` in one CAS �' revoke �' the host drains frontend, replication and provider and acknowledges the stored detached HEAD generation �' blockmaster checks the detached HEAD and the matching acknowledgement �' new epoch �' the new host claims HEAD. -**FORCED move:** blockmaster waits until both the persisted lease horizon (at least every grant, so at most TTL/2 later than the last grant) and the granted or conservative restart deadline, plus the full skew bound, have passed (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. +**FORCED move:** blockmaster waits until the granted deadline (the latest grant it made) or, after a restart, its restart floor, plus the full skew bound, has passed; it reads no lease value an earlier process wrote (`core/authority/workspace.go` `prepareWorkspaceMoveLocked`). The old host's late CAS fails on the epoch; its uploads become orphans for GC. Writes since the old host's last cut are lost. -**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's expiry and deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim. +**Move issue starts the new holder's lease.** The write that issues epoch e+1 also writes the new holder's lease (granted deadline issue + TTL), published with the epoch in one lease-view update; the holder's first renewal is an ordinary renewal of it (`core/authority/workspace.go` `issueWorkspaceMove`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`). A new holder that dies before it renews or claims HEAD therefore expires like any holder, and a forced move away from it waits for that lease's deadline plus the skew bound, never a predecessor's. Blockmaster reads HEAD for a forced move only after that admission holds (`core/host/master/workspace_service.go` `MoveWorkspace`): the holder then starts no new claim or cut, but a claim it already sent may still land, so HEAD is not frozen. A forced move accepts a HEAD that names the expected holder at the expected epoch, or any HEAD at an older epoch (the expected holder never claimed it, or an earlier holder's late claim landed); its lost range starts at that HEAD's `RemoteLSN`. A HEAD at the expected or a higher epoch that is not the expected holder's is refused. A returning holder is stopped by two fences: its lease-gated attach refuses to claim (its lease has expired), and a HEAD that already carries a higher epoch fences its claim. **Takeover** (`core/storage/chunk_restore.go` `ClaimChunkHead`, called before the chunk layer attaches in `core/frontend/durable/provider_chunk.go`): read HEAD; fence if HEAD has a higher epoch or another holder at the same epoch; seed the local LSN frontier from HEAD (`PrepareRestore`); CAS HEAD to the new epoch and holder with `State = active`; on an unknown outcome, succeed only if a re-read shows the exact proposal. I/O opens afterwards; blocks load lazily on first read. @@ -353,7 +353,7 @@ sequenceDiagram A->>A: self-fence when ValidForNs runs out M->>M: wait for expiry, restart deadline and skew bound, then mint epoch e+1 end - M->>M: the issue write also starts B's lease (horizon issue+1.5·TTL, deadline issue+TTL) + M->>M: the issue write also starts B's lease (deadline issue+TTL) Note over M,B: target B may be source A; the same clean proof or forced barrier applies M->>B: assignment at epoch e+1 and a lease opt B dies before renewing or claiming (HEAD still at epoch e) @@ -381,17 +381,17 @@ stateDiagram-v2 state "Lease (blockmaster)" as L { [*] --> Granted: first Renew after bind (registered server id, from its registered host) [*] --> Granted: move issue starts the new holder's lease - Granted --> Granted: Renew before horizon and deadline (from memory; registered server id, from its registered host) + Granted --> Granted: Renew before the deadline (from memory, no write; registered server id, from its registered host) Granted --> Revoking: BeginWorkspaceRevocation Revoking --> Acked: registered host acks detached HEAD gen; publisher-clock validity after half max(configured, persisted) skew is positive Acked --> Moved: CLEAN move, including same host, new epoch - Granted --> Expired: horizon or deadline passes + Granted --> Expired: the deadline passes Expired --> Granted: unchanged holder from its registered host, no move/revocation, MAX expiry + skew passed; durable re-grant Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted) Granted --> DeleteReserved: lifecycle deletion committed, then exclusion published under publisher mu -> leaseMu Expired --> DeleteReserved: same permanent reservation DeleteReserved --> DeleteReserved: every grant/renewal/extension refuses; restart rebuilds exclusion before serving - DeleteReserved --> NoLiveLease: durable horizon and granted/restart deadline plus skew have both passed + DeleteReserved --> NoLiveLease: the granted or restart deadline plus skew has passed } ``` diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d1ee250300..5618e57380 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -144,8 +144,8 @@ flowchart LR | any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | | Uncertain | Uncertain (move answer) | failed move replies classify uncertainty after local locks release, before any admission refusal; request-context cancellation/deadline remain typed; known successful replay is unchanged | `core/authority/workspace.go` `WorkspaceMoveOutcomeError`; `core/host/master/workspace_service.go` `MoveWorkspace` | `INV-AUTH-UNCERTAIN-001` | | Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | -| any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant, renewal and background horizon extension check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the persisted lease horizon and restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | -| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease horizon as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` | +| any authority line | DeleteReserved (permanent) | the existing lifecycle reservation is committed durably; then `mu -> leaseMu` publishes the exclusion. Publication, move issue, first grant, expired re-grant and renewal check it under their writer lock. Restart reloads every committed exclusion before serving. Deleting HEAD requires the granted or restart deadline plus skew to have ended, including unclaimed grants; the check returns a refusal rather than waiting | `core/authority/workspace_delete_reservation.go` `ReserveWorkspaceDeletion`, `NoLiveWorkspaceLease`; `core/host/master/volume_delete_authority.go`; `host.go` `New` | `INV-SNAPK-DELETE-GATE-001` | +| any authority line, stores still awaited (stage 1) | DeleteReserved without the holder's acknowledgement | the master's record is marked first, durably and in the lock that ends the store wait; the mark freezes the record in stage 1 (the wait never ends after it, so the primary, whose assignment keeps awaiting the stores, never serves); the reservation then skips the live-lease refusal. Deleting HEAD waits out the lease as above. Past stage 1, also while the end of creation is unrecorded (the volume may be serving), the live-lease refusal stays | `core/host/master/volume_delete_authority.go` `Reserve`; `core/host/master/store_attestation.go` `markDeleteWithoutAck`, `awaited`; `core/authority/workspace_delete_reservation.go` `ReserveNeverCreatedWorkspaceDeletion` | `INV-WS-DELETE-WITHOUT-ACK-001` | **Volume creation phase, in blockmaster's store record** (`core/host/master/store_attestation.go`, decided by `inCreationPhase` in `core/host/master/product_loop.go`). Every replacement entry (both promotion gates, the operator's failover and planned move, the rebalance) acts only on Established. @@ -230,10 +230,10 @@ a pre-issued publication. | Revoking | Acked | `AckWorkspaceRevocation` from the primary server/replica at the current epoch, validated by the same RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) (missing/foreign server refused), an authoritative detached HEAD matching the ACK epoch/holder/position, for a first ACK, positive granted validity after half the configured/persisted skew on the publisher clock; a matching recorded stop answers before any lease check without writing, while a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` | | Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (including the source host; clean proof or forced-move lease barrier still required), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` | -| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | +| Granted or Revoking | Expired | the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | | Expired | Granted | Same current primary server/replica/epoch, validated by RPC holderMatches (registered server id, gRPC peer on its registered host: `refuseWorkspaceHolderHost`) with missing server refused, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/host/master/workspace_service.go` `holderMatches` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-AUTH-HOLDER-IDENTITY-001` | | Awaiting assignment / fenced | Process exited | Workspace chunk primary only: exhausted startup wait (`INV-WS-MASTER-WAIT-001`: 30 s of answered contact past the master's barrier time; no bound while the master gives no reply) or lease fence exits 75 after bounded cleanup; a typed master FINAL refusal for a recorded revocation exits 79, while MOVED or DELETED exits 78 at once (an issued moved source may be refused on subscription before any own assignment); a foreign master fact newer than nonzero observed-own lineage or exact foreign HEAD at or above the assigned epoch permits 78. Planned drain retires startup monitoring before cleanup; ACK and signal retain normal exit. Restart follows the unchanged grant and HEAD-claim gates. | `cmd/blockvolume/process_exit.go` `superviseProcess`, `watchChunkStartup`, `waitWorkspaceStop`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `INV-WS-STARTUP-RETRY-001` | -| Expired | Moved (forced) | target may be the source host; explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-SAME-HOST-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | +| Expired | Moved (forced) | target may be the source host; explicit force; the granted or restart deadline plus the clock-skew bound has passed (this process's own deadline: the latest grant it made, or after a restart the restart floor; no wall value an earlier process wrote is read), for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced @`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-SAME-HOST-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` | | none, Granted, Revoking or Expired | Deleting | the chunk volume delete is admitted with `WorkspaceHolderState` = never started or deleting (`TERM-LIVE-HOLDER-001`): HEAD, read by blockmaster before its locks, is below the line's epoch, or already past the fence (deleting, purging, deleted: the rerun of a delete that stopped midway); no move pending. From then on renewals, grants, re-grants, revocations and moves of the volume are refused; the delete's HEAD compare-and-swap to deleting is its linearization point: a claim applied before it makes the delete refuse `volume_in_use` and give the reservation back, a claim after it fails. The lifecycle `DeleteVolume` reads no HEAD and keeps the ACK rule | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence`; `core/frontend/chunkstore/volume_delete.go` (HEAD to deleting) | `INV-WS-DELETE-NO-LIVE-HOLDER-001`, `INV-WS-CLAIM-BEFORE-SERVE-001` | | Moved | epoch issued | the moved owner is captured with the assignment under pub.mu and persisted with the issuing move journal before publication; the stream uses that captured owner, empty when unknown, with placement fallback only for a move-less epoch; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/assignment_owner.go` `captureAssignmentOwner`; `core/host/master/services.go` `assignmentFact`; `core/host/master/workspace_binding.go` `workspaceLineOwner`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` | @@ -806,12 +806,14 @@ Notes: | `INV-AUTH-RESTART-REISSUE-001` | A line records the primary process it was issued for (durable); a current primary reporting another process is re-issued its line at a new endpoint version, and a primary adopts no line issued for another process, so a restarted process never reuses the dead one's sessions. | M2 authority (RefreshEndpoint); M3 primary adoption | `core/authority/authority.go` `applyWithWorkspaceMove` (records the ask's or the source's incarnation); `core/authority/controller.go` `endpointStale`, `sameAsk`, `refreshAsk` (conditional on the line it read); `core/host/master/product_loop.go` `RunLifecycleProductTick`, `restartedHolderRefresh` (the product loop's direct path for a workspace-bound RF1 volume, conditional on the line it read); `core/authority/workspace.go` `persistWorkspaceTimedLocked`; `core/authority/observation_store.go` `SlotFactAt`; `core/host/master/host.go` (the source); `core/host/volume/host.go` `applyFact` | `TestPublisher_RestartedPrimaryGetsANewEndpointVersion`, `TestPublisher_AskWithoutAProcessIsIssuedForTheReportedOne`, `TestTopologyController_RestartedPrimaryAtTheSameAddressIsReissued`, `TestTopologyController_QueuedRefreshIsReplacedForANewerProcess`, `TestTopologyController_UnnamedLineIsReissuedOnceForTheReportingProcess`, `TestWorkspaceLeaseWriteKeepsTheLinesIncarnationAcrossReload`, `TestObservationStore_SlotFactAtIsTheProcessAtThoseEndpoints` (`core/authority/restart_endpoint_version_test.go`); `TestLinesNameTheirPrimarysProcess`, `TestLineForTheTargetsEndpointsNamesTheTargetsProcess` (`core/host/master/line_incarnation_test.go`); `TestRF1RuntimeVolumeIsReissuedToARestartedHolder`, `TestRF1RuntimeLineNamingNoProcessIsReissued`, `TestRF1RefreshDecidedBeforeACrossHostMoveIsNotApplied` (`core/host/master/rf1_restart_reissue_test.go`); `TestRefreshIsConditionalOnTheLineItWasDecidedAgainst`, `TestControllerRefreshNamesTheLineItWasDecidedAgainst` (`core/authority/refresh_expected_line_test.go`); `TestHost_ApplyFact_LineIssuedForAnotherProcessIsNotAdopted`, `TestHost_ApplyFact_UnnamedLineIsNotAdoptedWhereLinesNameTheirProcess` (`core/host/volume/line_incarnation_test.go`); `TestHostConfigAdoptsOnlyLinesNamingThisProcess` (`cmd/blockvolume/lines_name_their_process_test.go`); `TestRestartedPrimaryAtTheSameEpochIsAdmitted` (`core/replication/primary_restart_session_test.go`) | — | ACTIVE | | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it, a failed write does not publish it, and an unknown outcome (directory fsync after the rename failed) fail-stops blockmaster: see M2 any → (store write first). | M2 any → (store write first) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/authority_store_file.go` `Put` (`failStopDurabilityUnknown` after a failed directory open or fsync behind the rename, every record; a close error after a good fsync is reported written; Windows keeps its previous behaviour) | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`); `TestPutFailStopsWhenTheDirectoryFsyncFailsAfterRename`, `TestPutReportsWrittenWhenOnlyTheDirectoryCloseFails` (`core/authority/authority_store_dir_fsync_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | | `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`); `TestWorkspaceReplayedIssueStartsGranteeLease` (`core/authority/workspace_unclaimed_grant_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume, a lease extension included, latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view, the renewal path's only input, equals derive(the published authority line, workspace state, uncertainty, store presence). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | A failed authority write for a workspace volume latches uncertainty until a restart reloads the store: later authority changes and new or extended grants for that volume are refused. See M2 any (workspace) → Uncertain and Uncertain → Uncertain (move answer). | M2 any (workspace) → Uncertain; Uncertain → Uncertain (move answer) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `WorkspaceMoveOutcomeError`, `MoveWorkspace`; `core/host/master/workspace_service.go` `MoveWorkspace` | `TestWorkspaceUncertaintyPrecedesRequestRefusal` (`core/authority/workspace_outcome_uncertain_test.go`), `TestWorkspaceMoveUnknownPrecedesAdmissionRefusals` (`core/host/master/workspace_uncertain_precedence_test.go`), `TestWorkspaceUncertainIssueWriteIsTyped` (`core/authority/workspace_outcome_uncertain_test.go`) | `ControlPlane` `UniqueEpoch`; `WorkspaceMoveOutcome` `NoFalseRefusal`, `CallerEndTyped`, `UncertainReplyClass` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view, the renewal path's only input, equals derive(the published authority line, workspace state, uncertainty, store presence). | M2 every workspace transition | `core/authority/workspace_lease_view.go` `deriveLeaseLocked`, `refreshLeaseViewLocked`, `publishIssuedLeaseLocked`, `setLeaseDeadlineLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-LEASE-VIEW-OWNED-001` | The granted deadline and the extender flag exist only in the lease view; refreshing the view from its derive inputs never changes either of them. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `setLeaseDeadlineLocked`, `extendWorkspaceLease` | — | — | STUB | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch, the `Lease.ExpiresAtNS` persisted in the authority store is at least the published horizon, and the published horizon is at least every grant issued since the last reload. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`, `newWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked`, `issueWorkspaceMove` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-MONO-001` | Within one lease the published horizon never decreases: an extension writes a new horizon only when it is greater than the current one. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | Retired: v1.1 keeps no lease horizon current; renewals write nothing and a restarted master waits for its own restart floor (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED | +| `INV-WS-LEASE-HORIZON-MONO-001` | Retired with the lease horizon (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED | +| `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE | +| `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL + skew, own clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE | +| `INV-WS-AUTH-RECORD-V2-001` | An authority record this version writes has envelope version 2, which a v1.0.x master refuses (it would trust the record's stale lease expiry); this version reads versions 1 and 2. | M2 every workspace write | `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestARecordWrittenNowIsRefusedByAV100Master` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | @@ -903,8 +905,8 @@ Notes: | `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A same-host move issues a higher epoch: a clean move needs the current holder's sealed HEAD and its recorded epoch/holder/position ACK, and the successor reads that sealed image; a forced move needs the normal lease barrier and a durable lost-range record. | M2 Acked or Expired → Moved; M9 detached → higher-epoch idle | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/frontend/chunkstore/layout/start.go` `Start`, `core/frontend/chunkstore/layout/claim.go` `Claim` | `TestWorkspaceSameHostForcedMoveRecordsLostRange` (`core/authority/workspace_same_host_forced_test.go`); `TestWorkspaceRPCSameHostForcedRecoveryRecordsLoss` (`core/host/master/workspace_same_host_forced_test.go`); `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestLayoutSameHostCleanSuccessorReadsSealedImage` (`core/frontend/durable/provider_layout_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed`; `INV-SNAPK-DETACHED-001`. The B provider test performs a real plain detach, same-host higher-epoch fresh-root Start, and reads the sealed bytes. | ACTIVE | | `INV-WS-DELETE-NO-LIVE-HOLDER-001` | A workspace volume is marked deleting only with no live holder (`TERM-LIVE-HOLDER-001`): no line, a clean revocation ACK for the line, or HEAD below the line's epoch. A sealed HEAD without an ACK, a live or unreadable one is refused; the HEAD compare-and-swap to deleting fences a later claim. | M2 none/Granted/Revoking/Expired → Deleting | `core/authority/workspace_holder_state.go` `WorkspaceHolderState`; `core/authority/workspace.go` `RecordWorkspaceDeletion`; `core/host/master/services.go` `MarkVolumeDeleting`, `deleteHolderEvidence` | `TestWorkspaceHolderState` (`core/authority/workspace_holder_state_test.go`); `TestDeleteAdmitsANeverStartedLine` (`core/host/master/workspace_delete_never_started_test.go`); `TestDeleteAdmissionVerdicts` (`core/authority/workspace_delete_admission_test.go`); `TestMarkVolumeDeleting_RefusedWhileAssigned` (`core/host/master/volume_deleting_test.go`) | NeverStarted r2 `DeleteNeverStrandsALiveHolder`, `NoServedWriteLost`, re-run can finish, re-run can settle (exhaustive, 21 of 21 configurations as expected). Not modelled: two delete processes at the same instant; the gap between HEAD deleted and the volume marked deleted. Limit (v1): a never-started line that holds a lease is deleted once its lease horizon passed (about 60 s; the reservation refuses a live lease before it); the immediate exit is 1.0.1 | ACTIVE | | `INV-WS-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a revocation ACK matching its epoch, holder and published position; generation is readout only. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`); `TestWorkspaceLayoutHEADUsesTheMasterIdentity`, `TestWorkspaceLayoutHEADRefusalsAndStates`, `TestWorkspaceLayoutHEADReaderWiring`; also in `core/host/master/workspace_layout_head_test.go`, `cmd/blockmaster/workspace_layout_head_test.go` | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE | -| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is admitted only after the granted or restart deadline plus the clock-skew bound has passed for the lease the last move issue started (never a predecessor's; `INV-WS-RESTART-GRACE-001`): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`); `TestProcedureMasterUnreachableFencesBeforeForcedMove` (`cmd/blockvolume/master_loss_integration_test.go`, tags `subprocess chunkstore_integration`) | — | ACTIVE | +| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry (the deadline), never a persisted value. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE | | `INV-WS-FORCED-MOVE-HALF-SKEW-001` | The validity the master gives a host with a lease ends half the clock-skew bound before the reported lease expiry. | M2 Granted → Granted (reply); M4 NoLease, Valid → Valid | `core/authority/workspace_lease_view.go` `WorkspaceLeaseValidity`, `workspaceLeaseValidityAt`; `core/host/master/workspace_service.go` `leaseFact`; `core/authority/workspace.go` `AckWorkspaceRevocation`; `core/host/volume/workspace_lease.go` `Refresh` | `TestWorkspaceLeaseFactUsesPublisherClockAndSkew` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceAckUsesGrantedHalfSkewBoundary` (`core/authority/workspace_validity_test.go`); `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-READOUT-001` | Every issued forced grant the master returns, also on a replay and after a restart, carries the lost range stored in the authority store before the issue, never a recomputed one: see M2 Moved → epoch issued. | M2 lease: Expired → Moved (forced); Moved → epoch issued | `core/authority/workspace_lost_range.go` `recordLostRangeLocked`, `WorkspaceLostRangeReadouts`, `encodeLostRangeEnvelope`; `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/host/master/workspace_layout_head.go` `NewLayoutWorkspaceHEADReader`; `core/host/master/workspace_service.go` `grantWithLostRange`, `issuedRecord`; `core/rpc/wsclient/wsclient.go` `Readout` | `TestWorkspaceForcedMoveRecordsTheLostRange`, `TestWorkspaceForcedMoveLostRangeOrdering`, `TestWorkspaceForcedReservationResumeNeedsItsRange` (`core/authority/workspace_lost_range_test.go`); `TestWorkspaceForcedMoveStoresHeadFilerTime` (`core/authority/workspace_lost_range_readout_test.go`); `TestWorkspaceForcedMoveLostRangeOverRPC` (`core/host/master/workspace_lost_range_readout_test.go`); `TestReadoutWording` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceForceMove_Row3and4_SentAndGranted` (`cmd/sw-block/workspace_test.go`); `TestWorkspaceForceMoveAgainstRealMaster` (`cmd/sw-block/workspace_master_test.go`) | — | ACTIVE | | `INV-WS-LOST-RANGE-QUERY-001` | `QueryWorkspaceLostRange` returns the stored ranges unchanged: every issued forced move's range in issue order, or the single range of a given request id. | M2 lease: Moved → epoch issued (readout) | `core/authority/workspace_lost_range.go` `WorkspaceLostRangeReadouts`; `core/host/master/workspace_service.go` `QueryWorkspaceLostRange`; `core/rpc/wsclient/wsclient.go` `LostRanges`; `cmd/sw-block/workspace.go` `runWorkspaceLostRange` | `TestWorkspaceLostRangeAccumulatesInIssueOrder` (`core/authority/workspace_lost_range_readout_test.go`); `TestLostRangesBindsTheAnswer` (`core/rpc/wsclient/wsclient_test.go`); `TestWorkspaceLostRangeListsAllInOrder` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | From 3311545b14e6e3e2f67615b133ac688936a986cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:03:04 -0800 Subject: [PATCH 30/51] authority: the lease deadline keeps its monotonic reading A renewal's grant stays a time.Time (now+TTL with its monotonic reading) for the deadline admission compares; only the reply carries wall nanoseconds. The revoke ACK checks validity against that deadline the same way. A missing deadline reports expiry 0 (no host validity), and comments tell the deadline (restart + TTL) from the barrier (deadline + skew). Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/workspace.go | 9 ++--- .../core/authority/workspace_lease_view.go | 39 +++++++++++++------ .../authority/workspace_restart_grace_test.go | 23 +++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 4 files changed, 55 insertions(+), 18 deletions(-) diff --git a/seaweed-block/core/authority/workspace.go b/seaweed-block/core/authority/workspace.go index 8963f3479a..f0f92c72df 100644 --- a/seaweed-block/core/authority/workspace.go +++ b/seaweed-block/core/authority/workspace.go @@ -336,9 +336,7 @@ func (p *Publisher) AckWorkspaceRevocation(ctx context.Context, volume string, a if !ok || line.info.ReplicaID != ack.ReplicaID || line.info.Epoch != ack.Epoch || ack.Holder == "" || s == nil || s.Lease == nil || !s.Lease.Revoking { return fmt.Errorf("workspace revoke ACK: stale or unsolicited") } - lease := *s.Lease - lease.ExpiresAtNS = p.leaseDeadlineLocked(volume).UnixNano() - if p.WorkspaceLeaseValidity(lease) == 0 { + if p.deadlineValidity(p.leaseDeadlineLocked(volume), s.Lease.MaxClockSkewNS, p.workspaceNow()) == 0 { return fmt.Errorf("workspace revoke ACK: lease expired; forced move required") } s.Ack = &ack @@ -476,8 +474,9 @@ func (p *Publisher) forcedMoveAdmissionLocked(volume string, lease *WorkspaceLea // returns the barrier (the audit bound of the lost range: the granted or // restart deadline plus skew) whether or not it has passed, and an error // while it has not. The deadline is this process's own (the latest grant it -// made, or after a restart the restart floor, restart + TTL + skew); no -// value written by an earlier process is read. Caller holds p.mu. +// made, or after a restart the restart floor, restart + TTL); the barrier is +// that deadline plus the skew bound. No value written by an earlier process +// is read. Caller holds p.mu. func (p *Publisher) forcedMoveBarrierLocked(volume string, lease *WorkspaceLease) (lostUntil int64, now time.Time, err error) { now = p.workspaceNow() skew := p.workspaceSkew(lease) diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index f4c92d2306..e497d3c143 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -33,8 +33,9 @@ type leaseDerived struct { } // leaseView is one volume's renewal state. Guarded by Publisher.leaseMu. -// deadline (the latest grant, or the restart rule's now+TTL+skew) is owned -// by the view; d is derived. +// deadline (the latest grant, or after a restart the restart floor +// restart+TTL; a barrier adds the skew bound to it) is owned by the view; d +// is derived. type leaseView struct { d leaseDerived deadline time.Time @@ -121,14 +122,25 @@ func (p *Publisher) setLeaseDeadlineLocked(volume string, t time.Time, raise boo } // replyExpiryNS is the expiry reported to a host: what was granted (the -// deadline), never a persisted value. +// deadline), never a persisted value. Without a deadline (a published lease +// always has one) it reports 0, which gives the host no validity: fail +// closed. func (lv *leaseView) replyExpiryNS() int64 { if lv.deadline.IsZero() { - return lv.d.horizon // unreachable: a published lease always has a deadline + return 0 } return lv.deadline.UnixNano() } +// deadlineValidity is the host validity a grant expiring at deadline leaves +// at now: deadline minus half the skew bound, capped at the TTL, never +// negative. Both times are this process's, so the difference uses their +// monotonic readings. +func (p *Publisher) deadlineValidity(deadline time.Time, maxSkewNS int64, now time.Time) time.Duration { + skew := p.workspaceSkew(&WorkspaceLease{MaxClockSkewNS: maxSkewNS}) + return max(0, min(deadline.Add(-skew/2).Sub(now), p.workspaceTTL)) +} + // WorkspaceLeaseReply returns the published lease with its expiry set to // what was granted (the deadline), for replies that report a lease to a host // or operator. ok is false without a lease. @@ -215,9 +227,9 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine { // RenewWorkspaceLease answers a live holder from memory: it takes only the // leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant -// is now+TTL; nothing is written. A restarted master does not trust any -// earlier grant to have ended before its restart floor (restart + TTL + -// skew, set at load), so no durable horizon is needed. A first grant and an +// is now+TTL; nothing is written. A restarted master grants a different +// holder only once its restart floor (deadline restart + TTL, set at load) +// plus the skew bound has passed, so no durable horizon is needed. A first grant and an // expired re-grant after the shared move barrier write synchronously. func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { if err := ctx.Err(); err != nil { @@ -264,18 +276,21 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri unlock() return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain") } - grant := now.Add(p.workspaceTTL).UnixNano() + // The grant stays a time.Time with its monotonic reading: the deadline + // it raises is what admission compares (this process's own clock); only + // the reply carries wall nanoseconds. + grant := now.Add(p.workspaceTTL) // A grant without positive host validity (expiry minus half the skew // bound, leaseFact) would make the host fence on an invalid reply and lose // its remaining validity; refuse with an error instead. - if p.workspaceLeaseValidityAt(WorkspaceLease{ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS}, now) == 0 { + if p.deadlineValidity(grant, lv.d.maxSkewNS, now) == 0 { unlock() return WorkspaceLease{}, fmt.Errorf("workspace lease: a grant of %s leaves no host validity under skew bound %s", p.workspaceTTL, time.Duration(lv.d.maxSkewNS)) } - if g := time.Unix(0, grant); g.After(lv.deadline) { - lv.deadline = g + if grant.After(lv.deadline) { + lv.deadline = grant } - l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant, MaxClockSkewNS: lv.d.maxSkewNS} + l := WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lv.d.maxSkewNS} p.leaseMu.Unlock() return l, nil } diff --git a/seaweed-block/core/authority/workspace_restart_grace_test.go b/seaweed-block/core/authority/workspace_restart_grace_test.go index f0ab695d49..2ab7e7b274 100644 --- a/seaweed-block/core/authority/workspace_restart_grace_test.go +++ b/seaweed-block/core/authority/workspace_restart_grace_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "strings" "testing" "time" ) @@ -80,3 +81,25 @@ func TestARecordWrittenNowIsRefusedByAV100Master(t *testing.T) { t.Fatalf("today's decoder refuses today's record: %v", err) } } + +// The deadline admission compares keeps its monotonic reading through a +// first grant and through every renewal, so a wall-clock step inside one +// master neither shortens nor extends a lease (Go prints a monotonic +// reading as "m="). +func TestLeaseDeadlineKeepsItsMonotonicReading(t *testing.T) { + ctx := context.Background() + p := NewPublisher(nil, WithStore(&deleteGrantStore{}), WithWorkspaceLeaseConfig(30*time.Second, nil)) // the real clock + bindAndGrant(t, p, "v", "r") + monotonic := func(what string) { + t.Helper() + if d := p.leaseDeadlineLockedForTest("v"); !strings.Contains(d.String(), "m=") { + t.Fatalf("%s: the deadline %v has no monotonic reading: admission would compare wall time", what, d) + } + } + monotonic("after the first grant") + time.Sleep(2 * time.Millisecond) + if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { + t.Fatal(err) + } + monotonic("after a renewal") +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5618e57380..0ea5dcc666 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -812,7 +812,7 @@ Notes: | `INV-WS-LEASE-HORIZON-001` | Retired: v1.1 keeps no lease horizon current; renewals write nothing and a restarted master waits for its own restart floor (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED | | `INV-WS-LEASE-HORIZON-MONO-001` | Retired with the lease horizon (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED | | `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE | -| `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL + skew, own clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE | +| `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL, own monotonic clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE | | `INV-WS-AUTH-RECORD-V2-001` | An authority record this version writes has envelope version 2, which a v1.0.x master refuses (it would trust the record's stale lease expiry); this version reads versions 1 and 2. | M2 every workspace write | `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestARecordWrittenNowIsRefusedByAV100Master` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE | From da6130636d64d1f23fc4e2f5168c9dd976a22038 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:10:23 -0800 Subject: [PATCH 31/51] storage: a v1.1 no-op cut fences a foreign root at its own identity Commit by change made a v1.1 no-op cut compare only its captured chunks, so a HEAD read whole that had moved, at this holder's identity, to another chunk root was installed instead of fenced. A whole read's chunk root must again be the one the layer holds (the ref table), as the full comparison required; a HEAD moved with the same root still completes the no-op. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 8 +++++ .../core/storage/chunk_v11_outcomes_test.go | 29 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 9f4d6c18f3..4cefc76529 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1548,6 +1548,14 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch same := sameProposal(cur, baseHead) if byChange { same = sameByChange(cur, baseHead, headLookup(cur), nil, commitMarks(baseHead, captured, capturedVersions, map[uint64]*chunkRef{})) + if same && !fromBase { + // HEAD read whole: its chunk root must be the one the layer + // holds (the ref table), as the full comparison required; a + // HEAD moved at this identity to another root is fenced. + l.stMu.Lock() + same = sameChunkRoot(l.headChunksLocked(), cur.Chunks) + l.stMu.Unlock() + } } if !same { l.requeueCut(all) diff --git a/seaweed-block/core/storage/chunk_v11_outcomes_test.go b/seaweed-block/core/storage/chunk_v11_outcomes_test.go index e0d660c7c5..c4e660e6f9 100644 --- a/seaweed-block/core/storage/chunk_v11_outcomes_test.go +++ b/seaweed-block/core/storage/chunk_v11_outcomes_test.go @@ -172,3 +172,32 @@ func TestV11OutcomesKeepNoChunkMap(t *testing.T) { noMap(t, "the settled layer's kept result", kept) }) } + +// A no-op cut on the v1.1 format that reads HEAD whole and finds it moved, +// at this holder's own identity, to another chunk root is fenced, as on the +// v1.0 format: its captured chunks alone (none here) cannot tell that HEAD +// no longer names what the layer holds. A HEAD moved with the same root +// (only its generation) completes. +func TestV11NoOpCutFencesAForeignRootAtItsOwnIdentity(t *testing.T) { + t.Run("foreign root", func(t *testing.T) { + _, f, l, _, _ := v11ReportLayer(t) + f.mu.Lock() + f.head = copyChunkHead(f.head) + f.head.Gen++ + f.head.Chunks[0] = f.head.Chunks[1] // HEAD now names another chunk at 0 + f.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errChunkLayerFenced) { + t.Fatalf("a no-op cut over a foreign root at its own identity: %v, want fenced", err) + } + }) + t.Run("same root", func(t *testing.T) { + _, f, l, _, _ := v11ReportLayer(t) + f.mu.Lock() + f.head = copyChunkHead(f.head) + f.head.Gen++ + f.mu.Unlock() + if r, err := l.Cut(ctTimeout(t)); err != nil || !r.Noop { + t.Fatalf("a no-op cut over the same root at a newer generation: %+v %v, want a no-op", r, err) + } + }) +} From 518e418fe0ce2fe7d1131ff9e52c70e1e83cec4a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:10:41 -0800 Subject: [PATCH 32/51] master: a v1.0.x master refuses to start on a store this version opened Before it serves, under the authority store's lock, the master writes store-attestations.json as {"format":2,"volumes":{...}}. A v1.0.x master decodes that file as a bare map of volume records and returns the error from New before it listens or publishes. This master reads the envelope and v1.0.x's bare map (rewritten as the envelope at start) and refuses a later format. The authority record's version 2 alone does not stop a v1.0.x master (its loader skips such a record); the test is renamed to say it fails the v1.0.x decoder. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_restart_grace_test.go | 12 ++-- .../core/host/master/golden_v100_test.go | 62 +++++++++++++++- seaweed-block/core/host/master/host.go | 6 ++ .../core/host/master/store_attestation.go | 72 +++++++++++++++++-- seaweed-block/docs/design/invariants.md | 2 +- 5 files changed, 140 insertions(+), 14 deletions(-) diff --git a/seaweed-block/core/authority/workspace_restart_grace_test.go b/seaweed-block/core/authority/workspace_restart_grace_test.go index 2ab7e7b274..a923b41719 100644 --- a/seaweed-block/core/authority/workspace_restart_grace_test.go +++ b/seaweed-block/core/authority/workspace_restart_grace_test.go @@ -58,10 +58,12 @@ func TestForcedAdmissionIgnoresAPersistedHorizon(t *testing.T) { } } -// The authority record's envelope is version 2: a v1.0.x master, which -// trusts the persisted horizon a v1.1 master no longer keeps current, -// refuses every envelope version but 1. Today's decoder reads both. -func TestARecordWrittenNowIsRefusedByAV100Master(t *testing.T) { +// The authority record's envelope is version 2: v1.0.x's decoder refuses +// every envelope version but 1 (its loader then skips the record, so this +// alone does not stop a v1.0.x master: the store's attestation envelope +// fails its whole start, TestAV100MasterRefusesTheAttestationEnvelope in +// core/host/master). Today's decoder reads both. +func TestARecordWrittenNowFailsTheV100Decoder(t *testing.T) { r := DurableRecord{VolumeID: "v", ReplicaID: "r", Epoch: 1} raw, err := encodeEnvelope(r) if err != nil { @@ -75,7 +77,7 @@ func TestARecordWrittenNowIsRefusedByAV100Master(t *testing.T) { } // v1.0.x's decodeEnvelope: "if env.Version != 1 { ErrCorruptRecord }". if env.Version == storeEnvelopeVersionV100 { - t.Fatalf("a record written now carries envelope version %d, which a v1.0.x master accepts", env.Version) + t.Fatalf("a record written now carries envelope version %d, which v1.0.x's decoder accepts", env.Version) } if _, err := decodeEnvelope(raw, "v"); err != nil { t.Fatalf("today's decoder refuses today's record: %v", err) diff --git a/seaweed-block/core/host/master/golden_v100_test.go b/seaweed-block/core/host/master/golden_v100_test.go index 90cc402640..f37cfa8ec3 100644 --- a/seaweed-block/core/host/master/golden_v100_test.go +++ b/seaweed-block/core/host/master/golden_v100_test.go @@ -4,6 +4,7 @@ import ( "bytes" "crypto/sha1" "encoding/hex" + "encoding/json" "fmt" "os" "path/filepath" @@ -76,19 +77,74 @@ func TestAttestationGoldenFileIsTheV100File(t *testing.T) { } } -// Today's store writes the v1.0.0 file for the same steps. -func TestAttestationsWriteTheV100File(t *testing.T) { +// Today's store writes the v1.0.0 file's volumes for the same steps, inside +// this version's envelope: {"format":2,"volumes":}. The +// one change since v1.0.0, by the format path: a v1.0.x master refuses the +// envelope at start (TestAV100MasterRefusesTheAttestationEnvelope). +func TestAttestationsWriteTheV100FileInTheEnvelope(t *testing.T) { dir := t.TempDir() goldenAttestations(t, dir) got, err := os.ReadFile(filepath.Join(dir, storeAttestationFile)) if err != nil { t.Fatal(err) } - if want := readGoldenAttestations(t); !bytes.Equal(got, want) { + want := append(append([]byte(`{"format":2,"volumes":`), readGoldenAttestations(t)...), '}') + if !bytes.Equal(got, want) { t.Fatalf("%s\n got %s\n want %s", goldenAttestationFix, got, want) } } +// A v1.0.x master decodes store-attestations.json as a bare map of volume +// records (json.Unmarshal into map[string]attestedStores, its +// loadStoreAttestations), and its New returns that error before it listens +// or publishes. The envelope fails that decode; today's master reads both +// forms, and a master started on a v1.0.x store rewrites it as the envelope +// before it serves. +func TestAV100MasterRefusesTheAttestationEnvelope(t *testing.T) { + dir := t.TempDir() + goldenAttestations(t, dir) + b, err := os.ReadFile(filepath.Join(dir, storeAttestationFile)) + if err != nil { + t.Fatal(err) + } + var v100 map[string]attestedStores // v1.0.x's decode, verbatim + if err := json.Unmarshal(b, &v100); err == nil { + t.Fatalf("a v1.0.x master's decode accepted the file written now: %v", v100) + } + if bad := readAttestations(dir); len(bad) != 0 { + t.Fatalf("today's master does not read its own envelope: %v", bad) + } + // A v1.0.x store (the bare map) is read, and ensureEnvelope rewrites it. + old := t.TempDir() + if err := os.WriteFile(filepath.Join(old, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil { + t.Fatal(err) + } + s, err := loadStoreAttestations(old) + if err != nil { + t.Fatal(err) + } + if bad := readAttestations(old); len(bad) != 0 { + t.Fatalf("today's master does not read the v1.0.x form: %v", bad) + } + if err := s.ensureEnvelope(); err != nil { + t.Fatal(err) + } + b, err = os.ReadFile(filepath.Join(old, storeAttestationFile)) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(b, &v100); err == nil { + t.Fatal("after ensureEnvelope, a v1.0.x master's decode still accepts the store") + } + // An envelope of a later format is refused by this master too. + if err := os.WriteFile(filepath.Join(old, storeAttestationFile), []byte(`{"format":3,"volumes":{}}`), 0o644); err != nil { + t.Fatal(err) + } + if _, err := loadStoreAttestations(old); err == nil { + t.Fatal("this master accepted attestation format 3") + } +} + // wantAttestations is the v1.0.0 file's content, written out independently // of the store: every volume's primary, epoch, stores and initial replicas. var wantAttestations = map[string]attestedStores{ diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index e2979f3207..802c61cdcf 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -282,6 +282,12 @@ func New(cfg Config) (*Host, error) { if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil { return nil, fmt.Errorf("master.New: %w", err) } + // Under the authority store's lock and before anything is served: the + // attestation file in this version's envelope, which a v1.0.x master + // refuses at start (store_attestation.go). + if err := h.attest.ensureEnvelope(); err != nil { + return nil, fmt.Errorf("master.New: %w", err) + } var sink authority.ControllerSink = ctrl if len(cfg.Topology.Volumes) == 0 { diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 5195f2e107..90c24f2bde 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -19,6 +19,19 @@ import ( // write (temp file, fsync, rename, directory fsync). const storeAttestationFile = "store-attestations.json" +// storeAttestationFormat is the envelope this master writes: +// {"format": 2, "volumes": {...}}. A v1.0.x master decodes the file as a +// bare map of volume records, so the number under "format" fails its whole +// start (before any listener or authority publication): the downgrade guard +// for what this version stops keeping current (the lease horizon). The +// bare map (v1.0.x's form) is still read. +const storeAttestationFormat = 2 + +type storeAttestationEnvelope struct { + Format int `json:"format"` + Volumes map[string]attestedStores `json:"volumes"` +} + // attestedStores is one volume's last attestation: the primary line that // made it and, per replica, the store that counted toward its write ACKs. type attestedStores struct { @@ -55,6 +68,9 @@ type storeAttestations struct { mu sync.Mutex path string // "" = memory only vols map[string]attestedStores + // enveloped: the file on disk is this version's envelope (persist always + // writes it; ensureEnvelope writes it at start). + enveloped bool // changed[vol] is closed (and dropped) when vol's record changes. changed map[string]chan struct{} } @@ -72,15 +88,61 @@ func loadStoreAttestations(dir string) (*storeAttestations, error) { if err != nil { return nil, fmt.Errorf("store attestations: %w", err) } - if err := json.Unmarshal(b, &s.vols); err != nil { + vols, enveloped, err := decodeStoreAttestations(b) + if err != nil { return nil, fmt.Errorf("store attestations %s: %w", s.path, err) } - if s.vols == nil { - s.vols = map[string]attestedStores{} - } + s.vols, s.enveloped = vols, enveloped return s, nil } +// decodeStoreAttestations reads either form: the envelope (a number under +// "format": this master reads format 2 only) or v1.0.x's bare map. +func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error) { + var probe map[string]json.RawMessage + if err := json.Unmarshal(b, &probe); err != nil { + return nil, false, err + } + if raw, ok := probe["format"]; ok { + var format int + if json.Unmarshal(raw, &format) == nil { + if format != storeAttestationFormat { + return nil, false, fmt.Errorf("format %d, this master reads format %d", format, storeAttestationFormat) + } + var env storeAttestationEnvelope + if err := json.Unmarshal(b, &env); err != nil { + return nil, false, err + } + if env.Volumes == nil { + env.Volumes = map[string]attestedStores{} + } + return env.Volumes, true, nil + } + } + vols := map[string]attestedStores{} + if err := json.Unmarshal(b, &vols); err != nil { + return nil, false, err + } + return vols, false, nil +} + +// ensureEnvelope writes the file in this version's envelope, durably, when +// it is absent or in v1.0.x's form: the master calls it before it serves +// anything, so a v1.0.x master started on this store afterwards refuses its +// whole start. +func (s *storeAttestations) ensureEnvelope() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.path == "" || s.enveloped { + return nil + } + if err := s.persist(s.vols); err != nil { + return err + } + s.enveloped = true + return nil +} + // lookup returns the store a primary of the volume last attested for // replica; false when none ever did. A replica dropped from the write-ACK // set since keeps it. @@ -334,7 +396,7 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error { if s.path == "" { return nil } - payload, err := json.Marshal(vols) + payload, err := json.Marshal(storeAttestationEnvelope{Format: storeAttestationFormat, Volumes: vols}) if err != nil { return err } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 0ea5dcc666..bd5251ffff 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -813,7 +813,7 @@ Notes: | `INV-WS-LEASE-HORIZON-MONO-001` | Retired with the lease horizon (`INV-WS-RESTART-GRACE-001`). | legacy M2 Granted → Granted | — | — | — | ARCHIVED | | `INV-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` ; `core/lifecycle/placement_intent.go` `GetPlacementSnapshot`; `core/host/master/workspace_service.go` `RenewWorkspaceLease`; `core/lifecycle/node_inventory.go` `GetNodeSnapshot` (the holder host check) | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) ; `TestPlacementSnapshotDoesNotWaitForWriter`, `TestPlacementSnapshotFailedCommitStaysCommitted` (`core/lifecycle/placement_snapshot_test.go`); `TestNodeSnapshotDoesNotWaitForARegistrationWrite` (`core/lifecycle/node_snapshot_test.go`); `TestLiveRenewalDoesNotWaitForAHeldRegistrationWrite` (`core/host/master/server_host_identity_test.go`) | — | ACTIVE | | `INV-WS-RESTART-GRACE-001` | A renewal writes nothing durable. A forced move, an expired re-grant and a delete's no-live-lease proof wait for this process's deadline plus skew: its latest grant, or after a restart the restart floor (restart + TTL, own monotonic clock); no lease value an earlier process wrote is read. | M2 Granted → Granted; Expired → Moved (forced); Expired → Granted; any → DeleteReserved | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `regrantWorkspaceLease`, `newWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`, `AckWorkspaceRevocation`; `core/authority/authority.go` `reloadFromStore` (the restart floor) | `TestRenewalWritesNothingDurable`, `TestForcedAdmissionIgnoresAPersistedHorizon` (`core/authority/workspace_restart_grace_test.go`); `TestWorkspaceLeaseGuardServesThroughAStalledStore` (`core/host/master/workspace_lease_horizon_test.go`); `TestAfterARestartADifferentHolderIsRefusedUntilTheRestartFloor`, `TestAfterARestartTheSameLiveHolderRenewsAtOnce` (`core/authority/workspace_restart_barrier_test.go`) | `LeaseRestart` `OneServer` (grace design) | ACTIVE | -| `INV-WS-AUTH-RECORD-V2-001` | An authority record this version writes has envelope version 2, which a v1.0.x master refuses (it would trust the record's stale lease expiry); this version reads versions 1 and 2. | M2 every workspace write | `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestARecordWrittenNowIsRefusedByAV100Master` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE | +| `INV-WS-AUTH-RECORD-V2-001` | Before it serves, this master writes the store's attestation file as format 2, on which a v1.0.x master refuses its whole start; its authority records are envelope version 2 (a v1.0.x master would skip them). It reads both forms of each. | M2 every workspace write; master start | `core/host/master/store_attestation.go` `ensureEnvelope`, `decodeStoreAttestations`; `core/host/master/host.go` `New`; `core/authority/authority_store.go` `storeEnvelopeVersion`, `encodeEnvelope`, `decodeEnvelope` | `TestAV100MasterRefusesTheAttestationEnvelope`, `TestAttestationsWriteTheV100FileInTheEnvelope`, `TestAttestationsReadTheV100File` (`core/host/master/golden_v100_test.go`); `TestARecordWrittenNowFailsTheV100Decoder` (`core/authority/workspace_restart_grace_test.go`); `TestAuthorityStoreWritesTheV100Files`, `TestAuthorityStoreReadsTheV100Files` (`core/authority/golden_v100_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | | `INV-LIFECYCLE-STORE-DURABLE-001` | Node registration, volume record and placement-intent puts/replacements are atomic and durable: after a crash the record file is the complete old or the complete new record; a put that returned nil has fsynced the file and its directory. | M2 lifecycle record publication | `core/lifecycle/record_file.go` `writeRecordDurably`; `node_inventory.go`, `store.go`, `placement_intent.go` `putLocked` | `TestNodeInventoryCrashKeepsCompleteRegistration` (`core/lifecycle/node_inventory_crash_test.go`); `TestFileStoreCrashKeepsCompleteRecord`, `TestPlacementStoreCrashKeepsCompleteRecord`, `TestLifecyclePutSyncOrderAndFailure` (`core/lifecycle/store_crash_test.go`); `TestLifecycleStoreParentSync` (`core/lifecycle/store_parent_sync_test.go`) | � | ACTIVE | | `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/layout/create.go` `createVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCreateVolume_OverAnExistingHeadByState` (`core/frontend/chunkstore/layout/create_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | From ac02f34d816be3800e0ce420a299f8d6b1bd17a4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:21:37 -0800 Subject: [PATCH 33/51] master: the attestation envelope is re-synced at every start; volumes must be an object An envelope already on disk is fsynced (file and directory) at every start before the master serves: an earlier start may have renamed it in and failed its directory fsync. master.New releases the store lock when the envelope cannot be made durable or the attestations cannot be read. A format-2 file without an explicit volumes object (missing, null, wrong type) is refused rather than read as no attestations; v1.0.x files with volumes named format or volumes are still read as bare maps. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/golden_v100_test.go | 105 ++++++++++++++++++ seaweed-block/core/host/master/host.go | 2 + .../core/host/master/store_attestation.go | 71 ++++++++---- 3 files changed, 155 insertions(+), 23 deletions(-) diff --git a/seaweed-block/core/host/master/golden_v100_test.go b/seaweed-block/core/host/master/golden_v100_test.go index f37cfa8ec3..0065c5369f 100644 --- a/seaweed-block/core/host/master/golden_v100_test.go +++ b/seaweed-block/core/host/master/golden_v100_test.go @@ -5,10 +5,12 @@ import ( "crypto/sha1" "encoding/hex" "encoding/json" + "errors" "fmt" "os" "path/filepath" "reflect" + "strings" "testing" "github.com/seaweedfs/seaweed-block/core/storage" @@ -214,3 +216,106 @@ func TestAttestationReadCheckSeesLostState(t *testing.T) { }) } } + +// The envelope's volumes are an explicit object: a missing or null one is +// refused (never read as no attestations), {} is no volumes. A v1.0.x file +// whose volumes are named "format" or "volumes" is still read as the bare +// map it is. +func TestAttestationEnvelopeNeedsItsVolumesObject(t *testing.T) { + load := func(body string) (*storeAttestations, error) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return loadStoreAttestations(dir) + } + for _, body := range []string{`{"format":2}`, `{"format":2,"volumes":null}`, `{"format":2, "volumes" : null }`, `{"format":2,"volumes":[]}`, `{"format":2,"volumes":"x"}`} { + if _, err := load(body); err == nil { + t.Errorf("%s was read (as no attestations)", body) + } + } + if s, err := load(`{"format":2,"volumes":{}}`); err != nil || len(s.vols) != 0 || !s.enveloped { + t.Errorf("an empty volumes object: %v %+v", err, s) + } + s, err := load(`{"format":{"primary":"r1","epoch":2,"stores":{}},"volumes":{"primary":"r2","epoch":3,"stores":{}}}`) + if err != nil || s.enveloped || s.vols["format"].Primary != "r1" || s.vols["volumes"].Primary != "r2" { + t.Errorf("a v1.0.x file with volumes named format and volumes: %v %+v", err, s) + } +} + +// An envelope already on disk is fsynced again (file and directory) on every +// start: a start that renamed it in and then failed its directory fsync must +// not leave the next start serving on an envelope that may not survive a +// crash. +func TestAttestationEnvelopeIsSyncedAtEveryStart(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), readGoldenAttestations(t), 0o644); err != nil { + t.Fatal(err) + } + saved := syncAttestationDir + t.Cleanup(func() { syncAttestationDir = saved }) + syncs := 0 + syncAttestationDir = func(string) error { syncs++; return errors.New("injected directory fsync failure") } + s, err := loadStoreAttestations(dir) + if err != nil { + t.Fatal(err) + } + if err := s.ensureEnvelope(); err == nil { + t.Fatal("a failed directory fsync of the first envelope write was not an error (the master would serve)") + } + // The process restarts: the envelope is on disk (the rename happened). + s, err = loadStoreAttestations(dir) + if err != nil || !s.enveloped { + t.Fatalf("restart: %v enveloped=%v", err, s != nil && s.enveloped) + } + syncs = 0 + if err := s.ensureEnvelope(); err == nil || syncs != 1 { + t.Fatalf("restart with the directory fsync still failing: err=%v, %d directory fsyncs (want an error after one)", err, syncs) + } + syncAttestationDir = func(string) error { syncs++; return nil } + syncs = 0 + if err := s.ensureEnvelope(); err != nil || syncs != 1 { + t.Fatalf("restart: err=%v, %d directory fsyncs, want one before serving", err, syncs) + } +} + +// The envelope round-trips: loading a written envelope and writing it again +// gives the same bytes. +func TestAttestationEnvelopeRoundTrips(t *testing.T) { + dir := t.TempDir() + goldenAttestations(t, dir) + first, err := os.ReadFile(filepath.Join(dir, storeAttestationFile)) + if err != nil { + t.Fatal(err) + } + s, err := loadStoreAttestations(dir) + if err != nil { + t.Fatal(err) + } + s.mu.Lock() + err = s.persist(s.vols) + s.mu.Unlock() + if err != nil { + t.Fatal(err) + } + again, err := os.ReadFile(filepath.Join(dir, storeAttestationFile)) + if err != nil || !bytes.Equal(first, again) { + t.Fatalf("round trip changed the envelope (%v): %s / %s", err, first, again) + } +} + +// master.New refuses to serve when the attestation envelope cannot be made +// durable: it returns the error before it listens. +func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) { + saved := syncAttestationDir + t.Cleanup(func() { syncAttestationDir = saved }) + syncAttestationDir = func(string) error { return errors.New("injected directory fsync failure") } + h, err := New(Config{AuthorityStoreDir: t.TempDir(), Listen: "127.0.0.1:0"}) + if err == nil { + closeTestMaster(t, h) + t.Fatal("master.New served with a failed attestation envelope fsync") + } + if !strings.Contains(err.Error(), "injected directory fsync failure") { + t.Fatalf("master.New failed for another reason: %v", err) + } +} diff --git a/seaweed-block/core/host/master/host.go b/seaweed-block/core/host/master/host.go index 802c61cdcf..37f557518f 100644 --- a/seaweed-block/core/host/master/host.go +++ b/seaweed-block/core/host/master/host.go @@ -280,12 +280,14 @@ func New(cfg Config) (*Host, error) { // An unknown identity (stat error, unsupported platform) never matches. h.journal.setSelf(storeident.Of(cfg.AuthorityStoreDir)) if h.attest, err = loadStoreAttestations(cfg.AuthorityStoreDir); err != nil { + _ = boot.Close() // release the store lock: this master never serves return nil, fmt.Errorf("master.New: %w", err) } // Under the authority store's lock and before anything is served: the // attestation file in this version's envelope, which a v1.0.x master // refuses at start (store_attestation.go). if err := h.attest.ensureEnvelope(); err != nil { + _ = boot.Close() return nil, fmt.Errorf("master.New: %w", err) } diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index 90c24f2bde..becdc04022 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -1,6 +1,7 @@ package master import ( + "bytes" "encoding/hex" "encoding/json" "errors" @@ -109,13 +110,15 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error) if format != storeAttestationFormat { return nil, false, fmt.Errorf("format %d, this master reads format %d", format, storeAttestationFormat) } + // The volumes are an explicit object ({} when there are none): a + // missing or null one is refused, never read as no attestations. + if v, ok := probe["volumes"]; !ok || string(bytes.TrimSpace(v)) == "null" { + return nil, false, fmt.Errorf("format %d without a volumes object", format) + } var env storeAttestationEnvelope if err := json.Unmarshal(b, &env); err != nil { return nil, false, err } - if env.Volumes == nil { - env.Volumes = map[string]attestedStores{} - } return env.Volumes, true, nil } } @@ -126,20 +129,53 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error) return vols, false, nil } -// ensureEnvelope writes the file in this version's envelope, durably, when -// it is absent or in v1.0.x's form: the master calls it before it serves -// anything, so a v1.0.x master started on this store afterwards refuses its -// whole start. +// ensureEnvelope makes the file in this version's envelope durable before +// the master serves anything, so a v1.0.x master started on this store +// afterwards refuses its whole start: it writes the envelope when the file is +// absent or in v1.0.x's form, and fsyncs an envelope already there (file and +// directory) on every start, since an earlier start may have renamed it in +// and then failed its directory fsync. func (s *storeAttestations) ensureEnvelope() error { s.mu.Lock() defer s.mu.Unlock() - if s.path == "" || s.enveloped { + if s.path == "" { return nil } - if err := s.persist(s.vols); err != nil { - return err + if !s.enveloped { + if err := s.persist(s.vols); err != nil { + return err + } + s.enveloped = true + return nil + } + f, err := os.OpenFile(s.path, os.O_RDWR, 0) + if err != nil { + return fmt.Errorf("store attestations: %w", err) + } + serr := f.Sync() + if cerr := f.Close(); serr == nil { + serr = cerr + } + if serr != nil { + return fmt.Errorf("store attestations: fsync: %w", serr) + } + return syncAttestationDir(filepath.Dir(s.path)) +} + +// syncAttestationDir fsyncs the attestation file's directory (the commit of +// its rename). A variable so a test can fail it. +var syncAttestationDir = func(dir string) error { + if runtime.GOOS == "windows" { + return nil // a directory cannot be fsynced there; the rename is the commit + } + d, err := os.Open(dir) + if err != nil { + return fmt.Errorf("store attestations: directory: %w", err) + } + defer d.Close() + if err := d.Sync(); err != nil { + return fmt.Errorf("store attestations: directory fsync: %w", err) } - s.enveloped = true return nil } @@ -419,18 +455,7 @@ func (s *storeAttestations) persist(vols map[string]attestedStores) error { _ = os.Remove(temp) return fmt.Errorf("store attestations: %w", werr) } - if runtime.GOOS == "windows" { - return nil // a directory cannot be fsynced there; the rename is the commit - } - d, err := os.Open(filepath.Dir(s.path)) - if err != nil { - return fmt.Errorf("store attestations: directory: %w", err) - } - defer d.Close() - if err := d.Sync(); err != nil { - return fmt.Errorf("store attestations: directory fsync: %w", err) - } - return nil + return syncAttestationDir(filepath.Dir(s.path)) } // ingestStoreAttestation records a heartbeat's attestation when the From 43efa2c82a972d3d5e18780504a69cb81913564b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:22:43 -0800 Subject: [PATCH 34/51] storage: refuse a newer store format with a typed error and change nothing A store whose descriptor slots are intact but name a chunk-state format newer than this binary reads is refused with ErrStoreFormatNewer, told apart before the slot's byte checks, instead of "neither descriptor slot is valid"; a half-fence still opens on the known slot. Cut COW side files are discarded only after a slot is selected, so a refused open leaves the directory as it was. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/superblock_v3.go | 15 +++ .../superblock_v3_format_newer_test.go | 116 ++++++++++++++++++ seaweed-block/core/storage/walstore_v3.go | 12 +- 3 files changed, 139 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/core/storage/superblock_v3_format_newer_test.go diff --git a/seaweed-block/core/storage/superblock_v3.go b/seaweed-block/core/storage/superblock_v3.go index 29500e5e27..66e418ba71 100644 --- a/seaweed-block/core/storage/superblock_v3.go +++ b/seaweed-block/core/storage/superblock_v3.go @@ -65,6 +65,10 @@ var ( // ErrMigrationIncomplete: no selectable slot exists but a prepared // migration slot does (DESIGN 2.3, 10.1). The volume must not serve. ErrMigrationIncomplete = errors.New("storage: v3 migration not committed (only a prepared descriptor slot exists)") + // ErrStoreFormatNewer: an intact descriptor slot names a store format + // newer than this binary knows (its chunk-state format). The store is + // refused as written by a newer version, never read or changed. + ErrStoreFormatNewer = errors.New("storage: store written by a newer format: use a newer binary") // ErrCounterExhausted: a persisted counter would exceed 2^64-2 // (DESIGN 2.4). Nothing is written. ErrCounterExhausted = errors.New("storage: v3 counter exhausted") @@ -127,6 +131,9 @@ const ( var crc32cTable = crc32.MakeTable(crc32.Castagnoli) +// chunkStateFormatKnownV3 is the newest chunk-state format this binary reads. +const chunkStateFormatKnownV3 = 1 + // reservedRangesV3 are the [start, end) byte ranges that must be zero. var reservedRangesV3 = [][2]int{ {9, 12}, {122, 128}, {164, 168}, {240, 256}, {273, 280}, {308, 312}, {320, slotCRCOffsetV3}, @@ -212,6 +219,11 @@ func decodeSlotV3(b []byte, accept slotImplAcceptor) (descriptorV3, error) { if f := le.Uint16(b[6:]); f != 0 { return descriptorV3{}, fmt.Errorf("%w: slot flags %#x", errSuperblockInvalid, f) } + // A newer store format is told apart before any check of its bytes: an + // intact slot of a newer version is not an invalid one. + if f := le.Uint16(b[306:]); f > chunkStateFormatKnownV3 { + return descriptorV3{}, fmt.Errorf("%w: chunk-state format %d, this binary knows %d", ErrStoreFormatNewer, f, chunkStateFormatKnownV3) + } for _, r := range reservedRangesV3 { if i := firstNonZero(b[r[0]:r[1]]); i >= 0 { return descriptorV3{}, fmt.Errorf("%w: reserved byte %d is nonzero", errSuperblockInvalid, r[0]+i) @@ -430,6 +442,9 @@ func selectSlotV3(a, b []byte, accept slotImplAcceptor) (descriptorV3, slotIDV3, da, errA := decodeSlotV3(a, accept) db, errB := decodeSlotV3(b, accept) if errA != nil && errB != nil { + if errors.Is(errA, ErrStoreFormatNewer) || errors.Is(errB, ErrStoreFormatNewer) { + return descriptorV3{}, 0, fmt.Errorf("%w (A: %v; B: %v)", ErrStoreFormatNewer, errA, errB) + } return descriptorV3{}, 0, fmt.Errorf("%w: neither descriptor slot is valid (A: %v; B: %v)", errSuperblockInvalid, errA, errB) } diff --git a/seaweed-block/core/storage/superblock_v3_format_newer_test.go b/seaweed-block/core/storage/superblock_v3_format_newer_test.go new file mode 100644 index 0000000000..408f1a9e01 --- /dev/null +++ b/seaweed-block/core/storage/superblock_v3_format_newer_test.go @@ -0,0 +1,116 @@ +package storage + +import ( + "crypto/sha256" + "errors" + "os" + "path/filepath" + "testing" +) + +// formatNewerStore is a closed store whose descriptor slots are rewritten by +// mutate (each decoded, changed, and re-sealed with its CRC), plus a planted +// cut COW side file. +func formatNewerStore(t *testing.T, mutate func(slot int, d *descriptorV3)) (path, side string) { + t.Helper() + path = filepath.Join(t.TempDir(), "volume") + s, err := CreateWALStoreWithOptions(path, 64, 4096, WALStoreOptions{ChunkBlocks: 4}) + if err != nil { + t.Fatal(err) + } + if err := s.Close(); err != nil { + t.Fatal(err) + } + f, err := os.OpenFile(path, os.O_RDWR, 0o644) + if err != nil { + t.Fatal(err) + } + for i, off := range []int64{slotAOffsetV3, slotBOffsetV3} { + raw := make([]byte, slotSizeV3) + if _, err := f.ReadAt(raw, off); err != nil { + t.Fatal(err) + } + d, err := decodeSlotV3(raw, nil) + if err != nil { + t.Fatalf("setup: slot %d: %v", i, err) + } + mutate(i, &d) + if _, err := f.WriteAt(d.encode(), off); err != nil { + t.Fatal(err) + } + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + side = path + ".cut-cow-planted" + if err := os.WriteFile(side, []byte("side"), 0o600); err != nil { + t.Fatal(err) + } + return path, side +} + +func fileSum(t *testing.T, path string) [32]byte { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return sha256.Sum256(b) +} + +// A store written by a newer format (its descriptor slots intact, sealed, +// naming a chunk-state format this binary does not know) is refused with the +// typed ErrStoreFormatNewer, not reported as an invalid slot, and the open +// changes nothing: the file's bytes and the directory's cut COW side files +// stay as they were. A half-fence (one slot newer, the other at a known +// format) opens on the known slot, as before; a slot invalid otherwise is +// still invalid, not newer. +func TestANewerStoreFormatIsRefusedTypedAndUntouched(t *testing.T) { + t.Run("both slots newer", func(t *testing.T) { + path, side := formatNewerStore(t, func(_ int, d *descriptorV3) { + d.ChunkStateFormat, d.LocalWorkEpoch = 2, 1 + }) + before := fileSum(t, path) + s, err := OpenWALStore(path) + if err == nil { + _ = s.Close() + } + if !errors.Is(err, ErrStoreFormatNewer) { + t.Fatalf("open of a newer-format store: %v, want ErrStoreFormatNewer", err) + } + if fileSum(t, path) != before { + t.Fatal("the refused open changed the store's bytes") + } + if _, err := os.Stat(side); err != nil { + t.Fatalf("the refused open removed a cut COW side file: %v", err) + } + }) + t.Run("half-fence opens on the known slot", func(t *testing.T) { + path, _ := formatNewerStore(t, func(slot int, d *descriptorV3) { + if slot == 0 { + d.ChunkStateFormat, d.LocalWorkEpoch = 2, 1 + } + }) + s, err := OpenWALStore(path) + if err != nil { + t.Fatalf("open with one slot newer and one known: %v", err) + } + _ = s.Close() + }) + t.Run("control: an invalid slot is not newer", func(t *testing.T) { + path, side := formatNewerStore(t, func(_ int, d *descriptorV3) { + d.ChunkStateFormat, d.LocalWorkEpoch = 0, 5 // epoch without a format: invalid + }) + s, err := OpenWALStore(path) + if err == nil { + _ = s.Close() + t.Fatal("an invalid descriptor opened") + } + if errors.Is(err, ErrStoreFormatNewer) { + t.Fatalf("an invalid descriptor reported as a newer format: %v", err) + } + if _, err := os.Stat(side); err != nil { + t.Fatalf("a refused open removed a cut COW side file: %v", err) + } + }) +} diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 2e3473ad35..67edc7f070 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -347,10 +347,6 @@ func openWALStoreV3WithOptions(path string, requireMap bool, opts WALStoreOption _ = f.Close() return nil, err } - if err := discardCutCOWFiles(path); err != nil { - _ = f.Close() - return nil, err - } return openWALStoreV3File(path, f, requireMap, opts, nil, false) } @@ -376,6 +372,14 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO _ = f.Close() return nil, err } + // Side files are discarded only by an open that selected a slot: a store + // it refuses (a newer format, an invalid descriptor) is left as it was. + if !creating { + if err := discardCutCOWFiles(path); err != nil { + _ = f.Close() + return nil, err + } + } var other *descriptorV3 otherRaw := b if id == slotB { From 9f823870477a73a2809069392ad659f29e975436 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:23:58 -0800 Subject: [PATCH 35/51] master: the line-wake test publishes by the product tick it runs itself The controller never bound a once-reported static volume on Linux, so the test now creates and places a volume through the lifecycle, ingests its holder's heartbeat, settles the observation host (started == done, no buffered wake, no timer due), runs the product tick (the master runs none by itself), which binds the volume, and requires a build after that point: only the line-change hook can take it. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/line_change_wake_test.go | 133 ++++++++---------- 1 file changed, 58 insertions(+), 75 deletions(-) diff --git a/seaweed-block/core/host/master/line_change_wake_test.go b/seaweed-block/core/host/master/line_change_wake_test.go index 44fbc9c9f4..fb79d0c2b1 100644 --- a/seaweed-block/core/host/master/line_change_wake_test.go +++ b/seaweed-block/core/host/master/line_change_wake_test.go @@ -1,47 +1,61 @@ package master import ( + "context" "runtime" "testing" "time" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/lifecycle" ) // A published line wakes the observation build, through the master's -// wiring of the publisher's line-change hook. The order is made -// deterministic so no other wake can stand in for the hook: -// - the master starts with nothing ingested; its initial build runs, and -// the 1 ms pending grace's deadline is consumed (its rebuild runs too); -// - after the builds drain, one heartbeat is ingested: its single wake is -// consumed by one build whose snapshot already holds it (the snapshot is -// taken after the wake is received), showing v1 supported and unbound; -// - the controller binds v1 after that build. No heartbeat follows, no -// expiry is due (a one-hour window), and there is no GC tick: a later -// build carrying the line can only come from the hook. +// wiring of the publisher's line-change hook. The publication is the +// product tick's bind of a created and placed volume, run by the test (the +// master runs no tick by itself), and the order leaves nothing else to wake +// the build: +// - the master starts; its initial build (#1) and the 1 ms grace's +// rebuild (#2) finish; the volume is created and placed and its holder's +// heartbeat ingested; the observation host settles (every build taken +// has finished, no wake is buffered, no deadline is due within the test: +// a one-hour freshness window, no GC tick), all read under its lock: N +// builds done; +// - the test runs the product tick, which binds the volume; +// - a build N+1 must follow: nothing but the hook can take it. func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("the lifecycle stores need directory fsync") } h, err := New(Config{ - AuthorityStoreDir: t.TempDir(), - LifecycleStoreDir: t.TempDir(), - Listen: "127.0.0.1:0", - Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, - Topology: authority.AcceptedTopology{Volumes: []authority.VolumeExpected{{ - VolumeID: "v1", - Slots: []authority.ExpectedSlot{{ReplicaID: "r1", ServerID: "node-a"}}, - }}}, + Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), + WorkspaceRPC: true, LifecycleProductLoop: true, LayoutCreateVolume: testLayoutCreateVolume, + WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) { + return authority.WorkspaceHead{}, nil + }, + Freshness: authority.FreshnessConfig{FreshnessWindow: time.Hour, PendingGrace: time.Millisecond}, }) if err != nil { t.Fatal(err) } h.Start() - defer closeTestMaster(t, h) - // settle waits until every build the loop took has finished, no wake is - // buffered and no deadline timer fires within the test (the one-hour - // expiry timer stays armed), all read under the host's lock; it returns - // the builds done. + t.Cleanup(func() { closeTestMaster(t, h) }) + c, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + t.Cleanup(cancel) + if _, err := h.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: "node-a", DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + // settle waits, under the host's lock, until every build taken has + // finished, no wake is buffered and no deadline timer fires within a + // minute, with at least atLeast builds done; it returns the builds done. settle := func(what string, atLeast uint64) uint64 { t.Helper() deadline := time.Now().Add(5 * time.Second) @@ -55,59 +69,28 @@ func TestMasterRebuildsObservationOnAPublishedLine(t *testing.T) { t.Fatalf("%s: the observation host did not settle", what) return 0 } - waitDone := func(what string, n uint64, ok func(authority.BuildResult) bool) { - t.Helper() - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - _, done, _, _ := h.obs.BuildsForTest() - if b, have := h.obs.LastBuild(); have && done >= n && ok(b) { - return - } - time.Sleep(10 * time.Millisecond) - } - b, _ := h.obs.LastBuild() - t.Fatalf("%s: no build #%d satisfied it; last build %+v", what, n, b.Snapshot.Volumes) - } - carriesLine := func(epoch uint64) func(authority.BuildResult) bool { - return func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" && v.Authority.Assigned && v.Authority.Epoch == epoch { - return true - } - } - return false - } - } - // The initial build (#1) and the 1 ms grace's rebuild (#2, with nothing - // ingested yet) both finished: the grace's deadline is consumed, so no - // timer can arm after this point and see the heartbeat. - n := settle("startup", 2) - if err := h.obs.IngestHeartbeat(authority.HeartbeatMessage{ - ServerID: "node-a", SentAt: time.Now().UTC(), Reachable: true, Eligible: true, - Slots: []authority.HeartbeatSlot{{VolumeID: "v1", ReplicaID: "r1", DataAddr: "127.0.0.1:9201", CtrlAddr: "127.0.0.1:9101", Reachable: true, ReadyForPrimary: true, Eligible: true}}, - }); err != nil { + settle("startup", 2) + reviewCreate(t, c, ctx, "v1") + if _, err := h.Lifecycle().Placements.ApplyPlan(lifecycle.PlacementPlan{VolumeID: "v1", DesiredRF: 1, Candidates: []lifecycle.PlacementCandidate{{VolumeID: "v1", ServerID: "node-a", ReplicaID: "r1", Source: lifecycle.PlacementSourceExistingReplica}}}); err != nil { t.Fatal(err) } - // The heartbeat's one build (#n+1) shows v1 supported and unbound: the - // controller binds only after it. - waitDone("the heartbeat's build", n+1, func(b authority.BuildResult) bool { - for _, v := range b.Snapshot.Volumes { - if v.VolumeID == "v1" { - return true - } - } - return false - }) - for wait := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { - if line, ok := h.Publisher().VolumeAuthorityLine("v1"); ok && line.Assigned { - break - } - if time.Now().After(wait) { - t.Fatal("the controller did not bind v1") - } + reviewHeartbeat(t, c, ctx, "v1", "node-a", "127.0.0.1:10000", "127.0.0.1:10001") + n := settle("after the heartbeat", 3) + if _, ok := h.Publisher().VolumeAuthorityLine("v1"); ok { + t.Fatal("v1 was bound before the product tick: the publication under test is not the test's") } - line, _ := h.Publisher().VolumeAuthorityLine("v1") - // Every build after the heartbeat's was taken after the publication (no - // other wake was left): the hook's. One must come and carry the line. - waitDone("the hook's build", n+2, carriesLine(line.Epoch)) + if _, err := h.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + if line := waitAuthorityLine(t, h.Publisher(), "v1"); line.Epoch != 1 { + t.Fatalf("the product tick bound %+v", line) + } + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if _, done, _, _ := h.obs.BuildsForTest(); done > n { + return + } + time.Sleep(10 * time.Millisecond) + } + t.Fatalf("no observation build followed the publication (still %d builds): the line-change hook did not wake it", n) } From ddc349abe82085ed083e6d34a8e81f615b49934e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:25:54 -0800 Subject: [PATCH 36/51] master: refuse a nil decoded volumes map; a null v1.0.x attestation file migrates as {} The envelope's volumes are checked on the decoded map (a later key of another case can null it after a key probe), and a v1.0.x file that is null is read as no attestations, as v1.0.x read it, so its envelope says {} and the next start reads it. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/golden_v100_test.go | 25 ++++++++++++++++++- .../core/host/master/store_attestation.go | 19 ++++++++------ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/seaweed-block/core/host/master/golden_v100_test.go b/seaweed-block/core/host/master/golden_v100_test.go index 0065c5369f..a85a40f5a4 100644 --- a/seaweed-block/core/host/master/golden_v100_test.go +++ b/seaweed-block/core/host/master/golden_v100_test.go @@ -229,7 +229,7 @@ func TestAttestationEnvelopeNeedsItsVolumesObject(t *testing.T) { } return loadStoreAttestations(dir) } - for _, body := range []string{`{"format":2}`, `{"format":2,"volumes":null}`, `{"format":2, "volumes" : null }`, `{"format":2,"volumes":[]}`, `{"format":2,"volumes":"x"}`} { + for _, body := range []string{`{"format":2}`, `{"format":2,"volumes":null}`, `{"format":2, "volumes" : null }`, `{"format":2,"volumes":[]}`, `{"format":2,"volumes":"x"}`, `{"format":2,"volumes":{},"Volumes":null}`} { if _, err := load(body); err == nil { t.Errorf("%s was read (as no attestations)", body) } @@ -319,3 +319,26 @@ func TestMasterNewRefusesWhenTheEnvelopeIsNotDurable(t *testing.T) { t.Fatalf("master.New failed for another reason: %v", err) } } + +// A v1.0.x file that is null holds no attestations (as v1.0.x read it): it +// migrates to an envelope with an explicit {} that the next start reads. +func TestAV100NullAttestationFileMigrates(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, storeAttestationFile), []byte("null"), 0o644); err != nil { + t.Fatal(err) + } + s, err := loadStoreAttestations(dir) + if err != nil || len(s.vols) != 0 { + t.Fatalf("a null v1.0.x file: %v %+v", err, s) + } + if err := s.ensureEnvelope(); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(filepath.Join(dir, storeAttestationFile)) + if err != nil || string(b) != `{"format":2,"volumes":{}}` { + t.Fatalf("migrated to %s (%v)", b, err) + } + if _, err := loadStoreAttestations(dir); err != nil { + t.Fatalf("the next start refuses the migrated file: %v", err) + } +} diff --git a/seaweed-block/core/host/master/store_attestation.go b/seaweed-block/core/host/master/store_attestation.go index becdc04022..7e8e9b09b3 100644 --- a/seaweed-block/core/host/master/store_attestation.go +++ b/seaweed-block/core/host/master/store_attestation.go @@ -1,7 +1,6 @@ package master import ( - "bytes" "encoding/hex" "encoding/json" "errors" @@ -110,22 +109,28 @@ func decodeStoreAttestations(b []byte) (map[string]attestedStores, bool, error) if format != storeAttestationFormat { return nil, false, fmt.Errorf("format %d, this master reads format %d", format, storeAttestationFormat) } - // The volumes are an explicit object ({} when there are none): a - // missing or null one is refused, never read as no attestations. - if v, ok := probe["volumes"]; !ok || string(bytes.TrimSpace(v)) == "null" { - return nil, false, fmt.Errorf("format %d without a volumes object", format) - } var env storeAttestationEnvelope if err := json.Unmarshal(b, &env); err != nil { return nil, false, err } + // The volumes are an explicit object ({} when there are none): + // whatever left the decoded map nil (missing, null, a later key of + // another case) is refused, never read as no attestations. + if env.Volumes == nil { + return nil, false, fmt.Errorf("format %d without a volumes object", format) + } return env.Volumes, true, nil } } - vols := map[string]attestedStores{} + var vols map[string]attestedStores if err := json.Unmarshal(b, &vols); err != nil { return nil, false, err } + if vols == nil { + // v1.0.x read a null file as no attestations; so does this master, + // and the envelope it migrates to says {} explicitly. + vols = map[string]attestedStores{} + } return vols, false, nil } From 2153edfedbd202c16bf9271988d642d5f8a73477 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:43:15 -0800 Subject: [PATCH 37/51] storage: a v1.1 detach cancel is a commit by change with no change On the v1.1 format a detach settlement whose detach did not land cancels it with a commit by change carrying no change at the detach's base: HEAD keeps the base's chunks and returns to this holder's active identity, and no whole base image is built from the ref table. A cancel that lands is installed in place; one whose reply is lost after it applied is read back and adopted, as before. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 22 +++++- .../core/storage/chunk_v11_outcomes_test.go | 75 +++++++++++++++++++ 2 files changed, 94 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 4cefc76529..08a2714ae9 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1717,11 +1717,13 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.stMu.Lock() fenced, pending, isDetach, base := l.fenced, l.pending, l.pendingDetach, l.pendingBase changes, marked := l.pendingChanges, l.pendingMarked - baseHead := l.wholeHeadLocked() + baseHead := l.cutBaseLocked(nil) // the cancel's base: identity only on the v1.1 format, whole before l.stMu.Unlock() if fenced { return detachFenced, chunkCutResult{}, nil } + // cancelled: this settlement's cancel CAS landed; cur is that cancel. + cancelled := false if pending == nil || !isDetach { // Nothing of this detach can land: it failed before its CAS or was // definitely refused (an unresolved ordinary cut settles as usual). @@ -1738,13 +1740,21 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle cancel := copyHead(baseHead) cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder cancel.State, cancel.DetachedBy = chunkHeadActive, nil - if err := l.checkCommitFirst(ctx, base, cancel); err != nil { + // On the v1.1 format the cancel is a commit by change with no + // change: the base's chunks stay as HEAD has them; only the identity + // and the state move (nil changes: the whole base image, before). + var none map[uint64]*chunkRef + if changes != nil { + none = map[uint64]*chunkRef{} + } + if err := l.checkCommitFirstBy(ctx, base, proposalOf(cancel, none), none); err != nil { return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel check failed: %w", errChunkCASOutcomeUnknown, err) } - gen, casErr := casAndConfirmChunkHead(ctx, l.remote, base, cancel) + gen, casErr := casAndConfirmChunkHeadBy(ctx, l.remote, base, proposalOf(cancel, none), none, nil) if casErr == nil { cancel.Gen = gen cur = cancel + cancelled = none != nil } else if errors.Is(casErr, errChunkLayerFenced) { l.fencePublication(chunkHead{}) return detachFenced, chunkCutResult{}, nil @@ -1782,6 +1792,12 @@ func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (settled detachSettle l.fenced = true l.setHeadLocked(copyHead(cur)) return detachFenced, chunkCutResult{}, nil + case cancelled: + // The cancel by change landed: HEAD is the base's chunks at this + // holder's identity, active. Installed in place (identity only); its + // chunks are the table's already. + l.applyCommitLocked(cur, nil) + return detachNotPublished, chunkCutResult{}, nil default: if l.adoptHeadLocked(cur) != nil { return detachFenced, chunkCutResult{}, nil diff --git a/seaweed-block/core/storage/chunk_v11_outcomes_test.go b/seaweed-block/core/storage/chunk_v11_outcomes_test.go index c4e660e6f9..b87ebf5251 100644 --- a/seaweed-block/core/storage/chunk_v11_outcomes_test.go +++ b/seaweed-block/core/storage/chunk_v11_outcomes_test.go @@ -201,3 +201,78 @@ func TestV11NoOpCutFencesAForeignRootAtItsOwnIdentity(t *testing.T) { } }) } + +// unresolvedV11Detach is a v1.1 layer with chunk 0 published and a detach +// (writing chunk 2) whose CAS by change was lost before it applied: HEAD +// is still the detach's base, and the outcome is unresolved. +func unresolvedV11Detach(t *testing.T) (*chunkLayerImpl, *deltaSpyRemote, chunkHead) { + t.Helper() + withV11Format(t) + s, l, spy := deltaSpyLayer(t) + w := newWriteLog() + w.write(t, s, 0, 0x10) + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + base, err := spy.GetHead(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + w.write(t, s, 2*ctChunkBlocks, 0x22) + spy.mu.Lock() + spy.lose = true + spy.mu.Unlock() + if _, err := l.Detach(ctTimeout(t)); !errors.Is(err, errChunkCASOutcomeUnknown) { + t.Fatalf("detach with a lost CAS: %v, want an unresolved outcome", err) + } + return l, spy, base +} + +// On the v1.1 format a detach settlement whose detach did not land cancels +// it with a commit by change carrying no change, at the detach's base: HEAD +// keeps the base's chunks and returns to this holder's active identity. A +// cancel that lands is installed in place (the layer stays unfenced and its +// table is the remote's HEAD); a cancel whose reply is lost after it applied +// is read back and adopted, as before. +func TestV11DetachCancelGoesByChangeAndInstallsInPlace(t *testing.T) { + settleAndCheck := func(t *testing.T, l *chunkLayerImpl, spy *deltaSpyRemote, base chunkHead) { + t.Helper() + settled, _, err := l.SettleDetach(ctTimeout(t)) + if err != nil || settled != detachNotPublished { + t.Fatalf("SettleDetach: %v %v, want the detach cancelled (not published)", settled, err) + } + spy.mu.Lock() + last, full := spy.deltas[len(spy.deltas)-1], spy.fullCAS + spy.mu.Unlock() + if len(last) != 0 || full != 0 { + t.Fatalf("the cancel carried %d changes and %d whole-image CASes; want one commit by change with none", len(last), full) + } + head, err := spy.GetHead(ctTimeout(t)) + if err != nil { + t.Fatal(err) + } + if head.Gen != base.Gen+1 || chunkHeadIsDetached(head) || head.Holder != base.Holder || !reflect.DeepEqual(head.Chunks, base.Chunks) { + t.Fatalf("HEAD after the cancel: gen %d detached %v holder %q, %d chunks; want gen %d active with the base's %d chunks", head.Gen, chunkHeadIsDetached(head), head.Holder, len(head.Chunks), base.Gen+1, len(base.Chunks)) + } + l.stMu.Lock() + fenced, whole := l.fenced, l.wholeHeadLocked() + l.stMu.Unlock() + if fenced { + t.Fatal("a cancelled detach fenced the layer") + } + if whole.Gen != head.Gen || !reflect.DeepEqual(whole.Chunks, head.Chunks) { + t.Fatalf("the layer's HEAD after the cancel is gen %d with %d chunks; the remote's gen %d with %d", whole.Gen, len(whole.Chunks), head.Gen, len(head.Chunks)) + } + } + t.Run("cancel lands", func(t *testing.T) { + l, spy, base := unresolvedV11Detach(t) + settleAndCheck(t, l, spy, base) + }) + t.Run("cancel reply lost after it applied", func(t *testing.T) { + l, spy, base := unresolvedV11Detach(t) + spy.fakeChunkRemote.mu.Lock() + spy.fakeChunkRemote.casModes = []fakeCASMode{casAppliedLost} + spy.fakeChunkRemote.mu.Unlock() + settleAndCheck(t, l, spy, base) + }) +} From 62ee69b0e2203c374471a52816c8df062cb8eba5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:24:05 -0800 Subject: [PATCH 38/51] hostlimit, storage, durable: red tests, a long cut yields its slot to a waiter Seams: Config.YieldAfter (S, default 5 min), Limiter.ShouldYield (never, for now), storage.ErrCutYielded, storage.BudgetYield, ChunkLayerStats. CutsYielded and CutScheduleStatus.CutYields. - TestShouldYieldOnlyAfterSWithALiveWaiter: a Normal hold yields only once it is S old and another process holds a live ticket; never a lone hold, never before S, never an urgent hold, not for a ticket judged stalled. Fails here: no hold ever yields. - TestCutYieldsAtABatchBoundaryAndKeepsItsStaging: a cut whose budget asks it to yield ends at the next staging batch boundary with ErrCutYielded, counted as a yield, not a failure, publishes nothing, and its staged chunks are kept for the next attempt. Fails here: the cut never yields. - TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart: a yielded attempt is retried at the next poll, never backed off as a failure, and status counts it apart. Fails here: the retry came 1.1 s later. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/cut_loop_yield_test.go | 77 +++++++++++++++++++ .../core/frontend/durable/provider.go | 1 + seaweed-block/core/hostlimit/limiter.go | 10 ++- seaweed-block/core/hostlimit/yield_test.go | 61 +++++++++++++++ .../core/storage/chunk_cut_budget.go | 14 +++- .../core/storage/chunk_cut_budget_test.go | 4 + .../core/storage/chunk_cut_yield_test.go | 39 ++++++++++ seaweed-block/core/storage/chunk_seam.go | 1 + 8 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/cut_loop_yield_test.go create mode 100644 seaweed-block/core/hostlimit/yield_test.go create mode 100644 seaweed-block/core/storage/chunk_cut_yield_test.go diff --git a/seaweed-block/core/frontend/durable/cut_loop_yield_test.go b/seaweed-block/core/frontend/durable/cut_loop_yield_test.go new file mode 100644 index 0000000000..42d397f1b4 --- /dev/null +++ b/seaweed-block/core/frontend/durable/cut_loop_yield_test.go @@ -0,0 +1,77 @@ +package durable + +import ( + "context" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// slotYieldingLayer admits each cut through the budget (consuming its ticket); +// its first two attempts yield their slot, every later one succeeds. It +// reports nothing staged, so nothing but the yield rule can excuse a backoff. +type slotYieldingLayer struct { + storage.ChunkLayer // unused methods panic + budget storage.Budget + cuts atomic.Int32 + mu sync.Mutex + at []time.Time +} + +func (l *slotYieldingLayer) Fenced() bool { return false } +func (l *slotYieldingLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} } +func (l *slotYieldingLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) { + l.mu.Lock() + l.at = append(l.at, time.Now()) + l.mu.Unlock() + n := l.cuts.Add(1) + id, err := l.budget.Admit(ctx, 1, nil) + if err != nil { + return storage.ChunkCutResult{}, err + } + l.budget.Release(id) + if n <= 2 { + return storage.ChunkCutResult{}, storage.ErrCutYielded + } + return storage.ChunkCutResult{}, nil +} + +// A yielded attempt is not a failure: no backoff, it tries again at the next +// poll (on a ticket at the back, as any admitted attempt that did not +// succeed), and status counts it apart. +func TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart(t *testing.T) { + b := newRecordingBudget(t) + layer := &slotYieldingLayer{budget: b} + wait := &cutWaitSlot{} + p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkBudget: b}} + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go p.chunkLoop(ctx, "v1", layer, done, wait, nil) + t.Cleanup(func() { + cancel() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("the cut loop did not end within 5 s of its cancel") + } + }) + for deadline := time.Now().Add(5 * time.Second); layer.cuts.Load() < 3; time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("the loop made %d attempts in 5 s, want 3", layer.cuts.Load()) + } + } + layer.mu.Lock() + at := append([]time.Time(nil), layer.at...) + layer.mu.Unlock() + for i := 1; i < 3; i++ { + if gap := at[i].Sub(at[i-1]); gap >= 500*time.Millisecond { + t.Fatalf("attempt %d came %s after a yield: a yield was backed off as a failure", i+1, gap.Round(time.Millisecond)) + } + } + if got := wait.status(0).CutYields; got != 2 { + t.Fatalf("status counts %d yields, want 2", got) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index ff4927c411..91b7d1c809 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -442,6 +442,7 @@ type CutScheduleStatus struct { TicketDueHostNs int64 `json:",omitempty"` // the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting TicketsSkipped uint64 `json:",omitempty"` // earlier tickets the waiting cut passed by the skip rule TicketDropReason string `json:",omitempty"` // why the last ticket was given up before admission, when it was a refusal that waiting cannot fix + CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (seam) } // NewDurableProvider constructs a provider. view is the ONLY diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 888482df4f..106149f3f2 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -66,13 +66,16 @@ type Config struct { // FetchSlots caps the chunk fetches in flight on the host, across its // processes (HoldFetch): a guest read waits for a slot, never refused. FetchSlots int + // YieldAfter is S: a Normal hold this old yields its slot at its next + // staging batch when another cut waits (seam). + YieldAfter time.Duration } func DefaultConfig(dir string) Config { - return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second, FetchSlots: 64} + return Config{Directory: dir, NormalSlots: 3, UrgentSlots: 1, FillSlots: 2, IdleSlots: 1, PayloadBytes: 64 << 20, COWBytes: 1 << 30, BytesPerSecond: 64 << 20, FallbackVolumes: 200, NoProgress: 60 * time.Second, FetchSlots: 64, YieldAfter: 5 * time.Minute} } func (c Config) Validate() error { - if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 || c.FetchSlots < 1 || c.FetchSlots > 1024 { + if !filepath.IsAbs(c.Directory) || c.NormalSlots < 1 || c.NormalSlots > 256 || c.UrgentSlots < 1 || c.UrgentSlots > 256 || c.FillSlots < 0 || c.FillSlots > 256 || c.IdleSlots < 0 || c.IdleSlots > 256 || c.NormalSlots+c.UrgentSlots+c.FillSlots+c.IdleSlots > 256 || c.PayloadBytes <= 0 || c.COWBytes <= 0 || c.BytesPerSecond <= 0 || c.FallbackVolumes < 1 || c.FallbackVolumes > 65536 || c.NoProgress <= 0 || c.FetchSlots < 1 || c.FetchSlots > 1024 || c.YieldAfter <= 0 { return errors.New("hostlimit: invalid configuration") } return nil @@ -500,6 +503,9 @@ func (l *Limiter) Progress(id uint64) { } } +// ShouldYield reports whether the hold id should yield its slot now (seam). +func (l *Limiter) ShouldYield(id uint64) bool { return false } + // expire runs when a hold's timer fires: a hold that progressed within its // window is armed again for the rest of it; one that did not is revoked. The // decision and the revocation are one step under the limiter's lock, reading diff --git a/seaweed-block/core/hostlimit/yield_test.go b/seaweed-block/core/hostlimit/yield_test.go new file mode 100644 index 0000000000..c30ec1e438 --- /dev/null +++ b/seaweed-block/core/hostlimit/yield_test.go @@ -0,0 +1,61 @@ +package hostlimit + +import ( + "context" + "path/filepath" + "testing" + "time" +) + +// A Normal hold yields only once it is S old AND another process waits (a +// live ticket in the pool): a lone hold never yields however old, a waiter +// before S changes nothing, an urgent hold never yields, and a ticket this +// process judged stalled is not a waiter. +func TestShouldYieldOnlyAfterSWithALiveWaiter(t *testing.T) { + c := testConfig(t) + c.NormalSlots = 2 + c.YieldAfter = 60 * time.Millisecond + l := newTest(t, c) + waiter := newTest(t, c) // another process on the host + x, err := l.Admit(context.Background(), 1, nil) + if err != nil { + t.Fatal(err) + } + defer l.Release(x) + if l.ShouldYield(x) { + t.Fatal("a fresh hold with no waiter yields") + } + tk, err := waiter.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + if l.ShouldYield(x) { + t.Fatal("a hold younger than S yields to a waiter") + } + time.Sleep(80 * time.Millisecond) + if !l.ShouldYield(x) { + t.Fatal("a hold older than S does not yield to a live waiter") + } + l.markStalled(filepath.Base(tk.path)) + if l.ShouldYield(x) { + t.Fatal("a ticket this process judged stalled counts as a waiter") + } + tk.Close() + if l.ShouldYield(x) { + t.Fatal("a hold older than S yields with no waiter") + } + tk2, err := waiter.TakeTicket(HostNow()) + if err != nil { + t.Fatal(err) + } + defer tk2.Close() + u, err := l.Acquire(context.Background(), Urgent, nil) + if err != nil { + t.Fatal(err) + } + defer l.Release(u) + time.Sleep(80 * time.Millisecond) + if l.ShouldYield(u) { + t.Fatal("an urgent hold yields") + } +} diff --git a/seaweed-block/core/storage/chunk_cut_budget.go b/seaweed-block/core/storage/chunk_cut_budget.go index e74f7071b6..5b3159f36d 100644 --- a/seaweed-block/core/storage/chunk_cut_budget.go +++ b/seaweed-block/core/storage/chunk_cut_budget.go @@ -1,6 +1,18 @@ package storage -import "context" +import ( + "context" + "errors" +) + +// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut +// (seam). +var ErrCutYielded = errors.New("storage: the cut yielded its host slot to a waiting cut") + +// BudgetYield is a Budget that asks a long hold to yield (seam). +type BudgetYield interface { + ShouldYield(ticket uint64) bool +} // Budget is the host limiter seam. Admit runs before staging or the cut // barrier and reserves the configured payload ceiling. ReserveCOW accounts diff --git a/seaweed-block/core/storage/chunk_cut_budget_test.go b/seaweed-block/core/storage/chunk_cut_budget_test.go index 16c4b424d5..a6e53357b5 100644 --- a/seaweed-block/core/storage/chunk_cut_budget_test.go +++ b/seaweed-block/core/storage/chunk_cut_budget_test.go @@ -17,8 +17,12 @@ type testCutBudget struct { abort func(error) probe func() progressed int + yield bool // ShouldYield's answer (BudgetYield) } +// ShouldYield answers yield (BudgetYield). +func (b *testCutBudget) ShouldYield(uint64) bool { b.mu.Lock(); defer b.mu.Unlock(); return b.yield } + // Progress counts the cut's progress reports (BudgetProgress). func (b *testCutBudget) Progress(uint64) { b.mu.Lock(); b.progressed++; b.mu.Unlock() } diff --git a/seaweed-block/core/storage/chunk_cut_yield_test.go b/seaweed-block/core/storage/chunk_cut_yield_test.go new file mode 100644 index 0000000000..b557303bca --- /dev/null +++ b/seaweed-block/core/storage/chunk_cut_yield_test.go @@ -0,0 +1,39 @@ +package storage + +import ( + "errors" + "testing" +) + +// A cut whose budget asks it to yield ends its attempt at the next staging +// batch boundary with ErrCutYielded: an outcome of its own (never a failed +// cut in status), it publishes nothing, and the chunks it staged are kept, +// so the next attempt stages only the rest. +func TestCutYieldsAtABatchBoundaryAndKeepsItsStaging(t *testing.T) { + _, l := zeroStagedLayer(t, 6) + b := &testCutBudget{yield: true} + l.cfg.Budget = b + before := l.Stats() + if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, ErrCutYielded) { + t.Fatalf("cut: %v; want it to yield at a staging batch boundary", err) + } + after := l.Stats() + if after.CutsYielded != before.CutsYielded+1 || after.CutsFailed != before.CutsFailed || after.LastCutFailure != nil { + t.Fatalf("a yield counted yielded %d->%d, failed %d->%d, failure %+v; want one yield and no failure", + before.CutsYielded, after.CutsYielded, before.CutsFailed, after.CutsFailed, after.LastCutFailure) + } + staged := after.StagedChunks - before.StagedChunks + if staged == 0 || after.CutSeq != before.CutSeq { + t.Fatalf("the yielding attempt staged %d chunks and moved the cut sequence %d->%d; want a staged batch and no publication", + staged, before.CutSeq, after.CutSeq) + } + b.mu.Lock() + b.yield = false + b.mu.Unlock() + if _, err := l.Cut(ctTimeout(t)); err != nil { + t.Fatal(err) + } + if again := l.Stats().StagedChunks - after.StagedChunks; again >= staged { + t.Fatalf("the retry staged %d chunks again after the yield staged %d; want the yielded attempt's chunks kept", again, staged) + } +} diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index f3b29d4e40..1fef53a31d 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -510,6 +510,7 @@ type chunkLayerStats struct { CutsNoop uint64 // cuts with nothing new (no CAS) CutsFailed uint64 // every other cut failure CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached + CutsYielded uint64 // attempts that gave their host slot to a waiting cut (seam) CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read From 49158029e72576621e8b71921c46a04dd4ae13cc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 11:32:41 -0800 Subject: [PATCH 39/51] hostlimit, storage, durable: a long cut yields its slot to a waiting cut - hostlimit: Config.YieldAfter (S, default 5 min). ShouldYield answers yes only for a Normal hold at least S old while another cut on the host holds a live ticket this process has not judged stalled (dead tickets are reaped on the way); the probe runs only once the hold is old enough and takes no limiter lock. - storage: a cut attempt asks at each staging batch boundary and ends with ErrCutYielded, keeping what it staged; CutsYielded counts it, never as a failed cut. - durable: a yielded attempt is retried at the next poll with no backoff, on a ticket at the back (it was admitted), counted in status (CutYields) and not logged as a failure. - blockvolume: --host-limit-yield-after. Invariants: INV-HOST-CUT-YIELD-001; M7 states the rule. v1.1 notes carry it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/host_limit.go | 1 + .../core/frontend/durable/provider.go | 2 +- .../core/frontend/durable/provider_chunk.go | 12 ++++- seaweed-block/core/hostlimit/limiter.go | 49 +++++++++++++++++-- .../core/storage/chunk_cut_budget.go | 17 +++++-- .../core/storage/chunk_cut_observation.go | 13 ++++- seaweed-block/core/storage/chunk_layer.go | 8 +++ seaweed-block/core/storage/chunk_seam.go | 2 +- seaweed-block/docs/design/invariants.md | 3 +- seaweed-block/docs/releases/v1.1.md | 3 ++ 10 files changed, 96 insertions(+), 14 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/host_limit.go b/seaweed-block/cmd/blockvolume/host_limit.go index b20da0de9a..2a0538da93 100644 --- a/seaweed-block/cmd/blockvolume/host_limit.go +++ b/seaweed-block/cmd/blockvolume/host_limit.go @@ -17,6 +17,7 @@ func registerHostLimitFlags(fs *flag.FlagSet, c *hostlimit.Config) { fs.Int64Var(&c.BytesPerSecond, "host-limit-upload-bytes-sec", c.BytesPerSecond, "pacing parameter divided per process by cut-slot count; not a host rate cap. --host-limit-no-progress must exceed one chunk's send time at this rate per held slot, or a steadily sending cut is revoked") fs.IntVar(&c.FallbackVolumes, "host-limit-fallback-volumes", c.FallbackVolumes, "kept for configuration compatibility; the urgent fallback is not paced (no shared host cap to protect)") fs.IntVar(&c.FetchSlots, "host-limit-fetch-slots", c.FetchSlots, "chunk fetches in flight on the host, across its processes (1-1024); a read of an absent chunk waits for a slot, bounded by its read-miss timeout") + fs.DurationVar(&c.YieldAfter, "host-limit-yield-after", c.YieldAfter, "a normal cut that has held its slot this long gives it to a waiting cut at its next staging batch (keeping what it staged); a lone cut never yields") fs.DurationVar(&c.NoProgress, "host-limit-no-progress", c.NoProgress, "a held slot is revoked after this long with no progress of its work (chunks compared, staged, uploaded or filled); revocation aborts but waits for admitted I/O before release") fs.DurationVar(&c.NoProgress, "host-limit-max-hold", c.NoProgress, "deprecated: the same as --host-limit-no-progress (a hold is no longer limited by its age)") } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 91b7d1c809..3221fa911f 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -442,7 +442,7 @@ type CutScheduleStatus struct { TicketDueHostNs int64 `json:",omitempty"` // the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting TicketsSkipped uint64 `json:",omitempty"` // earlier tickets the waiting cut passed by the skip rule TicketDropReason string `json:",omitempty"` // why the last ticket was given up before admission, when it was a refusal that waiting cannot fix - CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (seam) + CutYields uint64 `json:",omitempty"` // automatic cut attempts that yielded their host slot to a waiting cut (not failures) } // NewDurableProvider constructs a provider. view is the ONLY diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 6bc826195b..f1204b8822 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -843,6 +843,7 @@ type cutSchedule struct { failedSeenSeq uint64 // the layer's CutSeq when the last automatic cut failed slotWaitSince time.Time // first refusal for held host slots since the last success; zero when not waiting slotWaits uint64 // automatic cuts refused for held host slots + yields uint64 // automatic cut attempts that yielded their slot to a waiting cut } // observe takes in, at now, the latest cut the layer reports (any @@ -890,6 +891,13 @@ func (pol cutPolicy) due(s cutSchedule, now time.Time, reconciling bool) (string // after records the outcome of an automatic cut started at start, with // the layer's CutSeq read after it. func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq uint64) cutSchedule { + if errors.Is(err, storage.ErrCutYielded) { + // Not a failure: the slot went to a waiting cut; try again at the + // next poll (on a ticket at the back of the queue). + s.yields++ + s.retryAt = end + return s + } if errors.Is(err, hostlimit.ErrSlotsHeld) { s.slotWaits++ if s.slotWaitSince.IsZero() { @@ -1084,7 +1092,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer } s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks) wait.record(s, ticket) - if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil { + if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && !errors.Is(err, storage.ErrCutYielded) && ctx.Err() == nil { if note, stuck := capturePendingNote(err); stuck { log.Printf("durable: %s chunk cut for volume=%s REFUSED: %s (retry in %s)", reason, volumeID, note, s.backoff) } else { @@ -2004,7 +2012,7 @@ func (w *cutWaitSlot) record(s cutSchedule, ticket *hostlimit.Ticket) { } w.mu.Lock() defer w.mu.Unlock() - st := CutScheduleStatus{HostSlotWaits: s.slotWaits, TicketDropReason: w.st.TicketDropReason} + st := CutScheduleStatus{HostSlotWaits: s.slotWaits, CutYields: s.yields, TicketDropReason: w.st.TicketDropReason} if !s.slotWaitSince.IsZero() { st.HostSlotWaitSinceNs = s.slotWaitSince.UnixNano() } diff --git a/seaweed-block/core/hostlimit/limiter.go b/seaweed-block/core/hostlimit/limiter.go index 106149f3f2..39ef7b704f 100644 --- a/seaweed-block/core/hostlimit/limiter.go +++ b/seaweed-block/core/hostlimit/limiter.go @@ -66,8 +66,9 @@ type Config struct { // FetchSlots caps the chunk fetches in flight on the host, across its // processes (HoldFetch): a guest read waits for a slot, never refused. FetchSlots int - // YieldAfter is S: a Normal hold this old yields its slot at its next - // staging batch when another cut waits (seam). + // YieldAfter is S: a Normal hold at least this old yields its slot at + // its cut's next staging batch when another cut on the host waits (a + // live ticket). A lone hold never yields; an urgent one never does. YieldAfter time.Duration } @@ -503,8 +504,48 @@ func (l *Limiter) Progress(id uint64) { } } -// ShouldYield reports whether the hold id should yield its slot now (seam). -func (l *Limiter) ShouldYield(id uint64) bool { return false } +// ShouldYield reports whether the hold id should yield its slot now: it is +// a Normal hold at least YieldAfter old and another cut on the host waits. +// It takes no lock of the limiter; the waiter probe (the tickets directory) +// runs only once the hold is old enough. +func (l *Limiter) ShouldYield(id uint64) bool { + v, ok := l.leases.Load(id) + if !ok { + return false + } + x := v.(*lease) + if x.class != Normal || time.Since(x.started) < l.cfg.YieldAfter { + return false + } + return l.waiterLive() +} + +// waiterLive reports whether another cut waits on the host: a live ticket in +// the pool (its holder's lock held) that this process has not judged stalled. +// A dead ticket found on the way is reaped, as a waiter's head check does. +func (l *Limiter) waiterLive() bool { + dir := filepath.Join(l.cfg.Directory, ticketsDir) + ents, err := os.ReadDir(dir) + if err != nil { + return false + } + present := make(map[string]bool, len(ents)) + for _, e := range ents { + present[e.Name()] = true + } + stalled := l.stalledTickets(present) + for _, e := range ents { + n := e.Name() + if _, ok := ticketDue(n); !ok || stalled[n] { + continue + } + if reap(filepath.Join(dir, n)) { + continue // its holder exited + } + return true + } + return false +} // expire runs when a hold's timer fires: a hold that progressed within its // window is armed again for the rest of it; one that did not is revoked. The diff --git a/seaweed-block/core/storage/chunk_cut_budget.go b/seaweed-block/core/storage/chunk_cut_budget.go index 5b3159f36d..e7255a2bac 100644 --- a/seaweed-block/core/storage/chunk_cut_budget.go +++ b/seaweed-block/core/storage/chunk_cut_budget.go @@ -5,15 +5,26 @@ import ( "errors" ) -// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut -// (seam). +// ErrCutYielded ends a cut attempt that gave its host slot to a waiting cut, +// at a staging batch boundary. It is its own outcome, never a failed cut: the +// chunks the attempt staged are kept, and its next attempt stages the rest. var ErrCutYielded = errors.New("storage: the cut yielded its host slot to a waiting cut") -// BudgetYield is a Budget that asks a long hold to yield (seam). +// BudgetYield is a Budget that asks a long hold to yield its slot: +// ShouldYield must be nonblocking and cheap while the hold is young. type BudgetYield interface { ShouldYield(ticket uint64) bool } +// budgetYield is the question a cut asks at each staging batch boundary; nil +// when the Budget never asks a hold to yield. +func budgetYield(b Budget, ticket uint64) func() bool { + if y, ok := b.(BudgetYield); ok { + return func() bool { return y.ShouldYield(ticket) } + } + return nil +} + // Budget is the host limiter seam. Admit runs before staging or the cut // barrier and reserves the configured payload ceiling. ReserveCOW accounts // each saved chunk until Release. ReserveCOW and Release must be nonblocking diff --git a/seaweed-block/core/storage/chunk_cut_observation.go b/seaweed-block/core/storage/chunk_cut_observation.go index cea4e073d7..bc69ca172d 100644 --- a/seaweed-block/core/storage/chunk_cut_observation.go +++ b/seaweed-block/core/storage/chunk_cut_observation.go @@ -22,11 +22,20 @@ type cutAttemptObservation struct { // progress renews the attempt's host hold (set at its admission, before // any worker starts; nil without a budget). progress func() - spans [cutWorkSpanCount]atomic.Int64 - counts [cutWorkCountCount]atomic.Int64 + // yield asks the attempt's host hold whether to give its slot to a + // waiting cut (set at its admission; nil without a yielding budget). + yield func() bool + spans [cutWorkSpanCount]atomic.Int64 + counts [cutWorkCountCount]atomic.Int64 } type cutObservationKey struct{} +// shouldYield asks, at a staging batch boundary, whether the attempt gives +// its host slot to a waiting cut. +func (w *cutAttemptObservation) shouldYield() bool { + return w != nil && w.yield != nil && w.yield() +} + // progressed reports one unit of the attempt's work to its host hold. func (w *cutAttemptObservation) progressed() { if w != nil && w.progress != nil { diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index aa522e46ae..580ffddaec 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1122,6 +1122,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch } budget = &cutBudgetReservation{budget: host, ticket: ticket, ctx: ctx} work.progress = budgetProgress(host, ticket) + work.yield = budgetYield(host, ticket) defer func() { if err != nil { err = errors.Join(err, context.Cause(budgetCtx)) @@ -1987,6 +1988,8 @@ func (l *chunkLayerImpl) recordCut(r chunkCutResult, st chunkCutStats, err error reason = "fenced" case errors.Is(err, errChunkLayerDetached): reason = "detached" + case errors.Is(err, ErrCutYielded): + l.stats.CutsYielded++ // its own outcome: never a failed cut default: l.stats.CutsFailed++ l.noteCutFailureLocked(err, abortReason) @@ -2184,6 +2187,11 @@ func (l *chunkLayerImpl) stage(ctx context.Context, st *chunkCutStats, spillCap if hook := l.testAfterStageHook; hook != nil { hook(round) } + // A batch boundary: a long hold gives its slot to a waiting cut here, + // keeping what it staged (its next attempt stages only the rest). + if cutObservation(ctx).shouldYield() { + return nil, ErrCutYielded + } } return staged, nil } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 1fef53a31d..dc02640da8 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -510,7 +510,7 @@ type chunkLayerStats struct { CutsNoop uint64 // cuts with nothing new (no CAS) CutsFailed uint64 // every other cut failure CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached - CutsYielded uint64 // attempts that gave their host slot to a waiting cut (seam) + CutsYielded uint64 // attempts that gave their host slot to a waiting cut at a staging batch boundary CutsAborted map[string]uint64 // saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload CASConflicts uint64 // HEAD CAS precondition failures CASUnknown uint64 // HEAD CAS results still unresolved after the re-read diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5f715d47af..a2c950cd30 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -509,7 +509,7 @@ snapshot lifetime; local persistence does not bypass it. ### M7. Host background-cut admission -`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. +`free -> [waiting] -> admitted -> draining -> joined -> released`; process death releases its OS locks (slots, tickets, the pending hold). Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; a hold is revoked only after its no-progress window (`NoProgress`, default 60 s) passes with no progress of its work (a chunk compared, staged or uploaded by the cut; `INV-HOST-HOLD-NO-PROGRESS-001`), and revocation cancels the cut but keeps its slot until workers join. Chunk fetches (a guest read miss, a hydrate-all fill) hold one of the host's `FetchSlots` (default 64) across their remote read only, after the limiter's first fetch checked the host's configuration; with all held they wait, unordered and bounded by the read's own timeout (a read miss answers pending) (`INV-HOST-FETCH-CAP-001`). A Normal hold at least `YieldAfter` old (default 5 min) yields its slot at its cut's next staging batch while another cut on the host holds a live ticket (`INV-HOST-CUT-YIELD-001`): the attempt ends as `yielded`, keeps what it staged, and its next attempt takes a ticket at the back; a lone hold never yields. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots. **Waiting (timer cuts).** A timer cut waiting for a slot holds a ticket: a file in `tickets/` named by its due time on the host monotonic clock, locked while it waits; it is taken by create, lock, and a re-check that the path still names the locked file. It is admitted only when no earlier ticket is live: an earlier ticket whose lock can be taken (its process exited) is removed by lock, re-check, unlink, unlock; a live one is passed only after the waiter has seen it stay ahead for 2 s of time with a normal slot free and no urgent work pending, summed across polls (a busy period pauses the count; the skip rule; it can be wrong about a slow holder: ticket order is fairness only, the slot lock is the exclusion). Only the earliest live earlier ticket not yet judged stalled is observed; a process keeps its judgement, for its later tickets too, until that ticket's file disappears, so one stalled ticket costs one skip, not one per hand-off. Admission consumes the ticket; a success elsewhere, fencing, Close, exit, not attempting (backoff, spacing, reconciling), or a refusal that waiting cannot fix drop it (the reason is reported). A refusal for held slots, pending urgent work, an earlier ticket or a held configuration lock is a wait. A timer cut that meets another capture holding the capture lock waits for it and is then skipped (that capture restarted the timer); while it waits, other waiters judge its ticket stalled after the skip time, once. @@ -1004,6 +1004,7 @@ Notes: | `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE | | `INV-HOST-HOLD-NO-PROGRESS-001` | A held slot is revoked only after its no-progress window passes with no reported progress of its work (a chunk compared, staged or uploaded by its cut): work that keeps progressing is never revoked, and a stalled hold is revoked within the window. | M7 admitted → draining (revoked) | `core/hostlimit/limiter.go` `Admit`, `Progress`, `expire`; `core/storage/chunk_cut_budget.go` `BudgetProgress`, `budgetProgress`; `core/storage/chunk_cut_observation.go` `progressed`; `core/storage/chunk_layer.go` `captureLocked` | `TestStalledHoldIsRevokedWithinTheWindow`, `TestProgressRenewsTheHold` (`core/hostlimit/limiter_progress_test.go`); `TestProgressRacingTheExpiryIsHonoured`, `TestProgressDoesNotWaitForTheLimiterLock`, `TestProgressStampIsMonotonicElapsed` (`core/hostlimit/limiter_review_test.go`); `TestCutReportsProgressToItsBudget` (`core/storage/chunk_cut_hold_progress_test.go`) | SlotShare (its progress-window rule; the share rule is a later change) | ACTIVE | | `INV-HOST-FETCH-CAP-001` | A chunk fetch holds one of the host's FetchSlots across its remote read only; a limiter's first fetch checks the host configuration (ErrConfig on a mismatch). With all held it waits, never refused: unordered, bounded by its context alone. Only non-blocking tries: an ended wait leaves nothing. | M7 (fetch slots, beside the cut slots) | `core/hostlimit/fetch.go` `HoldFetch`, `checkFetchConfig`, `waitFetch`; `core/hostlimit/limiter.go` `configGuard`; `core/storage/chunk_layer.go` `fillOnce`; `core/storage/chunk_cut_budget.go` `BudgetFetch` | `TestHoldFetchTakesAFreeSlotAtOnce`, `TestHoldFetchCapHoldsAcrossLimiters`, `TestHoldFetchAWaiterThatGivesUpLeavesNoSlotHeld`, `TestHoldFetchTakesAnotherSlotThatFreesFirst` (`core/hostlimit/fetch_test.go`); `TestHoldFetchFirstFetchChecksTheHostConfiguration`, `TestHoldFetchSlotDiesWithItsProcess`, `TestHoldFetchEndedWaitsLeaveNothingBehind`, `TestHoldFetchCancelledAtTheHandoffHoldsNothing`, `TestHoldFetchAPassedWaiterEndsByItsDeadline` (`core/hostlimit/fetch_review_test.go`); `TestChunkFetchHoldsAHostSlotAroundItsRemoteRead` (`core/storage/chunk_fetch_cap_test.go`) | — (a resource cap with no state of its own) | ACTIVE | +| `INV-HOST-CUT-YIELD-001` | A Normal hold at least YieldAfter old yields its slot at its cut's next staging batch only while another cut on the host holds a live ticket it has not judged stalled; the attempt ends as yielded, never a failure, and keeps what it staged. A lone or urgent hold never yields. | M7 admitted → released (yielded) | `core/hostlimit/limiter.go` `ShouldYield`, `waiterLive`; `core/storage/chunk_layer.go` `stage`; `core/storage/chunk_cut_budget.go` `ErrCutYielded`, `budgetYield`; `core/frontend/durable/provider_chunk.go` `cutPolicy.after` | `TestShouldYieldOnlyAfterSWithALiveWaiter` (`core/hostlimit/yield_test.go`); `TestCutYieldsAtABatchBoundaryAndKeepsItsStaging` (`core/storage/chunk_cut_yield_test.go`); `TestChunkLoop_AYieldIsRetriedAtOnceAndCountedApart` (`core/frontend/durable/cut_loop_yield_test.go`) | SlotShareN (yield on the waiting probe, a new ticket at the back); SlotShare rows 189 to 193 | ACTIVE | | `INV-HOST-CUT-BUDGET-CONFIG-001` | A busy configuration lock or a mismatched pool configuration refuses every class, urgent included, with no fallback. | M7 free → admitted (refused) | `core/hostlimit/limiter.go` `pool`, `Admit` | `TestConfigurationLockContentionRefusesAllClasses` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | | `INV-HOST-CUT-BUDGET-FALLBACK-001` | Only urgent admissions (urgent move-final cuts and named seals) proceed while the pool is unavailable, on a per-process fallback that claims no host-wide bound, leaves uploads unpaced while only fallback leases live, and is reported as fallback while any such lease lives. | M7 free → admitted (pool unavailable) | `core/hostlimit/limiter.go` `Admit`, `releaseLoop`, `WaitUpload` | `TestUnusablePoolClassPolicy`, `TestLastFallbackReleaseClearsActiveStatus`, `TestUrgentFallbackUploadIsNotPaced`, `TestFallbackDoesNotUnpaceAHealthyLease`, `TestConfigurationLockFailurePreservesPoolPolicy` (`core/hostlimit/limiter_test.go`); `TestChunkControl_NamedSnapshotUsesUrgentFallback` (`core/host/volume/chunk_control_adapter_test.go`) | `HostBudget` (fallback excluded) | ACTIVE | | `INV-HOST-CUT-BUDGET-PACING-001` | A process's upload pacing debt carries across its own leases, and a new process starts with no debt. | M7 admitted (upload pacing) | `core/hostlimit/limiter.go` `WaitUpload` | `TestPacingDebtSurvivesOwnLeaseTurnover`, `TestPacingFreshProcessesDoNotShareDebt` (`core/hostlimit/limiter_test.go`) | — | ACTIVE | diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 044a5550d7..13c0502601 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -17,6 +17,9 @@ These notes collect v1.1's changes as they land; v1.1 is not released. across the host's processes, so a mass move puts at most that many in flight. A read of an absent chunk waits for a slot, in no set order and bounded by its read-miss timeout, and is never refused. A process's first fetch checks the host's `configuration.json` as a cut admission does, so a fetch-only process with other flags is refused too. +- A normal cut that has held its host slot for `--host-limit-yield-after` (default 5 min) gives the slot to a waiting + cut at its next staging batch, keeping what it staged; its next attempt queues behind the waiters. A lone cut never + yields, and status counts yields apart from failures (`CutYields`). ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was From 495bbf8fe26a39a19709c009b5840a1b851489fc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 12:04:08 -0800 Subject: [PATCH 40/51] docs: status schema carries the cut yield counters Regenerated with STATUS_SCHEMA_UPDATE=1: Chunk.Stats.CutsYielded and Chunk.CutSchedule.CutYields. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/status-schema.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index c646dd92df..36c0315fe7 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -255,6 +255,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | | `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | | `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | +| `Volumes[].Chunk.Stats.CutsYielded` | uint64 | attempts that gave their host slot to a waiting cut at a staging batch boundary | | `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, no_room_to_cut, free_space_unreadable, budget_revoked, upload | | `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | | `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | @@ -339,6 +340,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.CutSchedule.TicketDueHostNs` | int64 | the waiting cut's host ticket: its due time on the host monotonic clock; absent when not waiting (omitted when empty) | | `Volumes[].Chunk.CutSchedule.TicketsSkipped` | uint64 | earlier tickets the waiting cut passed by the skip rule (omitted when empty) | | `Volumes[].Chunk.CutSchedule.TicketDropReason` | string | why the last ticket was given up before admission, when it was a refusal that waiting cannot fix (omitted when empty) | +| `Volumes[].Chunk.CutSchedule.CutYields` | uint64 | automatic cut attempts that yielded their host slot to a waiting cut (not failures) (omitted when empty) | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | From 868ee3c59553f5c2457c304cb9ffcf62d61f8d7b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:55:01 -0800 Subject: [PATCH 41/51] storage: the newer-format refusal's invariant row; narrow the discard claim INV-STORE-FORMAT-NEWER-001: an intact descriptor of a newer store format is refused typed, and an open refused at slot selection removes no file. The discard's comment names what it covers: a refusal after the select (a corrupt map) may still follow it. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/walstore_v3.go | 6 ++++-- seaweed-block/docs/design/invariants.md | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/storage/walstore_v3.go b/seaweed-block/core/storage/walstore_v3.go index 67edc7f070..9c9c3f17bd 100644 --- a/seaweed-block/core/storage/walstore_v3.go +++ b/seaweed-block/core/storage/walstore_v3.go @@ -372,8 +372,10 @@ func openWALStoreV3File(path string, f *os.File, requireMap bool, opts WALStoreO _ = f.Close() return nil, err } - // Side files are discarded only by an open that selected a slot: a store - // it refuses (a newer format, an invalid descriptor) is left as it was. + // Side files are discarded only by an open that selected a slot: an open + // refused at slot selection (a newer format, no valid descriptor) leaves + // the directory as it was. A later refusal (a corrupt map) may follow the + // discard, as before. if !creating { if err := discardCutCOWFiles(path); err != nil { _ = f.Close() diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5f715d47af..1ab783d3c9 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -632,6 +632,7 @@ The "Machine / transition" column refers to Part A. Notes under a table record w | `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates, except as `INV-WAL-V3-CAPTURE-COMPARED-001`. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | | `INV-WAL-V3-CAPTURE-COMPARED-001` | A chunk known equal to HEAD is neither staged nor compared again while its mutation version and HEAD ref match; own-batch chunks remain candidates. An interrupted or refused cut retains these proofs and requeues only unproven chunks. All candidate paths use one predicate. | M5 candidate selection | `core/storage/chunk_layer.go` `knownEqualToHeadLocked`, `captureCandidates`, `captureLocked`, `recordCapturedEqualMarks`, `stage`, `requeueCut`; `chunk_cut_payload.go` `markEqualNow` | `TestFreshFromHeadReadBackLeavesNoCutCandidates`, `TestFreshFromHeadFilledThenWrittenIsACandidate`, `TestEveryLocalWriteAfterACleanFillMakesTheChunkACandidate`, `TestABaseInstallAfterCleanFillsEndsTheirRecords`, `TestACleanFillRecordEndsWithItsHeadRef`, `TestARestoreTargetThatOnlyReadCutsNothing`, `TestARerunAfterAFailedCutComparesOnlyWhatDiffers`, `TestWithoutAFailedCutEveryUnknownChunkIsCompared`, `TestACutOffCompareKeepsItsWorkAndTheRerunComparesOnlyTheRest`, `TestFilledChunksAreFirstCutCandidatesAfterARestart`, `TestEveryDirtyMapInsertNotesTheChunkMutation`, `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`; `TestRefusedFullCutStagesOnlyTheUnmarkedChunk` (`core/storage/chunk_staging_equal_test.go`); `TestCopyErrorKeepsCapturedEqualMarks`, `TestInterruptedStagingKeepsEqualWork` (`core/storage/chunk_copy_error_equal_test.go`); `TestTimedOutRequestsThenRefusedCommitKeepEqualWork` (`core/frontend/chunkstore/layout_staging_retry_test.go`); also in `core/storage/chunk_fresh_readback_candidates_test.go`, `core/frontend/durable/first_cut_known_zero_test.go`, `core/storage/chunk_compare_progress_test.go`, `core/storage/chunk_mutation_note_guard_test.go`, `core/storage/chunk_own_test.go` | EqualMarks.MarkSound, EqualMarks.NoRecompare (must-violate rows 102-104); conservative reachability unchanged | ACTIVE | | `INV-CHUNK-STATE-UPGRADE-FENCE-001` | The chunk-state upgrade fence succeeds only after both descriptor slots are fsynced and read back with the format marker and local-work epoch; matching reopened slots require a fresh sync; uncertain writes or readback latch until reopen. | M1 format upgrade (caller not wired) | `core/storage/chunk_state_upgrade.go` `WALStore.FenceChunkStateUpgrade` | `TestChunkStateUpgradeFencesBothSlotsBeforeCompletion`, `TestChunkStateUpgradeUncertainSecondSlotRequiresReopen`, `TestChunkStateUpgradeFailureNeverCompletesUntilReopen`, `TestChunkStateUpgradeOldReaderPublicationRestartsTheFence`, `TestChunkStateUpgradeReopenedCachedPairNeedsFreshSync`, `TestChunkStateUpgradeRejectsSuccessfulWrongReadback` (`core/storage/chunk_state_upgrade_test.go`; single-publication and unlatched-readback mutant controls) | `CHUNK-STATE-r3` section 18; `SlotFence` rows 146-149 | STUB | +| `INV-STORE-FORMAT-NEWER-001` | An intact descriptor slot naming a store format newer than this binary reads is refused typed (`ErrStoreFormatNewer`), never as an invalid descriptor; an open refused at slot selection removes no file. | M1 open | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`; `core/storage/walstore_v3.go` `openWALStoreV3File` | `TestANewerStoreFormatIsRefusedTypedAndUntouched` (`core/storage/superblock_v3_format_newer_test.go`; refusal without the typed check and discard-before-select controls) | `SlotFence2` OpenNew | ACTIVE | | `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | | `INV-CHUNK-RECORD-PAGES-CURRENT-001` | An unfinished chunk record is used, and its header written, only when every page passes its check and is valid through exactly the store's synced position after recovery (behind: missed writes; ahead: not durable); an unmarked store discards it; the header follows the two-slot fence. | M1 Opened (chunk record load, v1.1 upgrade) | `core/storage/chunk_record.go` `loadChunkRecord`, `completeChunkRecord` | `TestUnfinishedRecordPagesBehindTheStoreAreNotTrusted`, `TestUnfinishedRecordAfterAnOldCheckpointIsDiscarded`, `TestStalePagesAreNeverCompleted`, `TestUnfinishedPagesAheadOfTheStoreAreNotTrusted`, `TestCompleteRecordAheadOfTheStoreIsNotTrusted`, `TestCompleteRecordPagePositions`, `TestRecordHeaderWaitsForTheFence`, `TestRecordHeaderIsNotWrittenAheadOfTheSyncedStore`, `TestDamagedPage` (`core/storage/chunk_record_test.go`) | SlotFence `PagesCurrent`, `FenceHolds`; pages carry chunk-kernel/2 states (the per-chunk state models are not in this repository) | STUB | From b0433c4bbf1e54a8119b09d865f14a36397e22d9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:36:07 -0800 Subject: [PATCH 42/51] blockvolume: a newer HEAD or store format exits 78, not a restart loop A startup that ends on a HEAD written by a newer version exits 78 head_newer_version instead of the restartable 75 (a restart reads the same HEAD again), and a fatal open of a store written by a newer format exits 78 store_format_newer instead of 1. The provider latches the newer-version refusal per recovery, beside the identity refusal. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 6 ++- .../blockvolume/newer_version_exit_test.go | 47 +++++++++++++++++++ seaweed-block/cmd/blockvolume/process_exit.go | 17 +++++++ .../core/frontend/durable/provider.go | 4 ++ .../core/frontend/durable/provider_startup.go | 10 ++++ .../durable/provider_startup_internal_test.go | 24 +++++++++- seaweed-block/docs/design/invariants.md | 4 +- 7 files changed, 108 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/newer_version_exit_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ea483d87ef..1de4d97e3a 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -938,7 +938,11 @@ func runVolume(f flags, exits *processExit) int { shutCancel() } _ = h.Close() - return 1 + code, reason := durableOpenFatalExit(sErr) + if reason != "" { + return reportWorkspaceExit(workspaceExit{code: code, reason: reason, detail: "the local store was written by a newer version: run a newer binary"}) + } + return code case durableStartupFaulted: fmt.Fprintln(os.Stderr, "blockvolume: durable recovery failed:", evidence) return waitFaultedDurableRecovery(exits.done, h, status, durableProv, evidence) diff --git a/seaweed-block/cmd/blockvolume/newer_version_exit_test.go b/seaweed-block/cmd/blockvolume/newer_version_exit_test.go new file mode 100644 index 0000000000..ded6947512 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/newer_version_exit_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// exitNewerVersion is a startup outcome that ended on a HEAD written by a +// newer version. +type exitNewerVersion struct{ exitStartupOutcome } + +func (exitNewerVersion) ChunkStartupNewerVersion(string, uint64) bool { return true } + +// A startup ended on a HEAD written by a newer version exits 78 +// head_newer_version (no restart: a restart reads the same HEAD), where the +// same ended startup otherwise exits the restartable 75. +func TestANewerHeadVersionExits78NotRestartable(t *testing.T) { + h, _ := exitAuthorityHost(t) + e := newProcessExit(context.Background()) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitNewerVersion{exitStartupOutcome{expired: true}}) { + t.Fatal("the newer-version startup did not end the process") + } + if out := <-e.decision; out.code != 78 || out.reason != "head_newer_version" { + t.Fatalf("newer-version startup exit = %+v, want 78 head_newer_version", out) + } + h2, _ := exitAuthorityHost(t) + e2 := newProcessExit(context.Background()) + chooseChunkStartupExit(e2, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h2, &exitStartupOutcome{expired: true}) + if out := <-e2.decision; out.code != 75 { + t.Fatalf("control: an ended startup without the refusal exits %+v, want 75", out) + } +} + +// A fatal durable open of a store written by a newer format exits 78 +// store_format_newer; any other fatal open exits 1 as before. +func TestAStoreOfANewerFormatExits78(t *testing.T) { + if code, reason := durableOpenFatalExit(fmt.Errorf("durable: OpenWALStore x: %w", storage.ErrStoreFormatNewer)); code != 78 || reason != "store_format_newer" { + t.Fatalf("newer-format store exit = %d %q, want 78 store_format_newer", code, reason) + } + if code, reason := durableOpenFatalExit(errors.New("durable: OpenWALStore x: invalid superblock")); code != 1 || reason != "" { + t.Fatalf("other fatal open exit = %d %q, want 1", code, reason) + } +} diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 1ead071108..87b8b6d4b7 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -2,6 +2,7 @@ package main import ( "context" + "errors" "fmt" "os" "os/signal" @@ -11,6 +12,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/host/volume" + "github.com/seaweedfs/seaweed-block/core/storage" ) const ( @@ -136,6 +138,16 @@ func reportWorkspaceExit(out workspaceExit) int { // INV-WS-STARTUP-RETRY-001: one decision combines a newer other-replica // authority fact and the provider's generation-bound foreign-HEAD proof. +// durableOpenFatalExit is the exit of a fatal durable storage open: 78 with +// reason store_format_newer for a store written by a newer format (no +// restart can open it), else 1 as before. +func durableOpenFatalExit(err error) (int, string) { + if errors.Is(err, storage.ErrStoreFormatNewer) { + return exitWorkspaceSuperseded, "store_format_newer" + } + return 1, "" +} + func workspaceRetryOutcome(reason string, h *volume.Host, claimSuperseded bool) workspaceExit { if claimSuperseded || h.IsCurrentReplicaSuperseded() { return workspaceExit{code: exitWorkspaceSuperseded, reason: "superseded"} @@ -275,6 +287,11 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar } } } + // A HEAD written by a newer version is permanent for this binary: exit 78, + // never the restartable 75 (a restart reads the same HEAD again). + if nv, ok := p.(interface{ ChunkStartupNewerVersion(string, uint64) bool }); ok && nv.ChunkStartupNewerVersion(f.volumeID, gen) { + out = workspaceExit{code: exitWorkspaceSuperseded, reason: "head_newer_version", detail: "HEAD was written by a newer version: run a newer binary"} + } if c, ok := p.(interface{ ChunkStartupCure(string, uint64) string }); ok { if cure := c.ChunkStartupCure(f.volumeID, gen); cure != "" { out.detail = cure diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index ff4927c411..d7d1cc9899 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -336,6 +336,9 @@ type volHandle struct { // startupIdentityRefused is the definite full-id refusal for startupEnded. // endChunkStartup is its decision writer, guarded by p.mu. startupIdentityRefused bool + // startupNewerVersion: startupEnded's refusal was a HEAD written by a + // newer version (layout.ErrHeadNewerVersion). endChunkStartup writes it. + startupNewerVersion bool // ImplWALStoreChunk. fresh: the local volume is new and starts from // the remote HEAD. It mirrors the durable fresh marker beside the @@ -1164,6 +1167,7 @@ func (p *DurableProvider) RecoverVolume(ctx context.Context, volumeID string) (R h.startupEnded = 0 h.startupSuperseded = false h.startupIdentityRefused = false + h.startupNewerVersion = false p.mu.Unlock() } report := recoverContext(ctx, h.storage, volumeID) diff --git a/seaweed-block/core/frontend/durable/provider_startup.go b/seaweed-block/core/frontend/durable/provider_startup.go index 10e4e1db8c..6c23502c99 100644 --- a/seaweed-block/core/frontend/durable/provider_startup.go +++ b/seaweed-block/core/frontend/durable/provider_startup.go @@ -44,6 +44,15 @@ func (p *DurableProvider) ChunkStartupIdentityRefused(volumeID string, gen uint6 return !p.closed && h != nil && gen != 0 && h.recoverGen == gen && h.startupEnded == gen && h.startupIdentityRefused } +// ChunkStartupNewerVersion reports that this recovery's startup ended on a +// HEAD written by a newer version: no restart of this binary can read it. +func (p *DurableProvider) ChunkStartupNewerVersion(volumeID string, gen uint64) bool { + p.mu.Lock() + defer p.mu.Unlock() + h := p.volumes[volumeID] + return !p.closed && h != nil && gen != 0 && h.recoverGen == gen && h.startupEnded == gen && h.startupNewerVersion +} + func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error) { p.mu.Lock() defer p.mu.Unlock() @@ -53,6 +62,7 @@ func (p *DurableProvider) endChunkStartup(h *volHandle, gen uint64, cause error) h.startupEnded = gen h.startupSuperseded = errors.Is(cause, errChunkForeignClaim) h.startupIdentityRefused = errors.Is(cause, layout.ErrIdentity) + h.startupNewerVersion = errors.Is(cause, layout.ErrHeadNewerVersion) h.startupCure = "" switch { case errors.Is(cause, layout.ErrStaleLocalRoot): diff --git a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go index 3d5848f289..ab0b19a7e9 100644 --- a/seaweed-block/core/frontend/durable/provider_startup_internal_test.go +++ b/seaweed-block/core/frontend/durable/provider_startup_internal_test.go @@ -1,6 +1,11 @@ package durable -import "testing" +import ( + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" +) func TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake(t *testing.T) { h := &volHandle{recoverGen: 1} @@ -55,3 +60,20 @@ func TestChunkStartupForeignProofIsGenerationBound(t *testing.T) { t.Fatal("old foreign proof poisoned current retry") } } + +// A startup that ends on a HEAD written by a newer version is latched for +// that recovery only; another cause (a malformed HEAD) is not it. +func TestChunkStartupNewerVersionIsGenerationBound(t *testing.T) { + h := &volHandle{recoverGen: 1} + p := &DurableProvider{volumes: map[string]*volHandle{"v": h}, startupUpdates: make(chan struct{}, 1)} + p.endChunkStartup(h, 1, fmt.Errorf("attach: %w", layout.ErrHeadNewerVersion)) + if !p.ChunkStartupNewerVersion("v", 1) || p.ChunkStartupNewerVersion("v", 2) || p.ChunkStartupNewerVersion("other", 1) { + t.Fatal("the newer-version refusal escaped its volume or recovery generation") + } + h2 := &volHandle{recoverGen: 1} + p2 := &DurableProvider{volumes: map[string]*volHandle{"v": h2}, startupUpdates: make(chan struct{}, 1)} + p2.endChunkStartup(h2, 1, fmt.Errorf("attach: %w", layout.ErrMalformed)) + if p2.ChunkStartupNewerVersion("v", 1) { + t.Fatal("a malformed HEAD was taken for a newer version") + } +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 1ab783d3c9..f15805d7ab 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -923,11 +923,11 @@ Notes: | `INV-WS-FORCED-CONFIRM-HOLDER-001` | A confirmation at an epoch the master reports no holder for, in its lease or its move journal, is refused without sending a move. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `core/rpc/wsclient/wsclient.go` `holderAt`, `request` | `TestForceMoveResolvesTheHolder` (`core/rpc/wsclient/wsclient_test.go`) | — | ACTIVE | | `INV-WS-FORCED-CONFIRM-NO-BYPASS-001` | No force-move flag bypasses the confirmation, and `--dry-run` is never a confirmation: it sends only a preview, which needs the same confirmation. | M2 lease: Expired → Moved (forced) (the explicit-force guard) | `cmd/sw-block/workspace.go` `runWorkspaceForceMove`, `workspacePreview`; `core/rpc/wsclient/wsclient.go` `PreviewForcedMove` | `TestWorkspaceForceMove_Row2_DryRunPreview`, `TestWorkspaceHelpText` (`cmd/sw-block/workspace_test.go`) | — | ACTIVE | | `INV-ATTACH-ASSIGNMENT-BOUND-001` | Without a master wait, the assignment allowance is checked between attach attempts; it never cancels a granted attempt's manifest read. Per-fetch bounds, recovery progress and provider Close still apply. | M1 Recovering to Serving (wait scheduling only) | `DurableProvider.chunkAuthorityWait` | `TestDefaultAttachAt262144EntriesOutlivesAssignmentWait`, `TestDefaultGrantedAttachFailureEndsAtAssignmentAllowance` (`core/frontend/durable/default_attach_attempt_test.go`); `TestRestoreDeferredAssignmentWaitEndsOnDeadlineAndClose` (`core/frontend/durable/provider_assignment_test.go`) | none (scheduling; authority guards unchanged) | ACTIVE | -| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_startup.go` `ChunkStartupIdentityRefused`, `endChunkStartup` | `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | +| `INV-WS-STARTUP-RETRY-001` | A workspace primary exits 75 on assignment timeout or lease expiry after bounded cleanup. A master fact newer than nonzero observed-own, or an exact foreign HEAD at/above the assigned epoch, permits 78. Newer HEAD/store format: 78. ACK and signal keep normal exit; lease and claim gates never relax. | M2 restart | `cmd/blockvolume/process_exit.go` `superviseProcess`, `workspaceRetryOutcome`; `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_startup.go` `ChunkStartupIdentityRefused`, `ChunkStartupNewerVersion`, `endChunkStartup`; `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`, `durableOpenFatalExit` | `TestANewerHeadVersionExits78NotRestartable`, `TestAStoreOfANewerFormatExits78` (`cmd/blockvolume/newer_version_exit_test.go`); `TestChunkStartupNewerVersionIsGenerationBound` (`core/frontend/durable/provider_startup_internal_test.go`); `TestChunkAssignmentTimeoutExposesCurrentRecoveryOutcome` (`core/frontend/durable/provider_startup_outcome_test.go`); `TestChunkStartupOutcomeRejectsOldGenerationAndCoalescesWake` (`core/frontend/durable/provider_startup_internal_test.go`); `TestWorkspaceDisplacedClaimUsesAssignedEpoch`, `TestWorkspaceRetryUsesNewestOwnAssignment`, `TestWorkspaceForeignHeadClaimChoosesNoRetry`, `TestWorkspaceOldLocalHolderForeignHeadChoosesNoRetry` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceExitFirstOutcomeIsLatched`, `TestWorkspaceExitDoesNotWaitForBlockedFrontendClose`, `TestWorkspacePlannedStopKeepsSuccess` (`cmd/blockvolume/process_exit_test.go`) | Existing WorkspaceRegrant restart transition; no new grant rule | ACTIVE | | `INV-WS-MASTER-WAIT-001` | Startup waits without a bound while the master gives no reply or refuses credentials or identity; after contact it ends 30 s beyond the later of recovery's first reply or the master barrier. Typed MOVED or DELETED ends it with 78, including a confirmed moved source without an own assignment. | M2 Awaiting assignment → Process exited | `core/host/volume/master_wait.go` `masterWait` (contact from heartbeat, stream and renewal results; the refusal kind from the status detail only); `core/frontend/durable/provider_chunk.go` `chunkAuthorityWait` (`ChunkMasterWait`); `cmd/blockvolume/process_exit.go` `chooseChunkStartupExit`; `core/host/master/workspace_service.go` `leaseRefusal`, `renewalMoved`; `core/authority/workspace.go` `WorkspaceSourceMoved`; `core/host/master/services.go` `SubscribeAssignments`; `core/authority/workspace_lease_view.go` `LeaseBarrierError`; `core/host/volume/workspace_lease.go` `renewDelay` (sleeps until just past the barrier time, jittered, at most 2 min; then a 200 ms poll for 5 s); `core/rpc/link/link.go` `MasterReconnect` | `TestChunkAuthorityWaitStartsAtFirstContact`, `TestLeaseGuardSleepsUntilTheBarrier`, `TestStatusShowsTheMasterWait`, `TestCredentialsRefusedForAnHourWaitsAndLogs`, `TestHeartbeatLogsTheMasterWait`, `TestFlappingMasterNeverExpiresEarly` (`core/host/volume/master_wait_test.go`); `TestMasterLinkReconnectsWithinTwoSeconds` (`core/host/volume/master_reconnect_test.go`); `TestChunkAuthorityWaitFollowsTheMasterWait`, `TestChunkAuthorityWaitPassesItsOwnStart`, `TestChunkGrantedAttachThatKeepsFailingIsBounded`, `TestChunkAuthorityWaitAttachesAGrantOnTheBoundsTick` (`core/frontend/durable/provider_master_wait_test.go`); `TestIdentityRefusalWaitsVisibly`, `TestChunkAuthorityWaitAfterASlowOpenGetsItsFullLimit`, `TestIdentityRefusalEndsAndDecays` (`core/host/volume/master_wait_test.go`); `TestIdentityRefusalEndsOnADeliveredAssignment` (`cmd/blockvolume/process_exit_authority_test.go`); `TestIdentityRefusalIsTyped` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestLeaseRefusalKinds`, `TestRenewalReplicaMismatchAtOlderLineEpochIsOther` (`core/host/master/workspace_lease_refusal_kind_test.go`); `TestChunkStartupExitFinalGives78`, `TestRestartedMovedSourceExits78WithoutAnOwnLine` (`cmd/blockvolume/process_exit_authority_test.go`); `TestWorkspaceSourceMovedProof`, `TestMovedSourceProofCallers`, `TestMasterWaitFinalSites`, `TestMovedAssignmentStreamIsFinalWithoutAnyOwnAssignment`; also in `core/authority/workspace_source_moved_test.go`, `core/host/master/workspace_moved_source_guard_test.go` | Real systemd moved-source and prestarted-target controls remain qualification gates. | ACTIVE | - `INV-WS-DELETE-NO-LIVE-HOLDER-001`: the verdict is the first admission's only. A rerun of a delete whose token already holds the reservation (or a committed one) is admitted without a new verdict and goes on to the catalog step, whose HEAD compare-and-swap is the fence: a HEAD a holder claimed in between is refused there and the reservation given back, so an interrupted delete strands neither the volume nor its id. A reservation may hold several tokens (one per delete request); a new token on an admitted reservation is decided by the verdict; on a committed one it skips the verdict too (committed only once the HEAD is being purged, so no holder can claim it). The HEAD read before the lock still runs for a rerun, and its result is then unused: it is kept outside the workspace lock on purpose. Availability window: a delete admitted for a never-started line that stops before it marks HEAD leaves the volume reserved for deletion; if the holder then claims HEAD, the volume cannot be used until that delete is re-run (the catalog step then refuses the live HEAD and gives the reservation back). Re-run an interrupted delete. -- `INV-WS-STARTUP-RETRY-001`: exit 78 is permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75 unless the master proves this server was an issued move's source and returns typed MOVED), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. +- `INV-WS-STARTUP-RETRY-001`: a startup ended on a HEAD written by a newer version exits 78 `head_newer_version`, and a fatal open of a local store written by a newer format exits 78 `store_format_newer`: no restart of this binary can read either, so neither restarts. Exit 78 is also permitted by a NEWER observed master fact for this volume naming another holder (compared with nonzero observed-own assignment; never-assigned zero retries75 unless the master proves this server was an issued move's source and returns typed MOVED), or by the exact refused HEAD claim image proving another holder at or above the assigned epoch. The provider binds the latter proof to its recovery generation. Both existing-root checks and claim CAS readback use the same epoch-qualified supersede classifier. A lower-epoch foreign HEAD on an existing root retains the move-back diagnostic; a displaced lower-epoch claim on a fresh root retries 75 without serving. A same-holder higher-epoch HEAD fence retries 75. Unknown/no line, same replica at a higher epoch, and status codes alone mean retry 75. A wrong retry costs a bounded restart loop; a wrong 78 causes an outage until an explicit operator start. Sealed same-epoch recovery remains up for read-only replay after assignment; stale local roots, corrupt WAL and I/O faults retain diagnostic wait. The first chosen outcome wins. Process cleanup reuses `WorkspaceDrainTimeout` (5 s), including a blocked Close; only main exits the process. - `INV-WS-MASTER-WAIT-001`: every reply produced by blockmaster's handler starts or continues a contact streak; a transport failure (`Unavailable`, `DeadlineExceeded`, `Canceled`) ends it. So a master that answers and drops in turn postpones the 30 s bound for as long as it flaps, also for an obsolete unit; it never ends the wait early (`TestFlappingMasterNeverExpiresEarly`). The barrier time travels as a duration the master computes from the same two predicates as admission, added by the volume to its own monotonic request start; the master re-checks the barrier on every re-grant, so a wrong duration only moves the 75 exit. The status codes alone still mean retry 75 (`INV-WS-STARTUP-RETRY-001`); only the typed `WorkspaceLeaseRefusal` detail (MOVED, DELETED) permits the early 78. Scale: after a master restart every lapsed volume has the same barrier time T and the master grants them one at a time, each grant one store write W under the publisher lock, so the last of N volumes is granted about T + 0.1 s + N x W; a volume whose grant comes 30 s past T exits 75 and is started again, so that starts at N >= 30 s / W. Measured: W p50 1.03 ms, p99 2.33 ms, max 14.5 ms (400 writes of the file authority store on an NVMe ext4 disk, `TestWorkspaceGrantStoreWriteTime`), so 200 volumes about T + 0.6 s and the 30 s point near 12,900 volumes (p99); 20 real volume processes served at most 0.81 s after T (`TestManyVolumesServeTogetherAfterMasterRestart`). The bound holds for that store device: on a device whose flushes stall (an fsync held for seconds), one stalled write puts every waiting volume behind it, so the blockmaster store's device is a deployment premise of serving within 2 s of the barrier. A granted process whose attach keeps failing (the chunk store unreachable) retries inside the same bound and then exits 75: it does not hold the lease while never serving. An identity refusal has no bound until an identity-checked call (a renewal, a delivered assignment) is accepted, or until 30 s of replies pass with no new identity refusal; the window then opens again. A serving holder that starts getting identity refusals is outside this row: its lease expires and it fences and exits 75 (`lease_expired`). - Part T lineage evidence: `recordSelfAssignment` records the newest identity-validated observed-own assignment before local-readiness admission; `EngineProjection` is the adopted-own lineage. Exit compares the former; fencing compares the latter. Both use `IsSuperseded` with explicit lineage; zero lineage selects retry75 and no fence; neither fact grants I/O. `TestWorkspaceExitAndFenceUseNamedLineages`, `TestWorkspaceExitLineageIncludesBlockedOwnAssignment`, and `TestWorkspaceObservedLineageNeverTrailsAdoption` (`core/host/volume/workspace_startup_test.go`) keep the distinction causal. - Part T evidence scope: `workspaceRetryOutcome` is the one retry/no-retry decision. Startup `chooseChunkStartupExit` supplies the recovery-generation-bound refused-claim HEAD proof; runtime lease-end supplies none. Both combine that input with a foreign master line newer than nonzero observed-own; absent proof means retry 75. From 55562d718e62acf3d38c5b261419790f80543c0b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 14:53:53 -0800 Subject: [PATCH 43/51] blockvolume: a master's final exit wins over a newer HEAD version The newer-HEAD-version exit (78 head_newer_version) is chosen before the master's final reasons, so a startup that also met a final refusal keeps its exit: moved and deleted stay 78 with their reason, revoked stays 79. Co-Authored-By: Claude Opus 5.5 --- .../blockvolume/newer_version_exit_test.go | 46 +++++++++++++++++++ seaweed-block/cmd/blockvolume/process_exit.go | 11 +++-- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/newer_version_exit_test.go b/seaweed-block/cmd/blockvolume/newer_version_exit_test.go index ded6947512..c4273a3768 100644 --- a/seaweed-block/cmd/blockvolume/newer_version_exit_test.go +++ b/seaweed-block/cmd/blockvolume/newer_version_exit_test.go @@ -5,7 +5,12 @@ import ( "errors" "fmt" "testing" + "time" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/seaweedfs/seaweed-block/core/rpc/control" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -45,3 +50,44 @@ func TestAStoreOfANewerFormatExits78(t *testing.T) { t.Fatalf("other fatal open exit = %d %q, want 1", code, reason) } } + +// A master's final refusal keeps its exit when the same startup also ended +// on a newer HEAD version: MOVED stays 78 moved, FINAL stays 79 revoked. +func TestAMasterFinalExitWinsOverANewerHeadVersion(t *testing.T) { + for _, tc := range []struct { + kind control.WorkspaceLeaseRefusal_Kind + final string + code int + reason string + }{ + {control.WorkspaceLeaseRefusal_MOVED, "moved", 78, "moved"}, + {control.WorkspaceLeaseRefusal_FINAL, "revoked", 79, "revoked"}, + } { + t.Run(tc.final, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + refusal, err := status.New(codes.FailedPrecondition, "final refusal").WithDetails(&control.WorkspaceLeaseRefusal{Kind: tc.kind}) + if err != nil { + t.Fatal(err) + } + h, _ := exitAuthorityHost(t, func(s *exitAssignmentStream) { s.streamRefuse = refusal.Err() }) + for { + if _, final := h.MasterWaitState(); final == tc.final { + break + } + select { + case <-ctx.Done(): + t.Fatalf("the master's %s refusal never reached the host", tc.final) + case <-time.After(time.Millisecond): + } + } + e := newProcessExit(ctx) + if !chooseChunkStartupExit(e, flags{workspaceLease: true, durableImpl: "walstore-chunk", volumeID: "v"}, h, &exitNewerVersion{exitStartupOutcome{expired: true}}) { + t.Fatal("no startup decision") + } + if out := <-e.decision; out.code != tc.code || out.reason != tc.reason { + t.Fatalf("final %s with a newer HEAD version chose %+v; want %d %s", tc.final, out, tc.code, tc.reason) + } + }) + } +} diff --git a/seaweed-block/cmd/blockvolume/process_exit.go b/seaweed-block/cmd/blockvolume/process_exit.go index 87b8b6d4b7..410264bafc 100644 --- a/seaweed-block/cmd/blockvolume/process_exit.go +++ b/seaweed-block/cmd/blockvolume/process_exit.go @@ -274,6 +274,12 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar if identity, ok := p.(interface{ ChunkStartupIdentityRefused(string, uint64) bool }); ok && identity.ChunkStartupIdentityRefused(f.volumeID, gen) { out = workspaceExit{code: exitWorkspaceSuperseded, reason: "layout_identity_mismatch", detail: "VOLUME/HEAD disagrees with --layout-id; retry with the layout id from the master's volume record"} } + // A HEAD written by a newer version is permanent for this binary: exit 78, + // never the restartable 75 (a restart reads the same HEAD again). A master + // final reason below (moved, deleted, revoked) still names the exit. + if nv, ok := p.(interface{ ChunkStartupNewerVersion(string, uint64) bool }); ok && nv.ChunkStartupNewerVersion(f.volumeID, gen) { + out = workspaceExit{code: exitWorkspaceSuperseded, reason: "head_newer_version", detail: "HEAD was written by a newer version: run a newer binary"} + } if h != nil { // Typed MOVED/DELETED refusals exit 78 and a recorded revocation // (FINAL) exits 79 at once; both are permanent, @@ -287,11 +293,6 @@ func chooseChunkStartupExit(e *processExit, f flags, h *volume.Host, p chunkStar } } } - // A HEAD written by a newer version is permanent for this binary: exit 78, - // never the restartable 75 (a restart reads the same HEAD again). - if nv, ok := p.(interface{ ChunkStartupNewerVersion(string, uint64) bool }); ok && nv.ChunkStartupNewerVersion(f.volumeID, gen) { - out = workspaceExit{code: exitWorkspaceSuperseded, reason: "head_newer_version", detail: "HEAD was written by a newer version: run a newer binary"} - } if c, ok := p.(interface{ ChunkStartupCure(string, uint64) string }); ok { if cure := c.ChunkStartupCure(f.volumeID, gen); cure != "" { out.detail = cure From 2e9d6e04a75d4d5ea8376e7f01d4deb7e4abc888 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:12:45 -0800 Subject: [PATCH 44/51] authority: tests follow the lease deadline barrier; renewals write nothing Tests that pinned the removed horizon (barrier at the persisted issue+1.5*TTL, extension writes and their status counters) now use this process's deadline (or restart floor) plus skew. The golden wm lost range is the same file: the master restarts half a lease after the issue, so both versions' barriers are the same instant. Co-Authored-By: Claude Opus 5.5 --- .../core/authority/golden_v100_test.go | 7 ++- .../authority/workspace_delete_guard_test.go | 4 +- .../workspace_forced_admission_test.go | 2 +- .../authority/workspace_lease_horizon_test.go | 14 +++--- .../authority/workspace_lost_range_test.go | 12 ++--- .../core/authority/workspace_regrant_test.go | 12 ++--- .../workspace_renewal_slowstore_test.go | 11 +++-- .../core/authority/workspace_skew_test.go | 7 ++- .../core/authority/workspace_test.go | 8 +-- .../workspace_unclaimed_grant_test.go | 25 +++++----- .../core/authority/workspace_validity_test.go | 11 +++-- .../master/journal_isolation_fold_test.go | 49 +------------------ .../workspace_lease_refusal_kind_test.go | 8 +-- .../master/workspace_paused_grantee_test.go | 10 +++- .../master/workspace_renewal_boundary_test.go | 18 +++---- .../workspace_renewal_slowstore_test.go | 15 ++++-- .../core/host/master/workspace_skew_test.go | 2 +- .../master/workspace_unclaimed_grant_test.go | 5 +- 18 files changed, 95 insertions(+), 125 deletions(-) diff --git a/seaweed-block/core/authority/golden_v100_test.go b/seaweed-block/core/authority/golden_v100_test.go index c5dcc76721..2517e58811 100644 --- a/seaweed-block/core/authority/golden_v100_test.go +++ b/seaweed-block/core/authority/golden_v100_test.go @@ -112,7 +112,12 @@ func goldenWorkspace(t *testing.T, dir string) { if r, err := p.MoveWorkspace(ctx, goldenCleanMove("wm"), predecessorHead); err != nil || !r.Issued { t.Fatalf("clean move of wm: %+v %v", r, err) } - now = now.Add(grantTTL + grantTTL/2 + goldenWorkspaceSkew) + // The master restarts half a lease after the issue, so the forced move's + // barrier is the same instant on v1.0.0 (the persisted issue+1.5*TTL) and + // today (the restart floor, restart+TTL): wm's lost range is the same file. + now = now.Add(grantTTL / 2) + p = goldenWorkspacePublisher(store, &now) + now = now.Add(grantTTL + goldenWorkspaceSkew) if r, err := p.MoveWorkspace(ctx, goldenForcedMove("wm"), predecessorHead); err != nil || !r.Issued { t.Fatalf("forced move of wm: %+v %v", r, err) } diff --git a/seaweed-block/core/authority/workspace_delete_guard_test.go b/seaweed-block/core/authority/workspace_delete_guard_test.go index 1253646bb5..d4179c59f4 100644 --- a/seaweed-block/core/authority/workspace_delete_guard_test.go +++ b/seaweed-block/core/authority/workspace_delete_guard_test.go @@ -22,8 +22,8 @@ func TestDeletionReservationGuardSites(t *testing.T) { "publishIssuedLeaseLocked": true, "setLeaseDeadlineLocked": true, "RenewWorkspaceLease": true, "regrantWorkspaceLease": true, // Reply-only copies never increase published validity. - "WorkspaceLeaseReply": true, "AckWorkspaceRevocation": true, - // Copies the published horizon into the leaf view under mu -> leaseMu. + "WorkspaceLeaseReply": true, + // Copies the persisted lease into the leaf view under mu -> leaseMu. "deriveLeaseLocked": true, // Positive lease construction and publication, or a plain clone. "newWorkspaceLease": true, "firstWorkspaceGrant": true, diff --git a/seaweed-block/core/authority/workspace_forced_admission_test.go b/seaweed-block/core/authority/workspace_forced_admission_test.go index 39329f88fc..41bc3cb2c9 100644 --- a/seaweed-block/core/authority/workspace_forced_admission_test.go +++ b/seaweed-block/core/authority/workspace_forced_admission_test.go @@ -15,7 +15,7 @@ func TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission(t *testing.T) { disk, _ := newTempStore(t) now := time.Unix(1000, 0) p, issued := cleanMoveToGrantee(t, disk, &now) - barrier := issued.Add(grantTTL + grantTTL/2 + p.workspaceSkew(p.WorkspaceState("v").Lease)) + barrier := issued.Add(grantTTL + p.workspaceSkew(p.WorkspaceState("v").Lease)) now = barrier.Add(-time.Nanosecond) if err := p.WorkspaceForcedMoveAdmitted(ctx, "v", "forced", "r", 2); err == nil || !strings.Contains(err.Error(), "expiry plus clock-skew margin has not elapsed") { t.Fatalf("admitted before expiry+skew: %v", err) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 53e1837b77..d34bf1dcd5 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -115,9 +115,9 @@ func forcedMove(volume, id string) (WorkspaceMoveRequest, WorkspaceHead) { } // The view equals derive(published) after every writer kind: bind, first -// grant, extension, endpoint refresh, revocation, ACK, clean move issue, a -// move reservation whose issue write fails (uncertain via apply), a failed -// extension (uncertain via persistWorkspaceLocked), reload and close. +// grant, renewal, endpoint refresh, revocation, ACK, clean move issue, a +// move reservation whose issue write fails (uncertain via apply), reload and +// close. func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { disk, _ := newTempStore(t) hs := &hookStore{AuthorityStore: disk} @@ -147,10 +147,10 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != c.sec(55).UnixNano() || got <= firstH { - t.Fatalf("extension did not publish trigger+1.5*TTL: %d", got) + if got := p.WorkspaceState("v").Lease.ExpiresAtNS; got != firstH { + t.Fatalf("a renewal changed the persisted lease: %d, was %d", got, firstH) } - check("extension") + check("renewal") if err := p.apply(AssignmentAsk{VolumeID: "v", ReplicaID: "r", DataAddr: "d2", CtrlAddr: "c", Intent: IntentRefreshEndpoint}); err != nil { t.Fatal(err) } @@ -174,7 +174,7 @@ func TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter(t *testing.T) { t.Fatalf("move issue deadline %s; want the new holder's issue+TTL %s", got, c.sec(40)) } // w: forced move whose issue write fails after the reservation persisted. - c.at(30 + 15 + 20 + 1) // past w's horizon (45) + skew (20) + c.at(30 + 20 + 1) // past w's deadline (30) + skew (20) hs.setBefore(func(r DurableRecord) error { if r.VolumeID == "w" && r.Workspace != nil && len(r.Workspace.Moves) > 0 && r.Workspace.Moves[len(r.Workspace.Moves)-1].Issued { return errors.New("injected issue write failure") diff --git a/seaweed-block/core/authority/workspace_lost_range_test.go b/seaweed-block/core/authority/workspace_lost_range_test.go index 8f1a197677..f7e1dd47a8 100644 --- a/seaweed-block/core/authority/workspace_lost_range_test.go +++ b/seaweed-block/core/authority/workspace_lost_range_test.go @@ -32,11 +32,9 @@ func forcedLostRangeFixture(t *testing.T, store AuthorityStore, restart bool) (p if restart && !p.leaseDeadlineLockedForTest("v").After(time.Unix(0, lease.ExpiresAtNS)) { t.Fatal("fixture: the restart deadline is not the later barrier term") } - barrier = time.Unix(0, lease.ExpiresAtNS) - if d := p.leaseDeadlineLockedForTest("v"); d.After(barrier) { - barrier = d - } - return p, now, barrier.Add(p.workspaceSkew(lease)) + // The barrier is this process's deadline (the grant's, or after a + // restart its floor) plus skew; the persisted ExpiresAtNS is not a term. + return p, now, p.leaseDeadlineLockedForTest("v").Add(p.workspaceSkew(lease)) } var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, @@ -44,8 +42,8 @@ var forcedLostRangeReq = WorkspaceMoveRequest{RequestID: "f", VolumeID: "v", Exp var forcedLostRangeHead = WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} // A forced move records the abandoned range beside its record: the kept HEAD -// frontier and the forced barrier (lease horizon, or after a restart the -// later restart deadline, plus skew) as the latest master time an old-holder +// frontier and the forced barrier (the lease deadline, or after a restart +// the restart floor, plus skew) as the latest master time an old-holder // write can have been acknowledged. A reload returns it; the move record's // own encoding is unchanged, so older binaries still verify and load it. func TestWorkspaceForcedMoveRecordsTheLostRange(t *testing.T) { diff --git a/seaweed-block/core/authority/workspace_regrant_test.go b/seaweed-block/core/authority/workspace_regrant_test.go index 3ab7d5849c..220ea95bc2 100644 --- a/seaweed-block/core/authority/workspace_regrant_test.go +++ b/seaweed-block/core/authority/workspace_regrant_test.go @@ -216,14 +216,14 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) { p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(10*time.Second, clock.now), WithWorkspaceMaxClockSkew(4*time.Second)) grant := bindAndGrant(t, p, "v", "r") if grant.ExpiresAtNS != clock.sec(10).UnixNano() || p.WorkspaceState("v").Lease.ExpiresAtNS != clock.sec(15).UnixNano() { - t.Fatal("fixture did not create the declared grant/horizon", grant) + t.Fatal("fixture did not create the declared grant and record", grant) } writes := 0 store.setBefore(func(DurableRecord) error { writes++; return nil }) - // The deadline+skew boundary is 14 s; horizon+skew is 19 s. - // Re-grant uses the same MAX barrier as a forced move, including the - // interval after the shorter deadline has passed and its final ns. - for _, now := range []time.Time{clock.sec(13), clock.sec(14), clock.sec(19).Add(-time.Nanosecond)} { + // The barrier is deadline+skew, 14 s; the persisted record's 15 s is + // not a term. Re-grant uses the same barrier as a forced move, including + // the interval after the deadline has passed and its final ns. + for _, now := range []time.Time{clock.sec(10), clock.sec(13), clock.sec(14).Add(-time.Nanosecond)} { clock.ns.Store(now.UnixNano()) if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil { t.Fatal("re-grant crossed the later expiry/skew boundary early", now, got) @@ -235,7 +235,7 @@ func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) { t.Fatal("unsafe early re-grant attempted persistence", writes) } } - clock.at(19) + clock.at(14) if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "force", "r", 1); err != nil { t.Fatal("fixture did not reach the shared forced-move barrier", err) } diff --git a/seaweed-block/core/authority/workspace_renewal_slowstore_test.go b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go index 41b7a9a822..e05a25e1e6 100644 --- a/seaweed-block/core/authority/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/authority/workspace_renewal_slowstore_test.go @@ -27,7 +27,8 @@ func (s *slowLeaseStore) Put(r DurableRecord) error { // A renewal of a live lease must not wait for the authority store's fsync: // the host's renewal RPC times out after 2 s, so a slower store write on the -// renewal path turns into a host fence and a volume shutdown (issue #205). +// renewal path turns into a host fence and a volume shutdown (issue #205). A +// renewal writes nothing, so it never reaches the stalled store. func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) { disk, _ := newTempStore(t) slow := &slowLeaseStore{AuthorityStore: disk} @@ -57,8 +58,8 @@ func TestWorkspaceRenewalDoesNotWaitForSlowStore(t *testing.T) { t.Fatalf("renewal of a live lease took %s behind a 2.5 s store write; the host's renewal RPC times out at 2 s", took.Round(time.Millisecond)) } t.Logf("renewal took %s", took) - if slow.puts.Load() == 0 { - t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it") + if slow.puts.Load() != 0 { + t.Fatalf("a renewal of a live lease wrote %d lease records; it writes nothing", slow.puts.Load()) } } @@ -113,8 +114,8 @@ func TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore(t *testing.T) { t.Fatalf("slowest of %d concurrent renewals took %s (all: %v); renewals serialize behind each other's store writes", n, slowest.Round(time.Millisecond), took) } t.Logf("slowest of %d concurrent renewals took %s", n, slowest) - if slow.puts.Load() == 0 { - t.Fatal("no lease write went through the 0.5 s stall: the test did not exercise it") + if slow.puts.Load() != 0 { + t.Fatalf("renewals of live leases wrote %d lease records; they write nothing", slow.puts.Load()) } } diff --git a/seaweed-block/core/authority/workspace_skew_test.go b/seaweed-block/core/authority/workspace_skew_test.go index 69b4c733c6..0a577b4fb6 100644 --- a/seaweed-block/core/authority/workspace_skew_test.go +++ b/seaweed-block/core/authority/workspace_skew_test.go @@ -23,10 +23,9 @@ func TestWorkspaceClockSkewPersistsAndProtectsRestart(t *testing.T) { if lease.MaxClockSkewNS != int64(4*time.Second) { t.Fatal("configured margin not in durable grant", lease) } - // The first grant persists the durable horizon start+1.5*TTL (9 s), - // the upper bound of every later grant; the forced barrier is - // horizon + skew, TTL/2 later than the grant itself (#205). - boundary := start.Add(9*time.Second + 4*time.Second) + // The forced barrier is the grant's deadline (start+TTL) plus the + // persisted skew; after a restart, the restart floor plus it. + boundary := start.Add(6*time.Second + 4*time.Second) if restart { now = start.Add(7 * time.Second) p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(6*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(time.Second)) diff --git a/seaweed-block/core/authority/workspace_test.go b/seaweed-block/core/authority/workspace_test.go index bd494aa6cd..1eea79dd80 100644 --- a/seaweed-block/core/authority/workspace_test.go +++ b/seaweed-block/core/authority/workspace_test.go @@ -35,7 +35,7 @@ func TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant(t *testing.T) { if _, err := p.RenewWorkspaceLease(context.Background(), "v", "old", 1); err != nil { t.Fatal(err) } - // Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205). + // Past the grant's deadline plus skew. now = now.Add(3 * time.Second) req := WorkspaceMoveRequest{RequestID: "m", VolumeID: "v", ExpectedReplicaID: "old", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetReplicaID: "old", TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old-node/old", RemoteLSN: 42} @@ -172,7 +172,9 @@ func TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry(t *testing.T) { if _, err := p.MoveWorkspace(ctx, req, head); err == nil { t.Fatal("unexpired lease moved") } - now = now.Add(2 * time.Second) + // Past the deadline, before deadline plus skew: the expired holder is + // not re-granted (a re-grant waits for the move barrier). + now = now.Add(1500 * time.Millisecond) if _, err := p.RenewWorkspaceLease(ctx, "v", "old", 1); err == nil { t.Fatal("expired host renewed") } @@ -236,7 +238,7 @@ func TestWorkspaceMoveUsesQualifiedHEADHolder(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "same", 1); err != nil { t.Fatal(err) } - // Past the durable horizon (1.5*TTL) plus skew, not only the grant (#205). + // Past the grant's deadline plus skew. now = now.Add(3 * time.Second) q := WorkspaceMoveRequest{RequestID: "qualified", VolumeID: "v", ExpectedReplicaID: "same", TargetReplicaID: "same", ExpectedHost: "old-node", TargetHost: "new-node", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} for _, holder := range []string{"same", "other-node/same", "old-node/other"} { diff --git a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go index bbc19d9c75..70c7535b43 100644 --- a/seaweed-block/core/authority/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/authority/workspace_unclaimed_grant_test.go @@ -94,12 +94,15 @@ func TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry(t *testing.T) { assertLeaseViewMatches(t, p, "after restart") } skew := p.workspaceSkew(p.WorkspaceState("v").Lease) - // The horizon (issue+1.5*TTL) is the later bound: the deadline is - // issue+TTL, or restart+TTL after a restart 0.2*TTL later. - barrier := issued.Add(grantTTL + grantTTL/2 + skew) + // The deadline is issue+TTL, or the restart floor restart+TTL + // after a restart 0.2 s later; the barrier is it plus skew. + barrier := issued.Add(grantTTL + skew) + if restart { + barrier = barrier.Add(200 * time.Millisecond) + } // The predecessor's lease (renewed 0.1 s before the issue) has // expired plus skew by then: only the grant's lease may admit. - if old := issued.Add(-100*time.Millisecond + grantTTL + grantTTL/2 + skew); !barrier.Add(-time.Nanosecond).After(old) { + if old := issued.Add(-100*time.Millisecond + grantTTL + skew); !barrier.Add(-time.Nanosecond).After(old) { t.Fatal("test clock does not separate the predecessor's barrier from the grant's") } now = barrier.Add(-time.Nanosecond) @@ -214,17 +217,15 @@ func TestWorkspaceUnclaimedGrantGranteeRenewsNormally(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err == nil { t.Fatal("old epoch renewed after the move") } - // Past 0.25*TTL the renewal starts an extension of the issued lease. + // A later renewal moves the deadline and writes nothing: the persisted + // lease stays the one the issue wrote. now = issued.Add(grantTTL / 2) - if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil { - t.Fatal(err) + if l, err := p.RenewWorkspaceLease(ctx, "v", "r", 2); err != nil || l.ExpiresAtNS != now.Add(grantTTL).UnixNano() { + t.Fatal("later renewal:", l, err) } st := p.WorkspaceState("v") - for wait := time.Now().Add(5 * time.Second); time.Now().Before(wait) && (st.Lease == nil || st.Lease.ExpiresAtNS == issued.Add(grantTTL+grantTTL/2).UnixNano()); st = p.WorkspaceState("v") { - time.Sleep(5 * time.Millisecond) - } - if st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != now.Add(grantTTL+grantTTL/2).UnixNano() { - t.Fatalf("issued lease not extended: %+v", st.Lease) + if store.puts.Load() != writes || st.Lease == nil || st.Lease.Epoch != 2 || st.Lease.ExpiresAtNS != issued.Add(grantTTL+grantTTL/2).UnixNano() { + t.Fatalf("a renewal wrote: %d records, lease %+v", store.puts.Load()-writes, st.Lease) } if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 2 || len(st.Moves) != 1 { t.Fatal("renewals changed authority", line) diff --git a/seaweed-block/core/authority/workspace_validity_test.go b/seaweed-block/core/authority/workspace_validity_test.go index c07443f731..53ffbe58d6 100644 --- a/seaweed-block/core/authority/workspace_validity_test.go +++ b/seaweed-block/core/authority/workspace_validity_test.go @@ -16,9 +16,9 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) { {"before", 28*time.Second - time.Nanosecond, true, false}, {"at", 28 * time.Second, false, false}, {"after", 29 * time.Second, false, false}, - {"horizon-before", 43*time.Second - time.Nanosecond, true, true}, - {"horizon-at", 43 * time.Second, false, true}, - {"horizon-after", 44 * time.Second, false, true}, + {"restart-before", 48*time.Second - time.Nanosecond, true, true}, + {"restart-at", 48 * time.Second, false, true}, + {"restart-after", 49 * time.Second, false, true}, } { t.Run(tc.name, func(t *testing.T) { disk, _ := newTempStore(t) @@ -36,8 +36,9 @@ func TestWorkspaceAckUsesGrantedHalfSkewBoundary(t *testing.T) { t.Fatal(err) } if tc.restart { - // Reopening at +20s gives a restart deadline of +50s, beyond - // the persisted +45s horizon. ACK must stop at +43s. + // Reopening at +20s gives a restart floor of +50s, beyond the + // persisted record's +45s: the ACK follows the floor and stops + // at +48s (the floor minus half the skew). now = start.Add(20 * time.Second) p = NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(30*time.Second, func() time.Time { return now }), WithWorkspaceMaxClockSkew(4*time.Second)) p.mu.Lock() diff --git a/seaweed-block/core/host/master/journal_isolation_fold_test.go b/seaweed-block/core/host/master/journal_isolation_fold_test.go index 9eb5ce8ab3..f751038ae3 100644 --- a/seaweed-block/core/host/master/journal_isolation_fold_test.go +++ b/seaweed-block/core/host/master/journal_isolation_fold_test.go @@ -2,13 +2,11 @@ package master import ( "context" - "encoding/json" "fmt" "io" "log" "net" - "net/http" - "net/http/httptest" + "path/filepath" "strings" "sync" @@ -301,51 +299,6 @@ func TestHostCloseForceClosesAStalledStatusConnection(t *testing.T) { } } -// The status endpoint carries the extension write latency: -1 before any -// extension, then the measured write once a renewal past 1.25 TTL of -// headroom (7.5 s after the first grant, TTL 30 s) has started one. -func TestStatusReportsExtensionWriteLatency(t *testing.T) { - h, c, _ := reviewBindingHost(t) - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - defer cancel() - reviewLegacyBind(t, h, c, ctx, "vol-b") - line := waitAuthorityLine(t, h.Publisher(), "vol-b") - svc := &services{host: h} - id := &control.WorkspaceIdentity{ServerId: "node-a", VolumeId: "vol-b", ReplicaId: line.ReplicaID, Epoch: line.Epoch} - if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil { - t.Fatal(err) // first grant: not an extension - } - get := func() map[string]any { - t.Helper() - rec := httptest.NewRecorder() - h.statusHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/status/workspace-lease", nil)) - var body map[string]any - if err := json.NewDecoder(rec.Body).Decode(&body); err != nil { - t.Fatal(err) - } - return body - } - if b := get(); b["extension_write_last_ms"] != float64(-1) || b["extension_write_max_last_minute_ms"] != float64(-1) { - t.Fatalf("before any extension: %v", b) - } - time.Sleep(8 * time.Second) - if _, err := svc.RenewWorkspaceLease(loopbackPeer(ctx), id); err != nil { - t.Fatal(err) - } - for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(20 * time.Millisecond) { - b := get() - last, _ := b["extension_write_last_ms"].(float64) - max, _ := b["extension_write_max_last_minute_ms"].(float64) - if last >= 0 && max >= last { - t.Logf("extension write: last %v ms, max in the last minute %v ms", last, max) - return - } - if time.Now().After(deadline) { - t.Fatalf("no extension write reported: %v", b) - } - } -} - // With a known file system id on both sides, machine id + device alone no // longer make a node co-located: a different fsid is another file system. // The same three facts are co-located; a heartbeat without an fsid (an older diff --git a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go index 3ca08c2168..b9849c3dd5 100644 --- a/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go +++ b/seaweed-block/core/host/master/workspace_lease_refusal_kind_test.go @@ -86,15 +86,15 @@ func TestLeaseRefusalKinds(t *testing.T) { t.Fatal("first grant:", err) } - // BARRIER: past the grant (TTL) but before the horizon (1.5 TTL) plus - // the default skew (2/3 TTL), i.e. 65 s after the grant. + // BARRIER: past the grant (TTL, 30 s) but before it plus the default + // skew (2/3 TTL), i.e. 50 s after the grant. nowNS.Add(int64(40 * time.Second)) text, r := refusalOf(t, "expired re-grant before the barrier", func() error { _, err := ws.RenewWorkspaceLease(ctx, e1); return err }()) if r == nil || r.GetKind() != control.WorkspaceLeaseRefusal_BARRIER { t.Fatalf("re-grant before the barrier: detail %v; want BARRIER", r) } - if left := time.Duration(r.GetRetryAfterNs()); left < 24*time.Second || left > 26*time.Second { - t.Fatalf("BARRIER retry_after %v; want 25 s (the barrier 65 s after the grant, now +40 s)", left) + if left := time.Duration(r.GetRetryAfterNs()); left < 9*time.Second || left > 11*time.Second { + t.Fatalf("BARRIER retry_after %v; want 10 s (the barrier 50 s after the grant, now +40 s)", left) } if !strings.HasPrefix(text, "workspace forced move lease expiry plus clock-skew margin has not elapsed") || !strings.Contains(text, "re-grant refused until") { t.Fatalf("BARRIER text %q: want the barrier text with its time", text) diff --git a/seaweed-block/core/host/master/workspace_paused_grantee_test.go b/seaweed-block/core/host/master/workspace_paused_grantee_test.go index f80f0b36bc..6abc463422 100644 --- a/seaweed-block/core/host/master/workspace_paused_grantee_test.go +++ b/seaweed-block/core/host/master/workspace_paused_grantee_test.go @@ -85,7 +85,12 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil { t.Fatal(err) } - oldBarrier := time.Unix(0, p.WorkspaceState("v").Lease.ExpiresAtNS) + // The predecessor's deadline (this process's grant, not the record's). + oldLease, ok := p.WorkspaceLeaseReply("v") + if !ok { + t.Fatal("no predecessor lease") + } + oldBarrier := time.Unix(0, oldLease.ExpiresAtNS) fixture := testutil.NewLayoutFixture(t, "v", 64, 4) readHead := func() authority.WorkspaceHead { @@ -176,7 +181,8 @@ func TestWorkspacePausedGranteeRefusedAtAttach(t *testing.T) { t.Fatalf("grantee lease %+v", lease) } skew := time.Duration(lease.MaxClockSkewNS) - grantBarrier := time.Unix(0, lease.ExpiresAtNS).Add(skew) + granted, _ := p.WorkspaceLeaseReply("v") // the grantee's deadline after its renewal + grantBarrier := time.Unix(0, granted.ExpiresAtNS).Add(skew) forced := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "new-node", TargetHost: "third-node", ExpectedEpoch: 2, TargetDataAddr: "td", TargetCtrlAddr: "tc", Kind: "forced", Force: true} diff --git a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go index f49a9629ea..e11777d67d 100644 --- a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go @@ -101,13 +101,13 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { case <-ctx.Done(): t.Fatal("renewal did not enter", ctx.Err()) } - // A renewal is answered from memory: the grant is in the reply, and - // the durable lease holds the horizon (>= every grant), so the - // persisted expiry is not the grant any more (#205). + // A renewal is answered from memory: the grant is in the reply and + // nothing is written, so the persisted lease is still the first + // grant's record. renewed := *p.WorkspaceState("v").Lease freshEarly := requestStart.Add(time.Duration(reply.ValidForNs)) if freshEarly.Sub(oldEarly) < time.Second || reply.ExpiresAtNs <= client.initial.ExpiresAtNs || renewed.ExpiresAtNS < reply.ExpiresAtNs || renewed.MaxClockSkewNS != int64(4*time.Second) { - t.Fatal("fixture did not extend the grant under the durable horizon", client.initial, reply, oldLease, renewed) + t.Fatal("fixture did not extend the grant", client.initial, reply, oldLease, renewed) } arrival := oldEarly.Add(-time.Second) if late { @@ -140,14 +140,10 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { } q := authority.WorkspaceMoveRequest{RequestID: "renewed-forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} - // The barrier is max(durable horizon, renewed grant) + skew; the old + // The barrier is the renewed grant + the persisted skew; the old // grant's expiry plus skew is still too early. - barrierBase := renewed.ExpiresAtNS - if reply.ExpiresAtNs > barrierBase { - barrierBase = reply.ExpiresAtNs - } - boundary := time.Unix(0, barrierBase).Add(time.Duration(renewed.MaxClockSkewNS)) - for _, when := range []time.Time{time.Unix(0, client.initial.ExpiresAtNs).Add(4 * time.Second), time.Unix(0, reply.ExpiresAtNs).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { + boundary := time.Unix(0, reply.ExpiresAtNs).Add(time.Duration(renewed.MaxClockSkewNS)) + for _, when := range []time.Time{time.Unix(0, client.initial.ExpiresAtNs).Add(4 * time.Second), boundary.Add(-time.Nanosecond)} { masterNS.Store(when.UnixNano()) if _, err := p.MoveWorkspace(ctx, q, head); err == nil { t.Fatal("forced move ignored renewed expiry plus persisted margin") diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go index 774b7b93e5..48ed6adcdb 100644 --- a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -172,7 +172,8 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { // Every lease write is now held until a renewal succeeded during its hold, // so a renewal that waited for the store would deadlock this test. The - // sampler records any fence while armed; three held writes must complete. + // sampler records any fence while armed; four renewals must succeed (about + // 5 s), and none of them may write the lease (a renewal writes nothing). var fenced atomic.Bool var sinceOKAtFence atomic.Int64 // time since the latest successful renewal when the fence was first seen sampled := make(chan struct{}) @@ -188,14 +189,20 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { time.Sleep(20 * time.Millisecond) } }() - for slow.held.Load() < 3 { - if fenced.Load() { + base := slow.renewals.Load() + for wait := time.Now().Add(30 * time.Second); slow.renewals.Load() < base+4 && !fenced.Load(); time.Sleep(20 * time.Millisecond) { + if time.Now().After(wait) { break } - time.Sleep(20 * time.Millisecond) } slow.armed.Store(false) <-sampled + if n := slow.renewals.Load() - base; n < 4 && !fenced.Load() { + t.Fatalf("only %d renewals succeeded in 30 s while armed", n) + } + if n := slow.gen.Load(); n != 0 { + t.Fatalf("renewals wrote the lease %d times while armed; a renewal writes nothing", n) + } if fenced.Load() || !g.Projection().Healthy || stops.Load() != 0 { // The gaps tell a starved runner (a gap near the 4 s validity) from a // guard that fenced although renewals kept succeeding in time. diff --git a/seaweed-block/core/host/master/workspace_skew_test.go b/seaweed-block/core/host/master/workspace_skew_test.go index 7292f5f817..5673fd3ace 100644 --- a/seaweed-block/core/host/master/workspace_skew_test.go +++ b/seaweed-block/core/host/master/workspace_skew_test.go @@ -50,7 +50,7 @@ func TestWorkspaceSkewSeparatesOldServingFromForcedGrant(t *testing.T) { if err := g.Refresh(context.Background()); err != nil { t.Fatal(err) } - lease := p.WorkspaceState("v").Lease + lease, _ := p.WorkspaceLeaseReply("v") // this process's deadline for the grant q := authority.WorkspaceMoveRequest{RequestID: "forced", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true} head := authority.WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42} if check == "host-early-fence" { diff --git a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go index 74ae751d38..32d2a9c35a 100644 --- a/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go +++ b/seaweed-block/core/host/master/workspace_unclaimed_grant_test.go @@ -35,7 +35,7 @@ func seedDetachedHead(t *testing.T, ctx context.Context, remote *storage.MemChun // then) and is granted on the predecessor's unchanged HEAD. A late claim by // the dead grantee never displaces the new owner's higher epoch. func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { - // The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s. + // The real lease (the 30 s TTL) plus skew takes ~50 s. ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) defer cancel() remote := storage.NewMemChunkRemote() @@ -114,7 +114,8 @@ func TestWorkspaceUnclaimedGrantForcedReassignOverRPC(t *testing.T) { if st == nil || st.Lease == nil || st.Lease.ReplicaID != "r1" || st.Lease.Epoch != grantee || st.Lease.Revoking { t.Fatalf("the issued move must start node-b's lease: %+v", st) } - barrier := time.Unix(0, st.Lease.ExpiresAtNS).Add(skew) + granted, _ := m.Publisher().WorkspaceLeaseReply("vol-a") // the issue's deadline, not the record's + barrier := time.Unix(0, granted.ExpiresAtNS).Add(skew) if q, err := ws.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: "vol-a"}); err != nil || q.GetLease() == nil || q.GetLease().GetEpoch() != grantee { t.Fatalf("QueryWorkspace after the issue: %+v %v", q.GetLease(), err) } From e7380482a8732a1e2210f03f0ed322646969eca7 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:17:57 -0800 Subject: [PATCH 45/51] blockvolume: real-systemd red for the newer-format exits Under the shipped unit's restart policy, a holder that meets a local store or a HEAD written by a newer format exits 78 with its reason and is not started again; the store's bytes and HEAD stay as they were; the control, a process of the same policy exiting 1, is restarted. Prebuilt binaries of the same tree can stand in for the build on a host without Go. Co-Authored-By: Claude Opus 5.5 --- .../newer_format_systemd_integration_test.go | 232 ++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go diff --git a/seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go b/seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go new file mode 100644 index 0000000000..6cf93b7932 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/newer_format_systemd_integration_test.go @@ -0,0 +1,232 @@ +//go:build linux && subprocess && chunkstore_integration && systemd_integration + +package main_test + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "fmt" + "hash/crc32" + "os" + "os/exec" + "path" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/rpc/lifecycleclient" + "github.com/seaweedfs/seaweed-block/core/rpc/link" + "google.golang.org/grpc" +) + +// Under the shipped unit's restart policy (Restart=on-failure, +// RestartPreventExitStatus=78 79), a holder that meets a local store or a +// HEAD written by a newer format exits 78 with its reason and systemd does +// not start it again: zero restarts after the restart interval, and the +// store's bytes and HEAD's record unchanged. The control: a process of the +// same unit policy that exits 1 is restarted. +func TestSystemdNewerFormatExits78WithoutRestart(t *testing.T) { + if os.Getenv("GAP1_SYSTEMD_AUTHORIZED") != "1" { + t.Fatal("explicit real-systemd qualification authorization required; no skip counts as proof") + } + if os.Geteuid() != 0 { + t.Fatal("systemd qualification needs root") + } + if os.Getenv("CHUNKSTORE_WEED") == "" { + t.Fatal("real CHUNKSTORE_WEED binary required") + } + if err := os.MkdirAll(durable.HostVolumeLockDir, 0o700); err != nil { + t.Fatalf("host volume lock directory: %v", err) + } + fixture := newGAP1Fixture(t) + root := fixture.root + bin := filepath.Join(root, "bin") + if err := os.Mkdir(bin, 0755); err != nil { + t.Fatal(err) + } + for _, name := range []string{"blockvolume", "blockmaster"} { + if pre := os.Getenv("SWB_PREBUILT_BIN"); pre != "" { // a host without a Go toolchain: binaries of the same commit + raw, err := os.ReadFile(filepath.Join(pre, name)) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(bin, name), raw, 0o755); err != nil { + t.Fatal(err) + } + continue + } + buildCtx, buildCancel := context.WithTimeout(context.Background(), 2*time.Minute) + cmd := exec.CommandContext(buildCtx, "go", "build", "-p", "4", "-o", filepath.Join(bin, name), "../"+name) + cmd.WaitDelay = time.Second + out, err := cmd.CombinedOutput() + buildCancel() + if err != nil { + t.Fatalf("real binary build: %v %s", err, out) + } + } + shipped := gap1ShippedPolicy(t) + stem := fmt.Sprintf("newerfmt-%d", time.Now().UnixNano()) + + // Control: the same unit policy restarts a process that exits 1. + control1 := stem + "-exit1" + fixture.start(t, control1, true, "/bin/sh", "-c", "exit 1") + waitGAP1(t, "control: an exit 1 was not restarted under the shipped policy", 30*time.Second, func() bool { + return gap1Unit(t, control1)["NRestarts"] != "0" + }) + restarts := gap1Unit(t, control1)["NRestarts"] // read before the stop, which resets it + gap1Systemctl(t, "stop", control1) + t.Logf("control: exit 1 restarted (NRestarts=%s) under Restart=%s RestartPreventExitStatus=%s", restarts, shipped["Restart"], shipped["RestartPreventExitStatus"]) + + cluster := startWorkspaceWeedAt(t, filepath.Join(root, "weed")) + gap1PreserveFailure(t, root, cluster.dir) + volume := stem + base := "/" + stem + masterAddr := leaseBinaryAddress(t) + target, masterListen := gap1TargetAddresses(t, masterAddr) + dataAddr, ctrlAddr, statusAddr, nvmeAddr := leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t), leaseBinaryAddress(t) + cfg := fmt.Sprintf("nodes:\n - server_id: s1\n data_addr: %s\n ctrl_addr: %s\n - server_id: s2\n data_addr: %s\n ctrl_addr: %s\nvolumes:\n - id: %s\n size_bytes: 262144\n replication_factor: 1\n placements:\n - server_id: s1\n replica_id: r1\n source: existing_replica\n", dataAddr, ctrlAddr, target.dataAddr, target.ctrlAddr, volume) + spec := filepath.Join(root, "cluster.yaml") + if err := os.WriteFile(spec, []byte(cfg), 0600); err != nil { + t.Fatal(err) + } + tlsDir := gap1WriteTLS(t, root, target) + fixture.start(t, stem+"-master", false, filepath.Join(bin, "blockmaster"), + "--listen", masterListen, "--tls-cert", filepath.Join(tlsDir, "master.crt"), "--tls-key", filepath.Join(tlsDir, "master.key"), + "--tls-client-ca", filepath.Join(tlsDir, "ca.crt"), "--role-file", filepath.Join(tlsDir, "roles"), "--audit-log", filepath.Join(tlsDir, "audit.log"), "--authority-store", filepath.Join(root, "auth"), "--lifecycle-store", filepath.Join(root, "life"), + "--cluster-spec", spec, "--lifecycle-product-loop-interval", "200ms", "--expected-slots-per-volume", "1", + "--workspace-rpc", "--chunk-filer", cluster.filerGRPC, "--chunk-path", base) + w4WaitTCP(t, masterAddr, 20*time.Second) + admin, err := link.ClientCredentials(link.TLSFiles{Cert: filepath.Join(tlsDir, "admin.crt"), Key: filepath.Join(tlsDir, "admin.key"), CA: filepath.Join(tlsDir, "ca.crt")}, "") + if err != nil { + t.Fatal(err) + } + conn, err := grpc.NewClient(masterAddr, admin) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + var layoutID layout.VolumeID + waitGAP1(t, "master never resolved the volume's layout identity", 20*time.Second, func() bool { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + id, e := lifecycleclient.ResolveVolume(ctx, control.NewLifecycleServiceClient(conn), volume) + layoutID = id + return e == nil + }) + store := filepath.Join(root, "store") + args := []string{"--master", masterAddr, "--server-id", "s1", + "--master-tls-cert", filepath.Join(tlsDir, "s1.crt"), "--master-tls-key", filepath.Join(tlsDir, "s1.key"), "--master-ca", filepath.Join(tlsDir, "ca.crt"), + "--volume-id", volume, "--replica-id", "r1", "--layout-id", layoutID.String(), + "--data-addr", dataAddr, "--ctrl-addr", ctrlAddr, "--heartbeat-interval", "200ms", "--t1-readiness", "--status-addr", statusAddr, + "--durable-root", store, "--durable-impl", "walstore-chunk", "--durable-blocks", "64", + "--chunk-filer", cluster.filerGRPC, "--chunk-path", base, "--chunk-control-endpoint", "--workspace-lease", + "--nvme-listen", nvmeAddr, "--nvme-subsysnqn", "nqn.2026-11.test:" + stem} + bootstrap := stem + "-bootstrap" + fixture.start(t, bootstrap, false, filepath.Join(bin, "blockvolume"), args...) + waitGAP1(t, "bootstrap did not attach under a real lease", 60*time.Second, func() bool { return gap1Operational(t, statusAddr, volume) }) + gap1Systemctl(t, "stop", bootstrap) + waitGAP1(t, "bootstrap still running", 30*time.Second, func() bool { return gap1Unit(t, bootstrap)["MainPID"] == "0" }) + + // refusedOnce starts a restarting unit and requires it to exit 78 with + // reason, then stay down past the restart interval with zero restarts. + refusedOnce := func(unit, reason string) { + t.Helper() + fixture.start(t, unit, true, filepath.Join(bin, "blockvolume"), args...) + waitGAP1(t, unit+": never exited 78", 120*time.Second, func() bool { + u := gap1Unit(t, unit) + return u["MainPID"] == "0" && u["ExecMainStatus"] == "78" + }) + time.Sleep(12 * time.Second) // past RestartSec (shipped 5s), twice + u := gap1Unit(t, unit) + if u["NRestarts"] != "0" || u["ExecMainStatus"] != "78" || u["MainPID"] != "0" { + t.Fatalf("%s: restarted or running after its 78: %+v", unit, u) + } + out, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-o", "cat").CombinedOutput() + if want := "exiting status=78 reason=" + reason; !strings.Contains(string(out), want) { + t.Fatalf("%s: journal lacks %q:\n%s", unit, want, out) + } + t.Logf("%s: exit 78 %s, NRestarts=0 after %s", unit, reason, shipped["RestartSec"]) + gap1Systemctl(t, "reset-failed", unit) + } + + // 1. The local store written by a newer format: both descriptor slots + // carry the chunk-state marker above what this binary reads. + var storeFile string // the one file under the durable root that starts with the store's superblock magic + if err := filepath.Walk(store, func(p string, fi os.FileInfo, err error) error { + if err != nil || !fi.Mode().IsRegular() || fi.Size() < 8192 { + return err + } + head := make([]byte, 4) + if f, err := os.Open(p); err == nil { + _, _ = f.Read(head) + _ = f.Close() + } + if string(head) == "SWBK" { + if storeFile != "" { + t.Fatalf("two stores under %s: %s, %s", store, storeFile, p) + } + storeFile = p + } + return nil + }); err != nil { + t.Fatal(err) + } + if storeFile == "" { + t.Fatalf("no store under %s", store) + } + original, err := os.ReadFile(storeFile) + if err != nil { + t.Fatal(err) + } + marked := append([]byte(nil), original...) + for _, off := range []int{0, 4096} { // descriptor slots A and B, 4096 bytes each, CRC32C in the last 4 + slot := marked[off : off+4096] + binary.LittleEndian.PutUint16(slot[306:], 9) // a chunk-state format newer than any this binary reads + binary.LittleEndian.PutUint64(slot[312:], 1) + binary.LittleEndian.PutUint32(slot[4092:], crc32.Checksum(slot[:4092], crc32.MakeTable(crc32.Castagnoli))) + } + if err := os.WriteFile(storeFile, marked, 0o644); err != nil { + t.Fatal(err) + } + refusedOnce(stem+"-store", "store_format_newer") + if after, err := os.ReadFile(storeFile); err != nil || !bytes.Equal(after, marked) { + t.Fatalf("the refused open changed the store (%v)", err) + } + if err := os.WriteFile(storeFile, original, 0o644); err != nil { + t.Fatal(err) + } + + // 2. A HEAD written by a newer version. + ref := chunkstore.VolumeRef{Name: volume, ID: layoutID} + cl := cluster.client(t, "") + dir := path.Join(base, ref.Dir()) + ctx := context.Background() + entry, err := cl.LookupEntry(ctx, dir, "HEAD") + if err != nil { + t.Fatal(err) + } + var head map[string]any + if err := json.Unmarshal(entry.Content, &head); err != nil { + t.Fatalf("HEAD record: %v", err) + } + head["version"] = 9 + newer, err := json.Marshal(head) + if err != nil { + t.Fatal(err) + } + entry.Content = newer + if err := cl.UpdateEntry(ctx, dir, entry, nil); err != nil { + t.Fatal(err) + } + refusedOnce(stem+"-head", "head_newer_version") + if after, err := cl.LookupEntry(ctx, dir, "HEAD"); err != nil || !bytes.Equal(after.Content, newer) { + t.Fatalf("the refused start changed HEAD (%v)", err) + } +} From bbeb8d98aa2754c52d2806accbeb57d130b99c1d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:24:06 -0800 Subject: [PATCH 46/51] authority: comments name the deadline barrier; gofmt Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/authority/golden_v100_test.go | 12 ++++++------ seaweed-block/core/authority/workspace_lease_view.go | 4 ++-- seaweed-block/core/authority/workspace_lost_range.go | 3 ++- seaweed-block/core/host/master/journal_isolation.go | 4 ++-- .../host/master/workspace_renewal_slowstore_test.go | 2 +- 5 files changed, 13 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/authority/golden_v100_test.go b/seaweed-block/core/authority/golden_v100_test.go index 2517e58811..772e449247 100644 --- a/seaweed-block/core/authority/golden_v100_test.go +++ b/seaweed-block/core/authority/golden_v100_test.go @@ -158,13 +158,13 @@ func goldenAuthorityFiles(t *testing.T, root string) map[string][]byte { // goldenAuthorityAtV100 is each fixture file's git blob hash as written on // the v1.0.0 tag checkout. var goldenAuthorityAtV100 = map[string]string{ - "workspace/wa.v3auth.json": "954efb2d8afda475ac856c4dc907d7b58cb719eb", - "workspace/wl.v3auth.json": "79dc6696143165fef5b749b9ba81757ba50056b1", + "workspace/wa.v3auth.json": "954efb2d8afda475ac856c4dc907d7b58cb719eb", + "workspace/wl.v3auth.json": "79dc6696143165fef5b749b9ba81757ba50056b1", "workspace/wm.lostrange.json": "a4f9f6a612eba987297def1f40eea5b92214575d", - "workspace/wm.v3auth.json": "c9adcceb41095cf4e5d06f12a442ec4f5fbbc725", - "v1.lostrange.json": "cb4200c2742a7c784d4eb2d1beed61a212053608", - "v1.v3auth.json": "88642d0ed99d19635e1ff3d2bd2082ecc319643e", - "v2.v3auth.json": "fb7a6a3cd8d2c81c955fc130566f6ae93c677c91", + "workspace/wm.v3auth.json": "c9adcceb41095cf4e5d06f12a442ec4f5fbbc725", + "v1.lostrange.json": "cb4200c2742a7c784d4eb2d1beed61a212053608", + "v1.v3auth.json": "88642d0ed99d19635e1ff3d2bd2082ecc319643e", + "v2.v3auth.json": "fb7a6a3cd8d2c81c955fc130566f6ae93c677c91", } func TestAuthorityGoldenFilesAreTheV100Files(t *testing.T) { diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index e497d3c143..197096a797 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -298,7 +298,8 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri // firstWorkspaceGrant creates a lease synchronously under p.mu (one write per // assignment epoch) for an epoch that has none: a move issue already started // its holder's lease. A host whose first renewal fails does not fence: it has -// no deadline yet and retries. The durable horizon starts at now+1.5*TTL. +// no deadline yet and retries. The record's ExpiresAtNS is now+1.5*TTL, the +// form v1.0.x reads; this process's deadline is now+TTL. func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) { p.beforeWorkspaceGrantLock("first grant") p.mu.Lock() @@ -396,7 +397,6 @@ func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL) } - // LeaseBarrierError is an expired re-grant refused because the forced-move // barrier has not passed. Until is when it passes (master wall time) and // RetryAfter is Until minus the master's time at the refusal, so a client diff --git a/seaweed-block/core/authority/workspace_lost_range.go b/seaweed-block/core/authority/workspace_lost_range.go index 74198aa17a..8b8ada0891 100644 --- a/seaweed-block/core/authority/workspace_lost_range.go +++ b/seaweed-block/core/authority/workspace_lost_range.go @@ -14,7 +14,8 @@ import ( // WorkspaceLostRange records what a forced move abandoned: the old holder's // writes after LostAfterLSN (the HEAD frontier the move keeps) are lost, and // none of them was acknowledged later than LostUntilNS (master time: the -// forced barrier, the lease horizon or restart deadline plus skew). The +// forced barrier: the lease deadline, or after a restart the restart floor, +// plus skew). The // lease carries no write frontier, so the upper bound is a time. // // HeadTimeNS is the kept HEAD entry's filer mtime, read with that HEAD at the diff --git a/seaweed-block/core/host/master/journal_isolation.go b/seaweed-block/core/host/master/journal_isolation.go index 3fa3589884..aa634a45ef 100644 --- a/seaweed-block/core/host/master/journal_isolation.go +++ b/seaweed-block/core/host/master/journal_isolation.go @@ -13,8 +13,8 @@ import ( // journalIsolation tracks nodes whose durable root shares the authority // store's file system. On one ext4 file system every fsync goes through one -// jbd2 journal: a volume's WAL fsync storm delays the authority journal's -// lease extensions, grants clamp to the durable horizon and leases run out. +// jbd2 journal: a volume's WAL fsync storm delays every authority write +// (grants, moves, revocations) behind it. // // The colocated set is the latest heartbeat fact per server (memory only): a // node that moves its durable root off the store's file system leaves the set diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go index 48ed6adcdb..c132afc4bc 100644 --- a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -149,7 +149,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { }) dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil)) - t.Cleanup(slow.release) // runs before the join above: frees a held Put first + t.Cleanup(slow.release) // runs before the join above: frees a held Put first seedSkewPublisher(t, p, dir) var stops atomic.Int32 g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, From 8ad9139fa671fc3aadfc8820b04a25a80f7c512f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:24:33 -0800 Subject: [PATCH 47/51] layout: a v1.1 commit writes HEAD version 1, the manifest size known or not HEAD's version followed the manifest size: a v1.1 commit by change over a HEAD without a recorded size (an upgraded volume's first cut) left it at version 0, a HEAD a v1.0 binary would read. A v1.1 commit now writes version 1 whatever it knows of the size (CommitRequest.V11, set by the layout remote on the v1.1 format), and a version-0 HEAD carrying a v1.1 manifest size is refused like one carrying ext. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/chunkstore/layout/commit.go | 15 +++++++---- .../core/frontend/chunkstore/layout/head.go | 17 ++++++++++++ .../chunkstore/layout/head_version_test.go | 27 ++++++++++++++++--- .../chunkstore/layout_manifest_size_test.go | 8 +++++- .../core/frontend/chunkstore/layout_remote.go | 4 +-- seaweed-block/docs/design/invariants.md | 1 + 6 files changed, 60 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/layout/commit.go b/seaweed-block/core/frontend/chunkstore/layout/commit.go index 2a7a898873..3459be7c1f 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/commit.go +++ b/seaweed-block/core/frontend/chunkstore/layout/commit.go @@ -62,6 +62,10 @@ type CommitRequest struct { // (the root and every segment it names): HEAD's CurrentBytes after the // commit, and the named snapshot's size. nil writes neither (unknown). ManifestBytes *uint64 + // V11: the commit writes a v1.1 HEAD. HEAD is then version 1 whether or + // not ManifestBytes is known (an upgraded volume's first commit by change + // does not know it). + V11 bool } // CommitDelta is a commit by change (cost table K3): HEAD's current root, @@ -453,18 +457,19 @@ func commitChecked(ctx context.Context, h Head, os ObjectStore, vol string, me H } next, changed, err := h.Commit(me, req.Session, plan.root, req.Position, req.Snapshot, req.Meta, req.State) if err == nil && changed { - next = next.withManifestBytes(req.Snapshot, req.ManifestBytes) + next = next.withManifestBytes(req.Snapshot, req.ManifestBytes, req.V11) } return next, changed, err } // withManifestBytes records the committed root's manifest size: HEAD's // CurrentBytes (nil: unknown, also when an earlier commit knew it), and the -// size of the snapshot this commit named, written once. -func (h Head) withManifestBytes(snapshot string, size *uint64) Head { +// size of the snapshot this commit named, written once. A v1.1 commit (v11) +// writes HEAD version 1, the size known or not; a size is a v1.1 field. +func (h Head) withManifestBytes(snapshot string, size *uint64, v11 bool) Head { h = h.clone() // the snapshot map is shared with the HEAD it came from - if size != nil && h.Version < HeadVersion1 { - h.Version = HeadVersion1 // the sizes are v1.1 fields + if (v11 || size != nil) && h.Version < HeadVersion1 { + h.Version = HeadVersion1 } h.CurrentBytes = cloneSize(size) if s, ok := h.Snapshots[snapshot]; snapshot != "" && ok && s.ManifestBytes == nil { diff --git a/seaweed-block/core/frontend/chunkstore/layout/head.go b/seaweed-block/core/frontend/chunkstore/layout/head.go index 4f345a8058..674d8afeca 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head.go @@ -249,6 +249,20 @@ func checkExt(version int, ext json.RawMessage) error { return nil } +// carriesManifestSizes reports whether h carries a v1.1 manifest size: its +// CurrentBytes or any snapshot's ManifestBytes. +func (h Head) carriesManifestSizes() bool { + if h.CurrentBytes != nil { + return true + } + for _, s := range h.Snapshots { + if s.ManifestBytes != nil { + return true + } + } + return false +} + // ErrNoNextPosition: a HEAD position with no room for a next LSN. No // commit produces it (Commit refuses); a HEAD that already carries one (an // older or broken writer) is still read, written by every other @@ -262,6 +276,9 @@ func (h Head) check() error { if err := checkExt(h.Version, h.Ext); err != nil { return err } + if h.Version == 0 && h.carriesManifestSizes() { + return fmt.Errorf("%w: a v1.0 HEAD carries v1.1 manifest sizes", ErrMalformed) + } switch h.State { case StateLive, StateDetached, StateDeleting, StateDeleted: default: diff --git a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go index d9270824d3..6bc71994a4 100644 --- a/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout/head_version_test.go @@ -102,19 +102,38 @@ func TestCommitRecordsTheManifestSize(t *testing.T) { if err != nil || !changed { t.Fatal(err) } - sized := next.withManifestBytes("snap", u64(777)) + sized := next.withManifestBytes("snap", u64(777), true) if sized.Version != HeadVersion1 || sized.CurrentBytes == nil || *sized.CurrentBytes != 777 { t.Fatalf("sized commit: %+v", sized) } if s := sized.Snapshots["snap"]; s.ManifestBytes == nil || *s.ManifestBytes != 777 { t.Fatalf("the named snapshot's size: %+v", s) } - unsized := next.withManifestBytes("snap", nil) + unsized := next.withManifestBytes("snap", nil, false) if unsized.Version != 0 || unsized.CurrentBytes != nil || unsized.Snapshots["snap"].ManifestBytes != nil { - t.Fatalf("a commit that does not know the size: %+v", unsized) + t.Fatalf("a v1.0 commit, which writes no size: %+v", unsized) + } + // A v1.1 commit that does not know the size (an upgraded volume's first + // commit by change) is still version 1, with the size unknown. + unknown := next.withManifestBytes("snap", nil, true) + if unknown.Version != HeadVersion1 || unknown.CurrentBytes != nil || unknown.Snapshots["snap"].ManifestBytes != nil { + t.Fatalf("a v1.1 commit without a size: %+v", unknown) + } + // A v1.0 HEAD never carries a v1.1 size: Encode refuses one. + bad := unsized.clone() + bad.CurrentBytes = u64(5) + if _, err := bad.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("a version-0 HEAD with a manifest size encoded: %v", err) + } + badSnap := unsized.clone() + sn := badSnap.Snapshots["snap"] + sn.ManifestBytes = u64(5) + badSnap.Snapshots["snap"] = sn + if _, err := badSnap.Encode(); !errors.Is(err, ErrMalformed) { + t.Fatalf("a version-0 HEAD with a snapshot size encoded: %v", err) } // Written once: a later size never rewrites a snapshot's. - again := sized.withManifestBytes("snap", u64(999)) + again := sized.withManifestBytes("snap", u64(999), true) if s := again.Snapshots["snap"]; *s.ManifestBytes != 777 { t.Fatalf("a snapshot's size was rewritten: %d", *s.ManifestBytes) } diff --git a/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go b/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go index d7942fefb0..e9bc3893ed 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go +++ b/seaweed-block/core/frontend/chunkstore/layout_manifest_size_test.go @@ -96,7 +96,10 @@ func TestCommitsKeepTheManifestSizeExact(t *testing.T) { } // A HEAD with no recorded size (a v1.0 HEAD) stays unknown through commits -// by change: they cannot know the objects they did not replace. +// by change: they cannot know the objects they did not replace. The first +// v1.1 commit still writes HEAD at version 1: the version follows the +// format, never whether a size is known (an upgraded volume's first cut is a +// commit by change, and a v1.0 binary must refuse what it wrote). func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) { withManifestSizes(t, false) ctx, _, r, h1 := threeShardVolume(t) // a v1.0 HEAD: no size @@ -118,6 +121,9 @@ func TestACommitByChangeKeepsAnUnknownSizeUnknown(t *testing.T) { if h.CurrentBytes != nil { t.Fatalf("a commit by change over an unknown size wrote %d", *h.CurrentBytes) } + if h.Version != layout.HeadVersion1 { + t.Fatalf("the first v1.1 commit (a commit by change, size unknown) wrote HEAD version %d, want %d", h.Version, layout.HeadVersion1) + } } // A commit by change that touches a shard but leaves its segment unchanged diff --git a/seaweed-block/core/frontend/chunkstore/layout_remote.go b/seaweed-block/core/frontend/chunkstore/layout_remote.go index 5d56d17433..09544ad838 100644 --- a/seaweed-block/core/frontend/chunkstore/layout_remote.go +++ b/seaweed-block/core/frontend/chunkstore/layout_remote.go @@ -535,7 +535,7 @@ func (l *LayoutRemote) prepareCommitLocked(ctx context.Context, expected storage return layout.Head{}, layout.CommitRequest{}, false, err } } - req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive} + req := layout.CommitRequest{Session: l.session, Prev: prev, Next: nextM, Position: next.RemoteLSN, State: layout.StateLive, V11: manifestSizesV11()} if delta { plan, err := layout.PlanCommit(l.vol.Name, layout.CommitRequest{Delta: &d}, true) if err != nil { @@ -1085,7 +1085,7 @@ func (l *LayoutRemote) CommitPendingSnapshot(ctx context.Context) error { if err != nil { return err } - req := layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta} + req := layout.CommitRequest{Session: l.session, Prev: m, Next: m, Position: h.Position, State: layout.StateLive, Snapshot: p.name, Meta: p.meta, V11: manifestSizesV11()} if manifestSizesV11() { req.ManifestBytes = &size } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index a2c950cd30..a413b8893a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1203,6 +1203,7 @@ Notes: | `INV-SNAPK-HEAD-WRITE-001` | HEAD changes only by one conditional update on its generation through `runTransition`; no path in the package creates a HEAD, and an absent HEAD is refused. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `runTransition`; `HeadStore` (read and conditional update only) | `TestGuard_WritersTransitionsAndRemovers`, `TestRunBegin` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-HEAD-GUARD-001` | A source scan refuses any other use of `UpdateHead`, a transition without its closure and interrupt tests, and any store remover other than the mark-gated Cleaner.removePlanned and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE | | `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 10 snapshots (`MaxSnapshots`) and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE | +| `INV-SNAPK-HEAD-V11-VERSION-001` | Any HEAD carrying a v1.1-only field (a manifest size, ext) is version 1, and a v1.1 commit writes version 1 whether or not it knows the manifest size; a version-0 HEAD with one is refused. | M-snapshot commit | `core/frontend/chunkstore/layout/commit.go` `withManifestBytes`; `core/frontend/chunkstore/layout/head.go` `check`, `checkExt`; `core/frontend/chunkstore/layout_remote.go` (`CommitRequest.V11`) | `TestCommitRecordsTheManifestSize` (`core/frontend/chunkstore/layout/head_version_test.go`); `TestACommitByChangeKeepsAnUnknownSizeUnknown` (`core/frontend/chunkstore/layout_manifest_size_test.go`) | none | ACTIVE | | `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE | | `INV-SNAPK-COMMIT-REACH-001` | A commit never names an unwritten object: before its HEAD update it finds present, written by its session or adopted from an earlier one of this volume, the own chunks new against HEAD's current root, every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`); `TestLayoutRemoteUploadFinishedAfterSessionEndCannotCommit` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`); also in `core/frontend/chunkstore/layout/commit_test.go` | — (the snapshot kernel model is not in this repository) | ACTIVE | From aa512ab6d46f5b6f1dff035e71b2c139f3e19b42 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:41:31 -0800 Subject: [PATCH 48/51] blockvolume, volume: red tests, an underivable cgroup limit starts on the default - A holder whose cgroup v2 limit cannot be derived (its membership is outside the cgroup2 mount of its mount namespace, or memory.max is unreadable), with neither --memory-limit-mib nor GOMEMLIMIT, must start on the 256 MiB default and record why (fails: exit 2 on the derivation error). An explicit but invalid flag still refuses. - Applying that limit must log exactly one WARN naming the reason and the two ways to choose a limit, and status must report the reason; a derived limit logs nothing (fails: no WARN, status empty). - Seams: flags.memoryLimitFallback, applyMemoryLimit (now called after logging is configured), ProcessMemoryStatus.SoftLimitFallback, volume.SetSoftLimitFallback / SoftLimitFallback. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 10 +- .../cmd/blockvolume/memory_fallback_test.go | 110 ++++++++++++++++++ seaweed-block/cmd/blockvolume/memory_limit.go | 11 ++ .../core/host/volume/memory_fallback.go | 8 ++ .../core/host/volume/memory_fallback_test.go | 18 +++ .../core/host/volume/memory_status.go | 3 + 6 files changed, 156 insertions(+), 4 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/memory_fallback_test.go create mode 100644 seaweed-block/cmd/blockvolume/memory_limit.go create mode 100644 seaweed-block/core/host/volume/memory_fallback.go create mode 100644 seaweed-block/core/host/volume/memory_fallback_test.go diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index ea483d87ef..9e94b6a39e 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -9,12 +9,12 @@ import ( "errors" "flag" "fmt" + "log" "math" "net" "os" "os/exec" "path/filepath" - "runtime/debug" "strconv" "strings" "time" @@ -163,6 +163,10 @@ type flags struct { // gating through the durable WriteObserver seam. replicationAck string version bool + + // memoryLimitFallback says why the default soft memory limit is in + // force instead of a cgroup-derived one (seam). + memoryLimitFallback string } // volumeLockDirTestOnlyFlag is hidden from --help (printVisibleUsage). @@ -592,13 +596,11 @@ func main() { fmt.Println(buildinfo.Version("blockvolume")) return } - if f.memoryLimitMiB > 0 { - debug.SetMemoryLimit(f.memoryLimitMiB << 20) - } if err := logging.Configure(f.logLevel); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } + applyMemoryLimit(f, log.Printf) os.Exit(run(f)) } diff --git a/seaweed-block/cmd/blockvolume/memory_fallback_test.go b/seaweed-block/cmd/blockvolume/memory_fallback_test.go new file mode 100644 index 0000000000..7d9c924460 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_fallback_test.go @@ -0,0 +1,110 @@ +package main + +import ( + "fmt" + "os" + "runtime/debug" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/host/volume" +) + +var fallbackBase = []string{"--master", "127.0.0.1:1", "--server-id", "h1", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:2", "--ctrl-addr", "127.0.0.1:3"} + +// cgroupFiles serves fixture /proc and cgroup files; anything else is absent. +func cgroupFiles(files map[string]string) func(string) ([]byte, error) { + return func(name string) ([]byte, error) { + if s, ok := files[name]; ok { + return []byte(s), nil + } + return nil, os.ErrNotExist + } +} + +// A holder whose cgroup v2 limit cannot be derived, with neither +// --memory-limit-mib nor GOMEMLIMIT given, starts on the 256 MiB default and +// says why: it is the no-limit case, never a refusal. The first case is a +// mount namespace whose cgroup2 mount does not cover the process's +// membership (what the process sees in /proc/self/mountinfo and cgroup). +func TestMemoryLimitFallsBackWhenTheCgroupLimitCannotBeDerived(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + for _, tc := range []struct { + name, reason string + files map[string]string + }{ + {"membership outside the namespace's cgroup2 mount", `no cgroup2 mount resolves membership "/user.slice/user-1000.slice/session-7.scope"`, map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 /system.slice/runner.service /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/user.slice/user-1000.slice/session-7.scope\n", + }}, + {"unreadable memory.max", "invalid /sys/fs/cgroup/holder/memory.max value", map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/holder\n", + "/sys/fs/cgroup/holder/memory.max": "garbage\n", + }}, + } { + t.Run(tc.name, func(t *testing.T) { + f, err := parseFlagsWithCgroup(fallbackBase, cgroupFiles(tc.files)) + if err != nil { + t.Fatalf("refused to start: %v", err) + } + if f.memoryLimitMiB != 256 { + t.Fatalf("limit %d MiB, want the 256 MiB default", f.memoryLimitMiB) + } + if !strings.Contains(f.memoryLimitFallback, tc.reason) { + t.Fatalf("fallback reason %q does not name %q", f.memoryLimitFallback, tc.reason) + } + }) + } + // An explicit but invalid limit still refuses. + if _, err := parseFlagsWithCgroup(append(append([]string{}, fallbackBase...), "--memory-limit-mib", "-1"), cgroupFiles(nil)); err == nil { + t.Fatal("an invalid --memory-limit-mib was accepted") + } +} + +// Applying a fallback limit logs exactly one WARN naming why and the two ways +// to choose a limit, and status reports the reason; a derived limit logs +// nothing and reports no reason. +func TestMemoryLimitFallbackWarnsOnceAndShowsInStatus(t *testing.T) { + t.Setenv("GOMEMLIMIT", "") + old := debug.SetMemoryLimit(-1) + t.Cleanup(func() { debug.SetMemoryLimit(old); volume.SetSoftLimitFallback("") }) + f, err := parseFlagsWithCgroup(fallbackBase, cgroupFiles(map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 /system.slice/runner.service /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/user.slice/user-1000.slice/session-7.scope\n", + })) + if err != nil { + t.Fatalf("refused to start: %v", err) + } + var lines []string + logf := func(format string, args ...any) { lines = append(lines, fmt.Sprintf(format, args...)) } + applyMemoryLimit(f, logf) + if len(lines) != 1 { + t.Fatalf("%d log lines, want exactly one WARN: %q", len(lines), lines) + } + for _, want := range []string{"level=WARN", "no cgroup2 mount resolves membership", "256 MiB", "--memory-limit-mib", "GOMEMLIMIT"} { + if !strings.Contains(lines[0], want) { + t.Fatalf("the WARN does not name %q: %s", want, lines[0]) + } + } + if got := debug.SetMemoryLimit(-1); got != 256<<20 { + t.Fatalf("soft limit in force %d, want 256 MiB", got) + } + if got := volume.SoftLimitFallback(); !strings.Contains(got, "no cgroup2 mount resolves membership") { + t.Fatalf("status reports the fallback as %q", got) + } + + lines = nil + f, err = parseFlagsWithCgroup(fallbackBase, cgroupFiles(map[string]string{ + "/proc/self/mountinfo": "29 23 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup rw\n", + "/proc/self/cgroup": "0::/system.slice/volume.service\n", + "/sys/fs/cgroup/system.slice/volume.service/memory.max": "2147483648\n", + })) + if err != nil { + t.Fatal(err) + } + applyMemoryLimit(f, logf) + if len(lines) != 0 || volume.SoftLimitFallback() != "" { + t.Fatalf("a derived limit logged %q and reports fallback %q", lines, volume.SoftLimitFallback()) + } +} diff --git a/seaweed-block/cmd/blockvolume/memory_limit.go b/seaweed-block/cmd/blockvolume/memory_limit.go new file mode 100644 index 0000000000..8ce7f76eb1 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/memory_limit.go @@ -0,0 +1,11 @@ +package main + +import "runtime/debug" + +// applyMemoryLimit sets the process's Go soft memory limit from the parsed +// flags (seam: no fallback report yet). +func applyMemoryLimit(f flags, logf func(string, ...any)) { + if f.memoryLimitMiB > 0 { + debug.SetMemoryLimit(f.memoryLimitMiB << 20) + } +} diff --git a/seaweed-block/core/host/volume/memory_fallback.go b/seaweed-block/core/host/volume/memory_fallback.go new file mode 100644 index 0000000000..78adf6b52f --- /dev/null +++ b/seaweed-block/core/host/volume/memory_fallback.go @@ -0,0 +1,8 @@ +package volume + +// SetSoftLimitFallback records why the process runs on the default soft +// memory limit (seam: not reported yet). +func SetSoftLimitFallback(reason string) {} + +// SoftLimitFallback is the reason SetSoftLimitFallback recorded (seam). +func SoftLimitFallback() string { return "" } diff --git a/seaweed-block/core/host/volume/memory_fallback_test.go b/seaweed-block/core/host/volume/memory_fallback_test.go new file mode 100644 index 0000000000..d5c6cc4b31 --- /dev/null +++ b/seaweed-block/core/host/volume/memory_fallback_test.go @@ -0,0 +1,18 @@ +package volume + +import "testing" + +// The status projection reports why the process runs on the default soft +// memory limit, and reports nothing once there is no such reason. +func TestStatusProjectionReportsTheSoftLimitFallback(t *testing.T) { + t.Cleanup(func() { SetSoftLimitFallback("") }) + s := NewStatusServer(NewAdapterProjectionView(stubProjector{}, "v1", "r1", nil)) + SetSoftLimitFallback("no cgroup2 mount resolves membership \"/user.slice/x.scope\"") + if got := s.statusProjection().Memory.SoftLimitFallback; got != "no cgroup2 mount resolves membership \"/user.slice/x.scope\"" { + t.Fatalf("status reports the fallback as %q", got) + } + SetSoftLimitFallback("") + if got := s.statusProjection().Memory.SoftLimitFallback; got != "" { + t.Fatalf("status still reports a cleared fallback: %q", got) + } +} diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 1ad9e5573e..1c952f7f75 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -16,6 +16,9 @@ type ProcessMemoryStatus struct { HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) SoftLimitBytes int64 // the Go soft memory limit in force (flag, GOMEMLIMIT or cgroup-derived default) + // SoftLimitFallback says why SoftLimitBytes is the default instead of a + // cgroup-derived limit (seam). + SoftLimitFallback string `json:",omitempty"` RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } From 7a70a7a1ca41a1fb72ecc2d74ab8051cf515ba62 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 15:46:02 -0800 Subject: [PATCH 49/51] blockvolume: an underivable cgroup memory limit starts on the default With neither --memory-limit-mib nor GOMEMLIMIT, a cgroup v2 limit that cannot be derived (a membership outside the cgroup2 mount of the holder's mount namespace, an unreadable or malformed memory.max) is the no-limit case: the holder keeps the 256 MiB default and starts, instead of exiting 2. applyMemoryLimit, run once logging is configured, logs one level=WARN line naming the derivation's error and the two ways to choose a limit, and status reports the reason in Memory.SoftLimitFallback (empty otherwise). Only an explicit but invalid limit still refuses. Docs: the flag's help, the operator guide's memory section, the status schema and the v1.1 notes. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/main.go | 13 +++++++---- .../cmd/blockvolume/memory_cgroup.go | 3 ++- seaweed-block/cmd/blockvolume/memory_limit.go | 14 +++++++++-- .../core/host/volume/memory_fallback.go | 23 +++++++++++++++---- .../core/host/volume/memory_status.go | 6 ++--- seaweed-block/docs/operator-guide.md | 10 +++++--- seaweed-block/docs/releases/v1.1.md | 4 ++++ seaweed-block/docs/status-schema.md | 1 + 8 files changed, 54 insertions(+), 20 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 9e94b6a39e..dcf572881f 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -165,7 +165,8 @@ type flags struct { version bool // memoryLimitFallback says why the default soft memory limit is in - // force instead of a cgroup-derived one (seam). + // force instead of a cgroup-derived one: the derivation's error. Empty + // when a limit was derived, given, or not needed. memoryLimitFallback string } @@ -193,7 +194,7 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) var f flags fs := flag.NewFlagSet("blockvolume", flag.ContinueOnError) fs.StringVar(&f.logLevel, "log-level", "info", "log verbosity: info or debug; timestamps are UTC with microseconds") - fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit; 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set") + fs.Int64Var(&f.memoryLimitMiB, "memory-limit-mib", 4*storage.DefaultCutPayloadMemoryBudget/(1<<20), "process Go soft memory limit in MiB; unset: 90% of the effective cgroup v2 memory.max, or 256 MiB without a limit or when it cannot be derived (one WARN says why); 0 preserves GOMEMLIMIT; explicit GOMEMLIMIT is preserved unless this flag is set") fs.StringVar(&f.masterAddr, "master", "", "master gRPC address (required)") fs.StringVar(&f.serverID, "server-id", "", "this server identity (required)") fs.StringVar(&f.masterTLS.Cert, "master-tls-cert", "", "this node's certificate (PEM) for mutual TLS to blockmaster; its CN must equal --server-id") @@ -297,11 +298,13 @@ func parseFlagsWithCgroup(args []string, readFile func(string) ([]byte, error)) if !memoryFlagSet && os.Getenv("GOMEMLIMIT") != "" { f.memoryLimitMiB = 0 } else if !memoryFlagSet && !f.version { + // An underivable cgroup limit is the no-limit case: the default stays + // in force and applyMemoryLimit warns why. Only an explicit limit + // (the flag, or GOMEMLIMIT read by the runtime) may refuse. limit, err := cgroupMemoryLimitMiB(readFile) if err != nil { - return flags{}, fmt.Errorf("derive memory limit: %w", err) - } - if limit != 0 { + f.memoryLimitFallback = err.Error() + } else if limit != 0 { f.memoryLimitMiB = limit } } diff --git a/seaweed-block/cmd/blockvolume/memory_cgroup.go b/seaweed-block/cmd/blockvolume/memory_cgroup.go index 7bab4193f8..ca6854f88d 100644 --- a/seaweed-block/cmd/blockvolume/memory_cgroup.go +++ b/seaweed-block/cmd/blockvolume/memory_cgroup.go @@ -75,7 +75,8 @@ func cgroupMemoryLimitMiB(readFile func(string) ([]byte, error)) (int64, error) // mountinfo names both the filesystem subtree root and its visible mountpoint. // A membership path must resolve inside that view; an unresolved v2 hierarchy -// is a configuration error, not evidence of unlimited memory. +// is an error here, not evidence of unlimited memory: the caller keeps the +// default limit and warns why. func cgroupMemoryDirectory(group string, readFile func(string) ([]byte, error)) (string, string, error) { data, err := readFile("/proc/self/mountinfo") if err != nil { diff --git a/seaweed-block/cmd/blockvolume/memory_limit.go b/seaweed-block/cmd/blockvolume/memory_limit.go index 8ce7f76eb1..c4f2d17c99 100644 --- a/seaweed-block/cmd/blockvolume/memory_limit.go +++ b/seaweed-block/cmd/blockvolume/memory_limit.go @@ -1,11 +1,21 @@ package main -import "runtime/debug" +import ( + "runtime/debug" + + "github.com/seaweedfs/seaweed-block/core/host/volume" +) // applyMemoryLimit sets the process's Go soft memory limit from the parsed -// flags (seam: no fallback report yet). +// flags. When the default is in force because the cgroup v2 limit could not +// be derived, it logs one WARN naming why and how to choose a limit, and +// status reports the reason (Memory.SoftLimitFallback). func applyMemoryLimit(f flags, logf func(string, ...any)) { if f.memoryLimitMiB > 0 { debug.SetMemoryLimit(f.memoryLimitMiB << 20) } + volume.SetSoftLimitFallback(f.memoryLimitFallback) + if f.memoryLimitFallback != "" { + logf("blockvolume: level=WARN memory limit: the cgroup v2 limit could not be derived (%s); running with the %d MiB default soft limit; set --memory-limit-mib or GOMEMLIMIT to choose a limit", f.memoryLimitFallback, f.memoryLimitMiB) + } } diff --git a/seaweed-block/core/host/volume/memory_fallback.go b/seaweed-block/core/host/volume/memory_fallback.go index 78adf6b52f..adb2b1aeb5 100644 --- a/seaweed-block/core/host/volume/memory_fallback.go +++ b/seaweed-block/core/host/volume/memory_fallback.go @@ -1,8 +1,21 @@ package volume -// SetSoftLimitFallback records why the process runs on the default soft -// memory limit (seam: not reported yet). -func SetSoftLimitFallback(reason string) {} +import "sync/atomic" -// SoftLimitFallback is the reason SetSoftLimitFallback recorded (seam). -func SoftLimitFallback() string { return "" } +// softLimitFallback is why the process runs on the default soft memory limit +// instead of a cgroup-derived one; the limit itself is process-wide too. +var softLimitFallback atomic.Pointer[string] + +// SetSoftLimitFallback records why the process runs on the default soft +// memory limit; empty clears it. +func SetSoftLimitFallback(reason string) { + softLimitFallback.Store(&reason) +} + +// SoftLimitFallback is the reason SetSoftLimitFallback recorded, or empty. +func SoftLimitFallback() string { + if p := softLimitFallback.Load(); p != nil { + return *p + } + return "" +} diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 1c952f7f75..b77a4fad11 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -16,9 +16,7 @@ type ProcessMemoryStatus struct { HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) SoftLimitBytes int64 // the Go soft memory limit in force (flag, GOMEMLIMIT or cgroup-derived default) - // SoftLimitFallback says why SoftLimitBytes is the default instead of a - // cgroup-derived limit (seam). - SoftLimitFallback string `json:",omitempty"` + SoftLimitFallback string `json:",omitempty"` // why SoftLimitBytes is the 256 MiB default instead of a cgroup-derived limit (the derivation's error) RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } @@ -26,7 +24,7 @@ type ProcessMemoryStatus struct { func processMemoryStatus() ProcessMemoryStatus { var m runtime.MemStats runtime.ReadMemStats(&m) - out := ProcessMemoryStatus{HeapAllocBytes: m.HeapAlloc, HeapInuseBytes: m.HeapInuse, HeapSysBytes: m.HeapSys, HeapReleasedBytes: m.HeapReleased, SoftLimitBytes: debug.SetMemoryLimit(-1)} + out := ProcessMemoryStatus{HeapAllocBytes: m.HeapAlloc, HeapInuseBytes: m.HeapInuse, HeapSysBytes: m.HeapSys, HeapReleasedBytes: m.HeapReleased, SoftLimitBytes: debug.SetMemoryLimit(-1), SoftLimitFallback: SoftLimitFallback()} b, err := os.ReadFile("/proc/self/status") if err != nil { return out diff --git a/seaweed-block/docs/operator-guide.md b/seaweed-block/docs/operator-guide.md index 711b03dc45..18aa423eba 100644 --- a/seaweed-block/docs/operator-guide.md +++ b/seaweed-block/docs/operator-guide.md @@ -271,9 +271,13 @@ are its only SeaweedFS flags. Run SeaweedFS on a trusted network; mTLS covers th Automatic sizing requires the cgroup v2 memory controller. On cgroup v1, or a hybrid hierarchy without v2 `memory.max`, set `--memory-limit-mib` explicitly for a large volume; otherwise it receives the 256 MiB fallback. - An unreadable or malformed cgroup limit refuses startup with a diagnostic; - an explicit memory flag or `GOMEMLIMIT` bypasses this detection. - Inspect `Memory.SoftLimitBytes` on the holder's status for the value in force. + A cgroup limit that cannot be derived (unreadable or malformed, or a + membership outside the cgroup2 mount visible in the holder's mount namespace) + does not stop the holder: it starts on the 256 MiB default and logs one + `level=WARN` line naming why. An explicit memory flag or `GOMEMLIMIT` bypasses + this detection; only an explicit but invalid one refuses startup. + Inspect `Memory.SoftLimitBytes` on the holder's status for the value in force, + and `Memory.SoftLimitFallback` for why the default is in force. - **Measured throughput on one host** (three runs; 16 cores, 23.2 GiB RAM, one consumer NVMe drive, fsync on every volume): diff --git a/seaweed-block/docs/releases/v1.1.md b/seaweed-block/docs/releases/v1.1.md index 13c0502601..2deb89237d 100644 --- a/seaweed-block/docs/releases/v1.1.md +++ b/seaweed-block/docs/releases/v1.1.md @@ -20,6 +20,10 @@ These notes collect v1.1's changes as they land; v1.1 is not released. - A normal cut that has held its host slot for `--host-limit-yield-after` (default 5 min) gives the slot to a waiting cut at its next staging batch, keeping what it staged; its next attempt queues behind the waiters. A lone cut never yields, and status counts yields apart from failures (`CutYields`). +- A `blockvolume` whose cgroup v2 memory limit cannot be derived (for example, its cgroup membership lies outside + the cgroup2 mount visible in its mount namespace) now starts on the 256 MiB default soft limit and logs one + `level=WARN` line naming why, instead of exiting 2; status reports the reason in `Memory.SoftLimitFallback`. An + explicit but invalid `--memory-limit-mib` or `GOMEMLIMIT` still refuses. ## Upgrade - With `--host-limit-dir` set, the limiter's `configuration.json` in that directory records the flags it was diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 36c0315fe7..41533450f0 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -26,6 +26,7 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | `Memory.HeapSysBytes` | uint64 | Go heap bytes obtained from the OS (HeapSys) | | `Memory.HeapReleasedBytes` | uint64 | Go heap bytes returned to the OS (HeapReleased) | | `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (flag, GOMEMLIMIT or cgroup-derived default) | +| `Memory.SoftLimitFallback` | string | why SoftLimitBytes is the 256 MiB default instead of a cgroup-derived limit (the derivation's error) (omitted when empty) | | `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | | `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | | `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary, its local durable backend admits I/O, and it may serve guest I/O (INV-FE-PRIMARY-READY-OPERATIONAL-001). | From 9c8b30b66f3b8296f6e03241a0b4036f2d0379e8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 16:07:51 -0800 Subject: [PATCH 50/51] storage: the publication report leaves the generation check to noteSettled main's HEAD-generation source guard allows a generation comparison only in conditional updates and noteSettled's deduplication. The two report paths added here compared generations before calling noteSettled; they now call it and let it drop a report of an unchanged generation. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/storage/chunk_layer.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index b9d02c5d3a..c4b47e1191 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -2066,10 +2066,10 @@ func resultHead(h chunkHead) chunkHead { return cutResultHead(h, chunkV11Format) // whole (the ref table's image on the v1.1 format), to next, before next is // installed. Caller holds stMu. func (l *chunkLayerImpl) noteSettledFromHeadLocked(next chunkHead) { - if l.cfg.OnPublishSettled == nil || next.Gen == l.head.Gen { + if l.cfg.OnPublishSettled == nil { return } - l.noteSettled(l.wholeHeadLocked(), next) + l.noteSettled(l.wholeHeadLocked(), next) // it drops a report of an unchanged generation } // copyResultHead copies a cut's reported HEAD as it was reported: a result @@ -2099,7 +2099,7 @@ func headLookup(h chunkHead) func(uint64) (chunkRef, bool) { // it. The publication report, when one is wanted, gets whole HEADs. Caller // holds stMu. func (l *chunkLayerImpl) applyCommitLocked(id chunkHead, changed []uint64) { - report := l.cfg.OnPublishSettled != nil && id.Gen != l.head.Gen + report := l.cfg.OnPublishSettled != nil // noteSettled drops an unchanged generation var prev chunkHead if report { prev = l.wholeHeadLocked() From 07b3d31697228842434adfe10c246c857a21b2eb Mon Sep 17 00:00:00 2001 From: pingqiu Date: Tue, 1 Dec 2026 16:44:01 -0800 Subject: [PATCH 51/51] blockvolume tests: adopt waits for the holder's frontend to admit I/O, not only a healthy primary Fixes #905. Co-Authored-By: Claude Opus 5.5 --- .../cmd/blockvolume/procedure_gate_integration_test.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go index 6fb6024f8d..4bc555fce0 100644 --- a/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go +++ b/seaweed-block/cmd/blockvolume/procedure_gate_integration_test.go @@ -403,13 +403,19 @@ func (env *handoffEnv) start(t *testing.T, name, id string) *daemon { return env.h.start(t, name, env.h.volume, env.volArgs(id)...) } -// adopt waits for the process to adopt v1 as primary and its host to report -// it healthy, and returns the epoch. +// adopt waits for the process to adopt v1 as primary, its host to report it +// a healthy primary, and its frontend to admit guest I/O +// (FrontendPrimaryReady), and returns the epoch. Healthy alone is not +// enough: until the frontend admits I/O, a write is answered "namespace not +// ready" (retryable), which the test's initiator does not retry. func (env *handoffEnv) adopt(t *testing.T, d *daemon, id string) uint64 { t.Helper() _, mustU := fatalOn(t) e := mustU(adoptedEpoch(d.waitLog(t, 60*time.Second, "blockvolume: volume v1 adopted as PRIMARY at r1@"))) env.h.waitPrimaryAt(t, env.hosts[id].status, e) + poll(t, 60*time.Second, fmt.Sprintf("%s: the holder adopted epoch %d but never reported its frontend ready", id, e), func() bool { + return env.frontendReadyAt(id) + }) return e }