mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 11:07:31 +01:00
Merge pull request #705 from seaweedfs/fix/cleaning-convergence
feat: resume holder cleaning and reclaim unused metadata
This commit is contained in:
commit
dfb77aef28
36 files changed
+2444
-143
No files matched your search
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
@@ -24,9 +25,11 @@ func (v VolumeRef) Dir() string { return layout.VolumeDir(v.Name, v.ID) }
|
||||
// BCatalog is the volume catalog on the content-named layout: every
|
||||
// operation is a layout kernel step over the volume's filer store.
|
||||
type BCatalog struct {
|
||||
f Filer
|
||||
b Blobs
|
||||
base string
|
||||
f Filer
|
||||
b Blobs
|
||||
base string
|
||||
cleanMu sync.Mutex
|
||||
cursors map[VolumeRef]*cleanCursor
|
||||
}
|
||||
|
||||
// NewBCatalog returns the catalog of the volumes under base.
|
||||
|
||||
@@ -4,62 +4,157 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
// cleanPage is the number of pool names one removal step plans at once
|
||||
// (a variable only so tests can page with a small one).
|
||||
var cleanPage uint32 = 1000
|
||||
|
||||
// CleanResult is what one cleaning pass removed.
|
||||
// CleanResult counts names examined/deleted by this bounded pass, all kinds.
|
||||
type CleanResult struct {
|
||||
Shards int // pool shards listed
|
||||
Planned int // candidate names read
|
||||
Removed int // names deleted
|
||||
Shards int
|
||||
Planned int
|
||||
Removed int
|
||||
Roots int
|
||||
Segments int
|
||||
}
|
||||
|
||||
// RemoveUnreachableAll is the cleaning's removal step over every pool shard
|
||||
// of v, page by page, for a holder whose clean(session) is open on HEAD
|
||||
// (opened by the holder's layout remote, LayoutRemote.Clean):
|
||||
// layout.RemoveUnreachable validates HEAD after reading each page's tags,
|
||||
// so it removes nothing unless clean(session) is this holder's.
|
||||
// The cursor is scheduling only: after a timeout a new session re-plans tags
|
||||
// and validates HEAD; no cached safety decision survives the pass. Completing
|
||||
// the last shard wraps to roots so earlier/new names are revisited next time.
|
||||
type cleanCursor struct {
|
||||
mu sync.Mutex
|
||||
phase int // roots, segments, chunks
|
||||
shard string
|
||||
after string
|
||||
segmentAfter string
|
||||
poolAfter string
|
||||
}
|
||||
|
||||
func (c *BCatalog) cleaningCursor(v VolumeRef) *cleanCursor {
|
||||
c.cleanMu.Lock()
|
||||
defer c.cleanMu.Unlock()
|
||||
if c.cursors == nil {
|
||||
c.cursors = map[VolumeRef]*cleanCursor{}
|
||||
}
|
||||
cur := c.cursors[v]
|
||||
if cur == nil {
|
||||
cur = &cleanCursor{}
|
||||
c.cursors[v] = cur
|
||||
}
|
||||
return cur
|
||||
}
|
||||
|
||||
// RemoveUnreachableAll resumes a bounded cleaning. Roots are removed before
|
||||
// segments, then chunks; interruptions leave only unnamed content behind.
|
||||
func (c *BCatalog) RemoveUnreachableAll(ctx context.Context, v VolumeRef, me layout.HolderID, session string) (res CleanResult, err error) {
|
||||
cur := c.cleaningCursor(v)
|
||||
if !cur.mu.TryLock() {
|
||||
return res, layout.ErrBusy
|
||||
}
|
||||
defer cur.mu.Unlock()
|
||||
s, r, err := c.open(v)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
cleaner := layout.NewCleaner(s, r, s, me, session)
|
||||
// Every new session starts at the first root: between sessions an operator
|
||||
// may un-name one whose segments this session would otherwise remove first.
|
||||
// Preserve segment/chunk progress, but never carry a root-phase view forward.
|
||||
if cur.phase == 1 {
|
||||
cur.segmentAfter = cur.after
|
||||
}
|
||||
cur.phase, cur.after = 0, ""
|
||||
for cur.phase < 2 {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
kind := layout.RootDir
|
||||
if cur.phase == 1 {
|
||||
kind = layout.SegDir
|
||||
}
|
||||
entries, err := c.f.ListEntries(ctx, path.Join(c.base, v.Dir(), kind), "", cur.after, cleanPage)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
if e == nil || e.IsDirectory || e.Name <= cur.after {
|
||||
return res, layout.ErrCorrupt
|
||||
}
|
||||
names = append(names, e.Name)
|
||||
}
|
||||
res.Planned += len(names)
|
||||
out, err := cleaner.Page(ctx, kind, 0, names)
|
||||
res.Removed += len(out.Names)
|
||||
if kind == layout.RootDir {
|
||||
res.Roots += len(out.Names)
|
||||
} else {
|
||||
res.Segments += len(out.Names)
|
||||
}
|
||||
if out.After != "" {
|
||||
cur.after = path.Base(out.After)
|
||||
}
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if uint32(len(names)) < cleanPage {
|
||||
cur.phase++
|
||||
cur.after = ""
|
||||
if cur.phase == 1 {
|
||||
cur.after = cur.segmentAfter
|
||||
} else {
|
||||
cur.segmentAfter = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
shards, err := s.List(ctx, path.Join(c.base, v.Dir(), layout.PoolDir))
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
sort.Strings(shards)
|
||||
for _, name := range shards {
|
||||
shard, perr := strconv.ParseUint(name, 10, 64)
|
||||
if perr != nil || strconv.FormatUint(shard, 10) != name {
|
||||
return res, errors.Join(layout.ErrCorrupt, errors.New("chunkstore: pool shard "+strconv.Quote(name)))
|
||||
}
|
||||
if name < cur.shard {
|
||||
continue
|
||||
}
|
||||
if name != cur.shard {
|
||||
cur.shard = name
|
||||
cur.poolAfter = ""
|
||||
}
|
||||
res.Shards++
|
||||
after := ""
|
||||
for {
|
||||
page, err := s.ListChunkCandidates(ctx, shard, after, cleanPage)
|
||||
if err := ctx.Err(); err != nil {
|
||||
return res, err
|
||||
}
|
||||
page, err := s.ListChunkCandidates(ctx, shard, cur.poolAfter, cleanPage)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if len(page) == 0 {
|
||||
break
|
||||
names := make([]string, len(page))
|
||||
for i, n := range page {
|
||||
names[i] = n.String()
|
||||
}
|
||||
res.Planned += len(page)
|
||||
removed, err := layout.RemoveUnreachable(ctx, s, r, s, me, session, shard, page)
|
||||
res.Removed += len(removed)
|
||||
out, err := cleaner.Page(ctx, layout.PoolDir, shard, names)
|
||||
res.Removed += len(out.Names)
|
||||
if out.After != "" {
|
||||
cur.poolAfter = path.Base(out.After)
|
||||
}
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
if uint32(len(page)) < cleanPage {
|
||||
break
|
||||
}
|
||||
after = page[len(page)-1].String()
|
||||
}
|
||||
}
|
||||
cur.phase, cur.shard, cur.after, cur.poolAfter = 0, "", "", ""
|
||||
return res, nil
|
||||
}
|
||||
@@ -92,8 +92,8 @@ func TestBCatalog_CleanRemovesOnlyUnreachable(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Shards != 2 || res.Planned != 3 || res.Removed != 2 {
|
||||
t.Fatalf("clean: %+v; want 2 shards, 3 planned, 2 removed", res)
|
||||
if res.Shards != 2 || res.Planned != 5 || res.Removed != 2 {
|
||||
t.Fatalf("clean: %+v; want 2 shards, 5 planned (root, segment, 3 chunks), 2 removed", res)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if present(t, s, n) {
|
||||
@@ -269,14 +269,14 @@ func TestBCatalog_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
res, _, err := cleanVia(ctx, c, v, cleanHolder)
|
||||
if err != nil || res.Removed != 1 {
|
||||
if err != nil || res.Removed != 3 || res.Roots != 1 || res.Segments != 1 {
|
||||
t.Fatalf("clean: %+v %v; want exactly X's chunk removed", res, err)
|
||||
}
|
||||
after, err := c.listObjects(ctx, v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(after) != len(before)-1 || present(t, s, cx) || !present(t, s, cy) {
|
||||
if len(after) != len(before)-3 || present(t, s, cx) || !present(t, s, cy) {
|
||||
t.Fatalf("objects %d -> %d, X present %v, Y present %v; want one fewer, X gone, Y kept", len(before), len(after), present(t, s, cx), present(t, s, cy))
|
||||
}
|
||||
h, _, err := c.ReadHead(ctx, v)
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
func TestCleaningSegmentResumeReplansRootsBeforeRemovingSegments(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
previousPage := cleanPage
|
||||
cleanPage = 1
|
||||
t.Cleanup(func() { cleanPage = previousPage })
|
||||
c, v, s, _ := cleanFixture(t)
|
||||
h, _, _ := s.ReadHead(ctx)
|
||||
oldRoot := *h.Current
|
||||
x := layout.NameChunk(1, bytes.Repeat([]byte{7}, 4096))
|
||||
yData := bytes.Repeat([]byte{8}, 4096)
|
||||
y := layout.NameChunk(1, yData)
|
||||
m1 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: x}}
|
||||
m2 := map[uint64]layout.Ref{1: {Owner: v.Name, OwnerID: v.ID, Chunk: y}}
|
||||
commitImage(t, s, v.Name, "next", m1, m2, map[uint64][]byte{1: yData}, 2, "")
|
||||
f := &cleaningListHook{Filer: c.f}
|
||||
c.f = f
|
||||
interrupt := true
|
||||
f.before = func(dir, after string) error {
|
||||
if dir == path.Join(s.root, layout.SegDir) {
|
||||
if interrupt {
|
||||
if after != "" {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return nil // finish one segment page before interruption
|
||||
}
|
||||
if _, found, err := s.Stat(ctx, oldRoot.Path()); err != nil || found {
|
||||
t.Fatalf("segment resume preceded removal of un-named root: found=%t err=%v", found, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("interrupt: %v", err)
|
||||
}
|
||||
if c.cleaningCursor(v).phase != 1 {
|
||||
t.Fatal("did not interrupt inside segment phase")
|
||||
}
|
||||
if c.cleaningCursor(v).after == "" {
|
||||
t.Fatal("interruption did not retain segment progress")
|
||||
}
|
||||
if _, err := c.DeleteSnapshot(ctx, v, "s"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
interrupt = false
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, r, _ := c.open(v)
|
||||
h, _, _ = s.ReadHead(ctx)
|
||||
img, err := r.Open(ctx, *h.Current)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := img.Chunk(ctx, 1)
|
||||
if err != nil || !bytes.Equal(got.Data, yData) {
|
||||
t.Fatalf("live image: %v %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
type cleaningListHook struct {
|
||||
Filer
|
||||
before func(string, string) error
|
||||
}
|
||||
|
||||
func (f *cleaningListHook) ListEntries(ctx context.Context, dir, prefix, after string, limit uint32) ([]*filerpb.Entry, error) {
|
||||
if f.before != nil {
|
||||
if err := f.before(dir, after); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return f.Filer.ListEntries(ctx, dir, prefix, after, limit)
|
||||
}
|
||||
|
||||
func orphanMetadata(t *testing.T, s *LayoutStore, chunk layout.ChunkName) layout.RootName {
|
||||
t.Helper()
|
||||
root, segs, err := layout.Build(map[uint64]layout.Ref{chunk.Index: {Owner: "v1", OwnerID: s.id, Chunk: chunk}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rn, err := layout.PrepareRoot(context.Background(), s, root, segs, "abandoned")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rn
|
||||
}
|
||||
|
||||
func TestCleaningMetadataCounts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, s, orphans := cleanFixture(t)
|
||||
dead := orphanMetadata(t, s, orphans[0])
|
||||
res, _, err := cleanVia(ctx, c, v, cleanHolder)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, found, err := s.Stat(ctx, dead.Path()); err != nil || found {
|
||||
t.Fatalf("unnamed root retained: found=%t err=%v", found, err)
|
||||
}
|
||||
if res.Roots != 1 || res.Segments != 1 {
|
||||
t.Fatalf("metadata removal counts: %+v", res)
|
||||
}
|
||||
if err := headNamesMissing(ctx, c, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleaningInterruptsAfterMetadataBeforeChunks(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, s, orphans := cleanFixture(t)
|
||||
dead := orphanMetadata(t, s, orphans[0])
|
||||
f := &cleaningListHook{Filer: c.f}
|
||||
c.f = f
|
||||
stop := true
|
||||
f.before = func(dir, after string) error {
|
||||
if stop && dir == path.Join(s.root, layout.PoolDir) {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("interrupt: %v", err)
|
||||
}
|
||||
if _, found, err := s.Stat(ctx, dead.Path()); err != nil || found {
|
||||
t.Fatalf("root was not removed before chunk phase: %t %v", found, err)
|
||||
}
|
||||
for _, n := range orphans {
|
||||
if !present(t, s, n) {
|
||||
t.Fatal("chunk removed before metadata phase finished")
|
||||
}
|
||||
}
|
||||
stop = false
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := headNamesMissing(ctx, c, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects, err := c.listObjects(ctx, v)
|
||||
if err != nil || len(objects) != 3 {
|
||||
t.Fatalf("after resumed clean: objects=%v err=%v; want one live root, segment and chunk", objects, err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestCleaningCursorResumesAfterTimeoutAndWraps(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, s, orphans := cleanFixture(t)
|
||||
prev := cleanPage
|
||||
cleanPage = 1
|
||||
t.Cleanup(func() { cleanPage = prev })
|
||||
f := &cleaningListHook{Filer: c.f}
|
||||
c.f = f
|
||||
fail := true
|
||||
f.before = func(dir, after string) error {
|
||||
if fail && dir == path.Join(s.root, layout.PoolDir, "1") {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("timeout: %v", err)
|
||||
}
|
||||
if present(t, s, orphans[0]) || !present(t, s, orphans[1]) {
|
||||
t.Fatal("timeout did not split the two shards")
|
||||
}
|
||||
fail = false
|
||||
lateRoot := orphanMetadata(t, s, orphans[1])
|
||||
f.before = func(dir, after string) error {
|
||||
if dir == path.Join(s.root, layout.PoolDir, "0") {
|
||||
return errors.New("cursor restarted before timed-out shard")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if present(t, s, orphans[1]) {
|
||||
t.Fatal("resumed pass did not reach later shard")
|
||||
}
|
||||
if _, found, err := s.Stat(ctx, lateRoot.Path()); err != nil || found {
|
||||
t.Fatalf("resumed chunk pass did not first remove newly abandoned metadata: %t %v", found, err)
|
||||
}
|
||||
f.before = nil
|
||||
raw := []byte("new orphan")
|
||||
n := layout.NameChunk(3, raw)
|
||||
if err := layout.EnsureObject(ctx, s, n.Path(), raw, "new"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if present(t, s, n) {
|
||||
t.Fatal("completed pass did not wrap around")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/retain"
|
||||
)
|
||||
|
||||
func TestDependentSnapshotSurvivesOperatorExpiryAndRetentionPrune(t *testing.T) {
|
||||
for _, route := range []string{"operator", "expiry", "prune"} {
|
||||
t.Run(route, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
c, v, _, _ := cleanFixture(t)
|
||||
now := time.Unix(10000, 0)
|
||||
meta := layout.SnapshotMeta{CreatedNs: 1, Class: layout.ClassSemantic}
|
||||
if route == "expiry" {
|
||||
meta.ExpiresNs = now.Add(-time.Second).UnixNano()
|
||||
}
|
||||
snapshotWithMeta(t, c, v, "dependent", meta, "dep", 2)
|
||||
snapshotWithMeta(t, c, v, "newer", layout.SnapshotMeta{CreatedNs: 2, Class: layout.ClassSemantic}, "new", 3)
|
||||
target := newRef(t, "target")
|
||||
if _, err := c.Restore(ctx, v, "dependent", target); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.SetRetention(ctx, v, retain.Policy{KeepNewest: 1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if route == "operator" {
|
||||
if _, err := c.DeleteSnapshot(ctx, v, "dependent"); !errors.Is(err, layout.ErrHasDependents) {
|
||||
t.Fatalf("operator: %v", err)
|
||||
}
|
||||
} else {
|
||||
dry, err := c.Retain(ctx, v, now, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
planned := false
|
||||
for _, n := range dry.Deleted {
|
||||
planned = planned || n == "dependent"
|
||||
}
|
||||
if !planned {
|
||||
t.Fatal("dependent was not a planned retention victim")
|
||||
}
|
||||
res, err := c.Retain(ctx, v, now, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if names(res.Refused) != "dependent" {
|
||||
t.Fatalf("retention did not report refusal: %+v", res)
|
||||
}
|
||||
}
|
||||
h, found, err := c.ReadHead(ctx, v)
|
||||
if err != nil || !found || len(h.Snapshots["dependent"].Dependents) != 1 {
|
||||
t.Fatalf("snapshot lost: %+v %v", h, err)
|
||||
}
|
||||
if _, _, err := cleanVia(ctx, c, v, cleanHolder); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, r, err := c.open(target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
th, _, err := s.ReadHead(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
img, err := r.Open(ctx, *th.Current)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := img.Chunk(ctx, 1); err != nil || !bytes.Equal(got.Data, bytes.Repeat([]byte{7}, 4096)) {
|
||||
t.Fatalf("restore after clean: %v %v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCleaningRemovesUnreferencedRootsAndSegments(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
lh := newLayoutHost(t)
|
||||
s, layer, remote := lh.attach("metadata", true, true)
|
||||
defer s.Close()
|
||||
writeSync(t, s, map[uint32][]byte{0: block(1)})
|
||||
remote.SetSnapshot("old", layout.SnapshotMeta{CreatedNs: 1, Class: layout.ClassSemantic})
|
||||
if _, err := layer.Capture(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := *lh.head().Current
|
||||
writeSync(t, s, map[uint32][]byte{0: block(2)})
|
||||
remote.SetSnapshot("keep", layout.SnapshotMeta{CreatedNs: 2, Class: layout.ClassSemantic})
|
||||
if _, err := layer.Capture(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "old"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error {
|
||||
_, err := lh.cat.RemoveUnreachableAll(ctx, lh.v, me, session)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, _ := lh.cat.Store(lh.v)
|
||||
if _, found, err := st.Stat(ctx, old.Path()); err != nil || found {
|
||||
t.Fatalf("unnamed root retained: found=%t err=%v", found, err)
|
||||
}
|
||||
if _, found, err := st.Stat(ctx, lh.head().Current.Path()); err != nil || !found {
|
||||
t.Fatalf("current root lost: found=%t err=%v", found, err)
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,7 @@ func TestBCatalog_OperatorSnapshotDeleteDuringACleaning(t *testing.T) {
|
||||
// Convergence: the next cleaning removes the chunk only s1 named.
|
||||
f.hook = nil
|
||||
res, _, err = cleanVia(ctx, c, v, cleanHolder)
|
||||
if err != nil || res.Removed != 1 || present(t, s, cx) || !present(t, s, cy) {
|
||||
if err != nil || res.Removed != 3 || res.Roots != 1 || res.Segments != 1 || present(t, s, cx) || !present(t, s, cy) {
|
||||
t.Fatalf("the next pass: %+v %v, X %v, Y %v; want X removed, Y kept", res, err, present(t, s, cx), present(t, s, cy))
|
||||
}
|
||||
if err := headNamesMissing(ctx, c, v); err != nil {
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
// pins it. "GAP" marks a reader that takes an absent HEAD for an empty
|
||||
// one; a change that treats an absent HEAD as unknown flips those probes.
|
||||
var headReaders = map[string]string{
|
||||
"core/frontend/chunkstore/layout_remote.go ProbeSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion; open local activity skips the read (TestMaintenanceNoticesSnapshotDeleteWithoutNotification, TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD)",
|
||||
"core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)",
|
||||
"core/frontend/durable/provider_layout.go settleLayoutStop -> ReadHead": "absent refuses unknown stop outcome, never resumes (probe TestLayoutStopAbortMustConfirmItsOutcome)",
|
||||
"core/frontend/durable/provider_layout.go startLayoutRoot -> ReadHead": "the diagnostic re-read after Start refusal cannot turn an absent HEAD into a claim; Start already refused it (probe TestLayoutStoreMissingHEADRefusesStart)",
|
||||
@@ -38,7 +39,7 @@ var headReaders = map[string]string{
|
||||
"core/host/volume/chunk_control.go ListSnapshots -> ReadHead": "refuses ErrHeadAbsent without creating HEAD (TestChunkControlUsesTheBoundLayoutIdentity)",
|
||||
"core/frontend/chunkstore/layout/delete.go OperatorReleaseDependent -> ReadHead": "reads the source's HEAD (absent: refuses ErrHeadAbsent) and the target's: a target without HEAD (never created, or a restore that died between its VOLUME and its HEAD) gets a deleted HEAD written exclusively before the release (probe LayoutOperatorRelease)",
|
||||
"core/frontend/chunkstore/layout/start.go Start -> ReadHead": "refuses ErrHeadAbsent and creates nothing (probe LayoutStart)",
|
||||
"core/frontend/chunkstore/layout/remove.go RemoveUnreachable -> ReadHead": "refuses ErrHeadAbsent and writes nothing to the objects (probe LayoutRemoval)",
|
||||
"core/frontend/chunkstore/layout/remove.go removePlanned -> ReadHead": "refuses ErrHeadAbsent and writes nothing to chunks, roots or segments (probe LayoutRemoval)",
|
||||
"core/frontend/chunkstore/layout/snapshots.go RunAddDependent -> ReadHead": "refuses ErrHeadAbsent before reading any root and writes nothing (probe LayoutAddDependent)",
|
||||
"core/frontend/chunkstore/catalog_b.go DeleteVolume -> ReadHead": "refuses ErrHeadAbsent before any write (probe BCatalog)",
|
||||
"core/frontend/chunkstore/catalog_b.go ReadHead -> ReadHead": "found=false to the caller, which reports no HEAD (probe BCatalog)",
|
||||
@@ -237,6 +238,14 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) {
|
||||
if _, err := layout.RemoveUnreachable(ctx, &absentLayoutHead{}, r, pool, layout.HolderID{Epoch: 1, Holder: "h"}, "c", 0, []layout.ChunkName{layout.NameChunk(1, []byte("x"))}); !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("layout removal over an absent HEAD: %v; want ErrHeadAbsent", err)
|
||||
}
|
||||
for kind, name := range map[string]string{
|
||||
layout.RootDir: (layout.RootName{Hash: layout.Sum([]byte("root"))}).String(),
|
||||
layout.SegDir: (layout.SegName{Hash: layout.Sum([]byte("segment"))}).String(),
|
||||
} {
|
||||
if _, err := layout.NewCleaner(&absentLayoutHead{}, r, pool, layout.HolderID{Epoch: 1, Holder: "h"}, "c").Page(ctx, kind, 0, []string{name}); !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("%s removal over absent HEAD: %v", kind, err)
|
||||
}
|
||||
}
|
||||
if pool.writes != 0 {
|
||||
t.Fatalf("layout removal over an absent HEAD wrote %d times to the objects", pool.writes)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func metadataFixture(t *testing.T) (*memObjects, *Head, *Reader, RootName, []string) {
|
||||
t.Helper()
|
||||
o, h, _, _ := removeFixture(t)
|
||||
root, segs, err := Build(manifest(ref("v1", 5, "e")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rn, raw, err := NameRoot(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.put(rn.Path(), raw, "s0")
|
||||
names := []string{rn.Path()}
|
||||
for sn, b := range segs {
|
||||
o.put(sn.Path(), b, "s0")
|
||||
names = append(names, sn.Path())
|
||||
}
|
||||
r, err := NewReader(removeBase, "v1", o.fetch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return o, h, r, rn, names
|
||||
}
|
||||
|
||||
func TestCleanerMetadataRetainsCurrentSnapshotAndDependent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
o, h, r, _, dead := metadataFixture(t)
|
||||
h.State = StateLive
|
||||
snap := h.Snapshots["daily"]
|
||||
snap.Dependents = deps(snap.Root, "target")
|
||||
h.Snapshots["daily"] = snap
|
||||
for name, f := range map[string]func() (Head, bool, error){
|
||||
"operator": func() (Head, bool, error) { return h.DeleteSnapshot("daily") },
|
||||
"retention": func() (Head, bool, error) { return h.RetireSnapshot("daily", 100) },
|
||||
} {
|
||||
if _, _, err := f(); !errors.Is(err, ErrHasDependents) {
|
||||
t.Fatalf("%s removed dependent snapshot: %v", name, err)
|
||||
}
|
||||
}
|
||||
cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1")
|
||||
for _, kind := range []string{RootDir, SegDir} {
|
||||
var names []string
|
||||
for p := range o.objs {
|
||||
if path.Dir(p) == path.Join(volRoot, kind) {
|
||||
names = append(names, path.Base(p))
|
||||
}
|
||||
}
|
||||
if _, err := cleaner.Page(ctx, kind, 0, names); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, rel := range dead {
|
||||
if o.has(rel) {
|
||||
t.Fatalf("unnamed metadata retained: %s", rel)
|
||||
}
|
||||
}
|
||||
for _, rn := range HeadRoots(*h) {
|
||||
if !o.has(rn.Path()) {
|
||||
t.Fatalf("HEAD root removed: %s", rn)
|
||||
}
|
||||
}
|
||||
if err := reachableMissing(h, o.data()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanerMetadataRefusesOutsideOwnCleaning(t *testing.T) {
|
||||
for name, edit := range map[string]func(*Head){
|
||||
"idle": func(h *Head) { h.Activity = Activity{Kind: ActIdle} },
|
||||
"snapshot": func(h *Head) { h.Activity = Activity{Kind: ActSnap, Session: "s"} },
|
||||
"foreign": func(h *Head) { h.Epoch++ },
|
||||
"other clean": func(h *Head) { h.Activity.Session = "other" },
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
o, h, r, rn, _ := metadataFixture(t)
|
||||
edit(h)
|
||||
if _, err := NewCleaner(&memHead{h: h}, r, o, me, "c1").Page(context.Background(), RootDir, 0, []string{rn.String()}); err == nil || len(o.writes) != 0 {
|
||||
t.Fatalf("err=%v writes=%v", err, o.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanerMetadataReuseDefeatsLateMarkAndDelete(t *testing.T) {
|
||||
for _, kind := range []string{RootDir, SegDir} {
|
||||
for _, when := range []string{"plan", "mark", "delete"} {
|
||||
t.Run(kind+"/"+when, func(t *testing.T) {
|
||||
o, h, r, _, dead := metadataFixture(t)
|
||||
rel := dead[0]
|
||||
if kind == SegDir {
|
||||
rel = dead[1]
|
||||
}
|
||||
reuse := func() {
|
||||
raw := append([]byte(nil), o.objs[o.full(rel)].data...)
|
||||
if err := EnsureObject(context.Background(), o, rel, raw, "successor"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if when == "plan" {
|
||||
o.afterStat = func(got string) {
|
||||
if got == rel {
|
||||
o.afterStat = nil
|
||||
reuse()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
o.hook = func(op, got string) {
|
||||
if op == when && got == rel {
|
||||
o.hook = nil
|
||||
reuse()
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := NewCleaner(&memHead{h: h}, r, o, me, "c1").Page(context.Background(), kind, 0, []string{path.Base(rel)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !o.has(rel) || o.objs[o.full(rel)].meta.Session != "successor" {
|
||||
t.Fatal("late removal erased a reused object")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanerRecreatesRemovedRootBeforeRenamingIt(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
o, h, r, rn, dead := metadataFixture(t)
|
||||
cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1")
|
||||
for _, rel := range dead {
|
||||
if _, err := cleaner.Page(ctx, path.Dir(rel), 0, []string{path.Base(rel)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if o.has(rn.Path()) {
|
||||
t.Fatal("root was not removed")
|
||||
}
|
||||
next := manifest(ref("v1", 5, "e"))
|
||||
root, segs, err := Build(next)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := EnsureObject(ctx, o, next[5].Chunk.Path(), []byte("e"), "again"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := PrepareRoot(ctx, o, root, segs, "again")
|
||||
if err != nil || got != rn {
|
||||
t.Fatalf("recreate: %v", err)
|
||||
}
|
||||
prev := manifest(ref("v1", 0, "a"), ref("v1", 3, "b"))
|
||||
h.Activity = Activity{Kind: ActSnap, Session: "again"}
|
||||
st := &memHead{h: h}
|
||||
published, err := RunCommit(ctx, st, o, "v1", me, CommitRequest{Session: "again", Prev: prev, Next: next, Position: 1, State: StateLive})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reachableMissing(&published, o.data()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCleanerReachableOncePerShardAndRechecksHead(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
o, h, _, _ := removeFixture(t)
|
||||
reads := map[string]int{}
|
||||
r, err := NewReader(removeBase, "v1", func(ctx context.Context, p string) ([]byte, bool, error) { reads[p]++; return o.fetch(ctx, p) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1")
|
||||
for _, idx := range []uint64{5, 7} {
|
||||
n := NameChunk(idx, []byte(map[uint64]string{5: "e", 7: "f"}[idx]))
|
||||
if _, err := cleaner.Page(ctx, PoolDir, 0, []string{n.String()}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, rn := range HeadRoots(*h) {
|
||||
if n := reads[volRoot+"/"+rn.Path()]; n != 1 {
|
||||
t.Fatalf("root read %d times across pages", n)
|
||||
}
|
||||
}
|
||||
h.Epoch++
|
||||
if _, err := cleaner.Page(ctx, PoolDir, 0, nil); err == nil {
|
||||
t.Fatal("cached reachability bypassed the new HEAD identity")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanerPlansTagsInBoundedParallelBeforeHead(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
o, h, r, _, _ := metadataFixture(t)
|
||||
var entered atomic.Int32
|
||||
var once sync.Once
|
||||
release := make(chan struct{})
|
||||
s := &scriptedObjects{memObjects: o, script: func(ctx context.Context, _ string) error {
|
||||
if entered.Add(1) == 2 {
|
||||
once.Do(func() { close(release) })
|
||||
}
|
||||
select {
|
||||
case <-release:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}}
|
||||
st := &memHead{h: h}
|
||||
st.afterRead = func() {
|
||||
if s.active.Load() != 0 {
|
||||
t.Error("HEAD read before all tag reads returned")
|
||||
}
|
||||
}
|
||||
names := make([]string, 100)
|
||||
for i := range names {
|
||||
names[i] = NameChunk(uint64(i), []byte("absent")).String()
|
||||
}
|
||||
if _, err := NewCleaner(st, r, s, me, "c1").Page(ctx, PoolDir, 0, names); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := s.peak.Load(); p < 2 || p > 32 {
|
||||
t.Fatalf("parallel tag reads=%d; want 2..32", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanerKeepsInitialRootsThroughOperatorDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
o, h, _, _ := removeFixture(t)
|
||||
r, err := NewReader(removeBase, "v1", o.fetch)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cleaner := NewCleaner(&memHead{h: h}, r, o, me, "c1")
|
||||
// Metadata has already been visited using the initial snapshot set.
|
||||
if _, err := cleaner.Page(ctx, RootDir, 0, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.Snapshots = nil
|
||||
old := NameChunk(2, []byte("c"))
|
||||
out, err := cleaner.Page(ctx, PoolDir, 0, []string{old.String()})
|
||||
if err != nil || len(out.Names) != 0 || !o.has(old.Path()) {
|
||||
t.Fatalf("operator delete let chunks disappear beneath an earlier retained root: %+v %v", out, err)
|
||||
}
|
||||
}
|
||||
@@ -128,8 +128,8 @@ func owners(m map[string]bool) []string {
|
||||
// - Release of a dependent: RunReleaseDependent is used only by
|
||||
// DeleteVolume (its own HEAD is deleting) and OperatorReleaseDependent,
|
||||
// which reads the target's HEAD before it releases.
|
||||
// - Pool: a name starting with Delete or Remove is used only in
|
||||
// RemoveUnreachable, whose only removal is DeleteMarked, each right
|
||||
// - Objects: a name starting with Delete or Remove is used only in
|
||||
// Cleaner.removePlanned, whose only removal is DeleteMarked, each right
|
||||
// after a gate on its Mark's error, and in DeleteVolume, whose steps run
|
||||
// in the delete's order: no holder, HEAD deleting, the dependents
|
||||
// released, the objects deleted (conditional on the volume id), HEAD
|
||||
@@ -216,8 +216,8 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool)
|
||||
}
|
||||
if strings.HasPrefix(name, "Delete") || strings.HasPrefix(name, "Remove") {
|
||||
for _, fn := range owners(by) {
|
||||
if fn != "RemoveUnreachable" && fn != "DeleteVolume" {
|
||||
bad = append(bad, fn+" uses "+name+": only RemoveUnreachable (mark-gated) and DeleteVolume (after HEAD deleting and the dependents released) remove")
|
||||
if fn != "Cleaner.removePlanned" && fn != "DeleteVolume" {
|
||||
bad = append(bad, fn+" uses "+name+": only Cleaner.removePlanned (mark-gated) and DeleteVolume (after HEAD deleting and the dependents released) remove")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,7 +227,7 @@ func guardFindings(code map[string]map[string]bool, decl, tests map[string]bool)
|
||||
}
|
||||
|
||||
// removerOrderFindings checks the removal rule (7') in the sources: in
|
||||
// RemoveUnreachable the only removal call is DeleteMarked (a delete
|
||||
// Cleaner.removePlanned the only removal call is DeleteMarked (a delete
|
||||
// conditional on the remover's own mark), and each is IMMEDIATELY
|
||||
// preceded, in the same block, by a mark gate: an if statement whose init
|
||||
// calls Mark and whose body leaves on its error (return or continue). An
|
||||
@@ -286,6 +286,12 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string {
|
||||
})
|
||||
return leaves
|
||||
}
|
||||
writer := "RemoveUnreachable"
|
||||
for _, src := range srcs {
|
||||
if strings.Contains(src, "func (c *Cleaner) removePlanned(") {
|
||||
writer = "removePlanned"
|
||||
}
|
||||
}
|
||||
var bad []string
|
||||
for fname, src := range srcs {
|
||||
file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0)
|
||||
@@ -294,7 +300,7 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string {
|
||||
}
|
||||
for _, d := range file.Decls {
|
||||
fn, ok := d.(*ast.FuncDecl)
|
||||
if !ok || fn.Body == nil || fn.Name.Name != "RemoveUnreachable" {
|
||||
if !ok || fn.Body == nil || fn.Name.Name != writer {
|
||||
continue
|
||||
}
|
||||
deletes := 0
|
||||
@@ -315,17 +321,17 @@ func removerOrderFindings(t *testing.T, srcs map[string]string) []string {
|
||||
deletes++
|
||||
for _, name := range names {
|
||||
if name != "DeleteMarked" {
|
||||
bad = append(bad, "RemoveUnreachable calls "+name+": its only removal is DeleteMarked, conditional on its own mark")
|
||||
bad = append(bad, "Cleaner.removePlanned calls "+name+": its only removal is DeleteMarked, conditional on its own mark")
|
||||
}
|
||||
}
|
||||
if i == 0 || !markGate(blk.List[i-1]) {
|
||||
bad = append(bad, "RemoveUnreachable removes without a mark gate immediately before it (an if on Mark's error that leaves)")
|
||||
bad = append(bad, "Cleaner.removePlanned removes without a mark gate immediately before it (an if on Mark's error that leaves)")
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if deletes == 0 {
|
||||
bad = append(bad, "RemoveUnreachable is declared and has no delete: the scan is broken")
|
||||
bad = append(bad, "Cleaner.removePlanned is declared and has no delete: the scan is broken")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -445,7 +451,7 @@ func TestGuard_Controls(t *testing.T) {
|
||||
"untested transition": {src: `func RunZz(ctx context.Context, st HeadStore) (Head, error) { return runTransition(ctx, st, nil) }`, want: "has no TestZz_Closure"},
|
||||
"lease wait outside claim": {src: `func w(ctx context.Context, l LeaseWait) error { return l.OldLeaseEnded(ctx, 1) }`, want: "only RunClaim claims"},
|
||||
"remover outside RemoveUnreachable": {src: `type p interface{ DeleteObject(context.Context, string) error }
|
||||
func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"},
|
||||
func w(ctx context.Context, x p) error { return x.DeleteObject(ctx, "o") }`, want: "only Cleaner.removePlanned (mark-gated) and DeleteVolume"},
|
||||
"claim without lease wait": {src: `func RunClaim(ctx context.Context, st HeadStore, lease LeaseWait, me HolderID) (Head, error) {
|
||||
return runTransition(ctx, st, func(h Head) (Head, bool, error) { return h, false, nil })
|
||||
}`, want: "does not wait for the old lease", file: "claim.go"},
|
||||
@@ -500,7 +506,7 @@ func w(ctx context.Context, x g) error { return x.NoLiveLease(ctx) }`, want: "on
|
||||
"a fourth HEAD create": {src: `func w(ctx context.Context, st NewVolumeStore, h Head) { _ = st.CreateHead(ctx, h) }`, want: "only createVolume creates a HEAD"},
|
||||
"tombstone outside the operator's release": {src: `func w(ctx context.Context, t TargetStore, h Head) { _ = t.CreateDeletedHead(ctx, h) }`, want: "only the operator's release writes a tombstone"},
|
||||
"remover method value": {src: `type p interface{ RemoveName(string) }
|
||||
func w(x p) { f := x.RemoveName; f("o") }`, want: "only RemoveUnreachable (mark-gated) and DeleteVolume"},
|
||||
func w(x p) { f := x.RemoveName; f("o") }`, want: "only Cleaner.removePlanned (mark-gated) and DeleteVolume"},
|
||||
} {
|
||||
srcs := packageSources(t, false)
|
||||
file := c.file
|
||||
@@ -524,22 +530,21 @@ func removeVariant(t *testing.T, mode string) string {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := strings.ReplaceAll(string(b), "\r\n", "\n")
|
||||
gate := "if err := os.Mark(ctx, c.Path(), tag, session); err != nil {"
|
||||
gate := "if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil {"
|
||||
if !strings.Contains(src, gate) {
|
||||
t.Fatal("remove.go mark gate not found")
|
||||
}
|
||||
switch mode {
|
||||
case "ignored":
|
||||
i := strings.Index(src, gate)
|
||||
j := strings.Index(src[i:], "\n\t\t}\n") + i + len("\n\t\t}\n")
|
||||
src = src[:i] + "_ = os.Mark(ctx, c.Path(), plan, session)\n" + src[j:]
|
||||
src = strings.Replace(src, gate, "if err := error(nil); err != nil {", 1)
|
||||
case "second":
|
||||
src = strings.Replace(src, "removed = append(removed, c)", "_ = os.DeleteMarked(ctx, c.Path(), session)\n\t\tremoved = append(removed, c)", 1)
|
||||
src = strings.Replace(src, "out.Names = append(out.Names, rel)", "_ = c.os.DeleteMarked(ctx, rel, c.session)\n out.Names = append(out.Names, rel)", 1)
|
||||
case "other":
|
||||
src = strings.Replace(src, "removed = append(removed, c)", "_ = os.RemoveOther(ctx, c.Path())\n\t\tremoved = append(removed, c)", 1)
|
||||
src = strings.Replace(src, "out.Names = append(out.Names, rel)", "_ = c.os.RemoveOther(ctx, rel)\n out.Names = append(out.Names, rel)", 1)
|
||||
case "unconditional":
|
||||
src = strings.Replace(src, "if err := os.DeleteMarked(ctx, c.Path(), session); err != nil {", "if err := os.DeleteObject(ctx, c.Path()); err != nil {", 1)
|
||||
src = strings.Replace(src, "if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil {", "if err := c.os.DeleteObject(ctx, rel); err != nil {", 1)
|
||||
}
|
||||
|
||||
i := strings.Index(src, ")\n")
|
||||
return src[i+2:]
|
||||
}
|
||||
@@ -5,100 +5,239 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// RemoveUnreachable is the cleaning's removal (transition 7') for one pool
|
||||
// shard, for the holder with its own clean(session) open at HEAD's epoch,
|
||||
// in an order that makes its plan atomic with its HEAD view
|
||||
// (read-validate-write):
|
||||
// 1. read the tag (writer session, mark) of every candidate;
|
||||
// 2. only then read HEAD, require it is still this holder's with
|
||||
// clean(session), and compute what any root in it (current or
|
||||
// snapshot) names in this volume's pool;
|
||||
// 3. MARK each candidate no root names, expected the tag from step 1;
|
||||
// 4. DELETE it, expected that mark.
|
||||
//
|
||||
// If a successor acted before step 2, HEAD is no longer this holder's and
|
||||
// nothing is written. If it acted after, every tag from step 1 predates
|
||||
// its writes: a session that names a chunk no root named at its Begin
|
||||
// writes that chunk's entry (create, or reuse with a new tag), so the MARK
|
||||
// or the DELETE fails its condition, however late it lands. No lease
|
||||
// reasoning is needed. A candidate an earlier session marked and did not
|
||||
// delete (it died in between) is planned again: its tag carries that
|
||||
// mark, so the MARK replaces it, and the earlier session's late DELETE,
|
||||
// conditional on its own mark, fails. Every unreachable name is therefore
|
||||
// removed by the next completed cleaning. Chunks a restore target names stay live: the source's snapshot
|
||||
// root names them while it has dependents. It returns the names it
|
||||
// deleted, in index order.
|
||||
func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) {
|
||||
if os == nil || r == nil {
|
||||
return nil, errors.New("layout: removal needs a reader and an object store")
|
||||
// Cleaner is one clean(session)'s removal plan. Tags are read before each
|
||||
// authoritative HEAD view; only immutable reachability is cached between pages.
|
||||
// It is used serially, and never survives a cleaning session or process restart.
|
||||
type Cleaner struct {
|
||||
tagParallel int
|
||||
st HeadStore
|
||||
r *Reader
|
||||
os ObjectStore
|
||||
me HolderID
|
||||
session string
|
||||
roots []RootName
|
||||
rootsRead bool
|
||||
metadata map[string]bool
|
||||
shard uint64
|
||||
chunks map[ChunkName]bool
|
||||
}
|
||||
|
||||
// NewCleaner starts a per-session remover; Page validates HEAD before every write.
|
||||
func NewCleaner(st HeadStore, r *Reader, os ObjectStore, me HolderID, session string) *Cleaner {
|
||||
return &Cleaner{st: st, r: r, os: os, me: me, session: session, tagParallel: 32}
|
||||
}
|
||||
|
||||
// RemovalResult advances through names examined (including live objects), not
|
||||
// merely deleted names. A failed candidate is left for the next pass to retry.
|
||||
type RemovalResult struct {
|
||||
Names []string
|
||||
After string
|
||||
}
|
||||
|
||||
// Page removes unreferenced metadata (RootDir or SegDir) or chunks (PoolDir,
|
||||
// with shard). Every name is validated before any store effect. Metadata pages
|
||||
// must be visited roots first, then segments, before chunk pages.
|
||||
func (c *Cleaner) Page(ctx context.Context, kind string, shard uint64, names []string) (RemovalResult, error) {
|
||||
rels := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
var rel string
|
||||
switch kind {
|
||||
case RootDir:
|
||||
n, err := ParseRootName(name)
|
||||
if err != nil {
|
||||
return RemovalResult{}, err
|
||||
}
|
||||
rel = n.Path()
|
||||
case SegDir:
|
||||
n, err := ParseSegName(name)
|
||||
if err != nil {
|
||||
return RemovalResult{}, err
|
||||
}
|
||||
rel = n.Path()
|
||||
case PoolDir:
|
||||
n, err := ParseChunkName(name)
|
||||
if err != nil {
|
||||
return RemovalResult{}, err
|
||||
}
|
||||
if Shard(n.Index) != shard {
|
||||
return RemovalResult{}, ErrMalformed
|
||||
}
|
||||
rel = n.Path()
|
||||
default:
|
||||
return RemovalResult{}, ErrMalformed
|
||||
}
|
||||
rels = append(rels, rel)
|
||||
}
|
||||
sorted := append([]ChunkName(nil), candidates...)
|
||||
sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index })
|
||||
plan := map[ChunkName]ObjectMeta{}
|
||||
for _, c := range sorted {
|
||||
if Shard(c.Index) != shard {
|
||||
continue
|
||||
}
|
||||
meta, found, err := os.Stat(ctx, c.Path())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if found {
|
||||
plan[c] = meta
|
||||
return c.removePlanned(ctx, rels, kind, shard)
|
||||
}
|
||||
|
||||
// removePlanned is the single mark/delete writer for all content-named objects:
|
||||
// tags -> HEAD + holder/clean validation -> reachability -> conditional mark ->
|
||||
// conditional delete. A reuse after planning or marking defeats the late write.
|
||||
func (c *Cleaner) removePlanned(ctx context.Context, rels []string, kind string, shard uint64) (out RemovalResult, err error) {
|
||||
if c.os == nil || c.r == nil {
|
||||
return out, errors.New("layout: removal needs a reader and an object store")
|
||||
}
|
||||
type tag struct {
|
||||
meta ObjectMeta
|
||||
found bool
|
||||
err error
|
||||
}
|
||||
tags := make([]tag, len(rels))
|
||||
// Bounded parallel tag reads finish before HEAD is read. Their original order
|
||||
// determines the first error, independent of completion order.
|
||||
var wg sync.WaitGroup
|
||||
jobs := make(chan int)
|
||||
for range min(c.tagParallel, len(rels)) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := range jobs {
|
||||
tags[i].meta, tags[i].found, tags[i].err = c.os.Stat(ctx, rels[i])
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := range rels {
|
||||
jobs <- i
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
for _, t := range tags {
|
||||
if t.err != nil {
|
||||
return out, t.err
|
||||
}
|
||||
}
|
||||
h, found, err := st.ReadHead(ctx)
|
||||
h, found, err := c.st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return out, err
|
||||
}
|
||||
if !found {
|
||||
return nil, ErrHeadAbsent
|
||||
return out, ErrHeadAbsent
|
||||
}
|
||||
if err := h.holderErr(me); err != nil {
|
||||
return nil, err
|
||||
if err := h.holderErr(c.me); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if h.Activity != (Activity{Kind: ActClean, Session: session}) {
|
||||
return nil, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, session)
|
||||
if h.Activity != (Activity{Kind: ActClean, Session: c.session}) {
|
||||
return out, fmt.Errorf("%w: HEAD has %s(%s), not clean(%s)", ErrNoSession, h.Activity.Kind, h.Activity.Session, c.session)
|
||||
}
|
||||
live, err := reachable(ctx, r, h, shard)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
roots := HeadRoots(h)
|
||||
if !c.rootsRead {
|
||||
c.roots = roots
|
||||
c.rootsRead = true
|
||||
} else {
|
||||
// Operators may un-name snapshots during a pass. Keep the initial superset
|
||||
// until this session ends, so chunks are not deleted beneath a root that the
|
||||
// earlier metadata phase retained. A new root requires a fresh pass/view.
|
||||
for _, rn := range roots {
|
||||
seen := false
|
||||
for _, old := range c.roots {
|
||||
if rn == old {
|
||||
seen = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !seen {
|
||||
return out, ErrPrecondition
|
||||
}
|
||||
}
|
||||
}
|
||||
var removed []ChunkName
|
||||
for _, c := range sorted {
|
||||
tag, planned := plan[c]
|
||||
if !planned || live[c] {
|
||||
live := map[string]bool{}
|
||||
if kind == PoolDir {
|
||||
if c.chunks == nil || c.shard != shard {
|
||||
c.chunks, err = reachable(ctx, c.r, c.roots, shard)
|
||||
c.shard = shard
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
for n := range c.chunks {
|
||||
live[n.Path()] = true
|
||||
}
|
||||
} else {
|
||||
if c.metadata == nil {
|
||||
c.metadata = map[string]bool{}
|
||||
for _, rn := range c.roots {
|
||||
img, e := c.r.Open(ctx, rn)
|
||||
if e != nil {
|
||||
c.metadata = nil
|
||||
return out, e
|
||||
}
|
||||
c.metadata[rn.Path()] = true
|
||||
for _, sn := range img.root.Segments {
|
||||
c.metadata[sn.Path()] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
live = c.metadata
|
||||
}
|
||||
for i, rel := range rels {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
tag := tags[i]
|
||||
if !tag.found || live[rel] {
|
||||
out.After = rel
|
||||
continue
|
||||
}
|
||||
if err := os.Mark(ctx, c.Path(), tag, session); err != nil {
|
||||
if err := c.os.Mark(ctx, rel, tag.meta, c.session); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
continue // written since the plan
|
||||
out.After = rel
|
||||
continue
|
||||
}
|
||||
return removed, fmt.Errorf("layout: mark %s: %w", c, err)
|
||||
return out, fmt.Errorf("layout: mark %s: %w", rel, err)
|
||||
}
|
||||
if err := os.DeleteMarked(ctx, c.Path(), session); err != nil {
|
||||
if err := c.os.DeleteMarked(ctx, rel, c.session); err != nil {
|
||||
if errors.Is(err, ErrPrecondition) {
|
||||
continue // reused since the mark
|
||||
out.After = rel
|
||||
continue
|
||||
}
|
||||
return removed, fmt.Errorf("layout: delete %s: %w", c, err)
|
||||
return out, fmt.Errorf("layout: delete %s: %w", rel, err)
|
||||
}
|
||||
removed = append(removed, c)
|
||||
out.Names = append(out.Names, rel)
|
||||
out.After = rel
|
||||
}
|
||||
return removed, nil
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RemoveUnreachable is the chunk-only compatibility boundary. A full pass uses
|
||||
// one Cleaner across its pages so each shard's reachable set is resolved once.
|
||||
func RemoveUnreachable(ctx context.Context, st HeadStore, r *Reader, os ObjectStore, me HolderID, session string, shard uint64, candidates []ChunkName) ([]ChunkName, error) {
|
||||
sorted := append([]ChunkName(nil), candidates...)
|
||||
sort.Slice(sorted, func(a, b int) bool { return sorted[a].Index < sorted[b].Index })
|
||||
var names []string
|
||||
for _, n := range sorted {
|
||||
if Shard(n.Index) == shard {
|
||||
names = append(names, n.String())
|
||||
}
|
||||
}
|
||||
cleaner := NewCleaner(st, r, os, me, session)
|
||||
cleaner.tagParallel = 1 // The chunk-only boundary preserves serial planning.
|
||||
res, err := cleaner.Page(ctx, PoolDir, shard, names)
|
||||
var removed []ChunkName
|
||||
for _, rel := range res.Names {
|
||||
for _, n := range sorted {
|
||||
if n.Path() == rel {
|
||||
removed = append(removed, n)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return removed, err
|
||||
}
|
||||
|
||||
// reachable returns this volume's chunk names in shard that any root in h
|
||||
// names. A root or segment that cannot be read is an error: nothing is
|
||||
// removed on a partial view.
|
||||
func reachable(ctx context.Context, r *Reader, h Head, shard uint64) (map[ChunkName]bool, error) {
|
||||
func reachable(ctx context.Context, r *Reader, roots []RootName, shard uint64) (map[ChunkName]bool, error) {
|
||||
own, err := r.VolumeID(ctx, r.vol)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
live := map[ChunkName]bool{}
|
||||
for _, rn := range HeadRoots(h) {
|
||||
for _, rn := range roots {
|
||||
if err := r.EachRef(ctx, rn, shard, func(_ uint64, ref Ref) bool {
|
||||
if ref.OwnerID == own {
|
||||
live[ref.Chunk] = true
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// All snapshot-removal transitions converge on DeleteSnapshot. Retention's
|
||||
// additional pin check must never bypass the dependent check on that same HEAD.
|
||||
func TestSnapshotWithDependentsSurvivesEveryRemovalTransition(t *testing.T) {
|
||||
for _, state := range []string{StateLive, StateDetached} {
|
||||
for _, call := range []string{"delete", "retire", "run-delete", "run-retire"} {
|
||||
t.Run(string(state)+"/"+call, func(t *testing.T) {
|
||||
h := idleHead()
|
||||
h.State = state
|
||||
rn := RootName{Hash: Sum([]byte("root"))}
|
||||
h.Current = &rn
|
||||
h.Snapshots = map[string]Snapshot{"dependent": {Root: rn, Dependents: deps(rn, "target")}}
|
||||
st := &memHead{h: &h}
|
||||
ctx := context.Background()
|
||||
var err error
|
||||
switch call {
|
||||
case "delete":
|
||||
_, _, err = h.DeleteSnapshot("dependent")
|
||||
case "retire":
|
||||
_, _, err = h.RetireSnapshot("dependent", 100)
|
||||
case "run-delete":
|
||||
_, err = RunDeleteSnapshot(ctx, st, "dependent")
|
||||
case "run-retire":
|
||||
_, err = RunRetireSnapshot(ctx, st, "dependent", 100)
|
||||
}
|
||||
if !errors.Is(err, ErrHasDependents) {
|
||||
t.Fatalf("dependent removal: %v", err)
|
||||
}
|
||||
if len(st.h.Snapshots["dependent"].Dependents) != 1 || st.h.Snapshots["dependent"].Root != rn {
|
||||
t.Fatal("dependent snapshot left HEAD")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,7 +109,14 @@ func TestHolderFunctions_RefuseAStaleHolder(t *testing.T) {
|
||||
t.Errorf("CheckCommitObjects by %s over a snap(s) HEAD held by %s passed", who, me.Holder)
|
||||
}
|
||||
}
|
||||
covered := map[string]bool{"RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true, "CheckCommitObjects": true, "commitChecked": true}
|
||||
// The constructor has no effect; every Page still checks the supplied holder.
|
||||
for who, caller := range callers {
|
||||
o, h, r, rn, _ := metadataFixture(t)
|
||||
if _, err := NewCleaner(&memHead{h: h}, r, o, caller, "c1").Page(context.Background(), RootDir, 0, []string{rn.String()}); !errors.Is(err, ErrNotHolder) || len(o.writes) != 0 {
|
||||
t.Errorf("Cleaner by %s: %v writes=%v", who, err, o.writes)
|
||||
}
|
||||
}
|
||||
covered := map[string]bool{"NewCleaner": true, "RemoveUnreachable": true, "Start": true, "startCheck": true, "DetachedBy": true, "CheckCommitObjects": true, "commitChecked": true}
|
||||
var missing []string
|
||||
for fname, src := range packageSources(t, false) {
|
||||
file, err := parser.ParseFile(token.NewFileSet(), fname, src, 0)
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestLayoutRemote_CleanAfterOverwriteAndSnapshotDelete(t *testing.T) {
|
||||
if _, err := lh.cat.DeleteSnapshot(ctx, lh.v, "s1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res := clean(); res.Removed != 1 {
|
||||
if res := clean(); res.Removed != 3 || res.Roots != 1 || res.Segments != 1 {
|
||||
t.Fatalf("clean after deleting s1: %+v; want exactly the overwritten chunk", res)
|
||||
}
|
||||
if after := poolObjects(t, lh.cat, lh.v); after != before-1 {
|
||||
|
||||
@@ -82,6 +82,33 @@ type pendingSnapshot struct {
|
||||
meta layout.SnapshotMeta
|
||||
}
|
||||
|
||||
// ProbeSnapshots reads only the snapshot names for maintenance scheduling. A
|
||||
// nil set means skipped: never wait behind a runtime call or probe inside an
|
||||
// open cut/cleaning. Holding mu across the read keeps a new local activity from
|
||||
// opening between the idle check and the read. This neither rolls back activity
|
||||
// nor changes the engine view; the cleaning kernel remains the safety gate.
|
||||
func (l *LayoutRemote) ProbeSnapshots(ctx context.Context) (map[string]struct{}, error) {
|
||||
if !l.mu.TryLock() {
|
||||
return nil, nil
|
||||
}
|
||||
defer l.mu.Unlock()
|
||||
if l.session != "" || l.cleaning != "" {
|
||||
return nil, nil
|
||||
}
|
||||
h, found, err := l.st.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, layout.ErrHeadAbsent
|
||||
}
|
||||
names := make(map[string]struct{}, len(h.Snapshots))
|
||||
for name := range h.Snapshots {
|
||||
names[name] = struct{}{}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
var (
|
||||
_ storage.ChunkRemote = (*LayoutRemote)(nil)
|
||||
_ storage.ChunkKeyer = (*LayoutRemote)(nil)
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
type probeReadCounter struct {
|
||||
sessionStore
|
||||
reads int
|
||||
absent bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *probeReadCounter) ReadHead(ctx context.Context) (layout.Head, bool, error) {
|
||||
s.reads++
|
||||
if s.err != nil || s.absent {
|
||||
return layout.Head{}, false, s.err
|
||||
}
|
||||
return s.sessionStore.ReadHead(ctx)
|
||||
}
|
||||
|
||||
func TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD(t *testing.T) {
|
||||
lh := newLayoutHost(t)
|
||||
r, err := NewLayoutRemote(lh.cat, lh.v, lh.me)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
probe, ok := any(r).(interface {
|
||||
ProbeSnapshots(context.Context) (map[string]struct{}, error)
|
||||
})
|
||||
if !ok {
|
||||
t.Fatal("layout runtime has no idle-only snapshot probe")
|
||||
}
|
||||
count := &probeReadCounter{sessionStore: r.st}
|
||||
r.st = count
|
||||
ctx := context.Background()
|
||||
names, err := probe.ProbeSnapshots(ctx)
|
||||
if err != nil || names == nil || count.reads != 1 {
|
||||
t.Fatalf("idle: %v %v reads=%d", names, err, count.reads)
|
||||
}
|
||||
r.mu.Lock()
|
||||
names, err = probe.ProbeSnapshots(ctx)
|
||||
r.mu.Unlock()
|
||||
if err != nil || names != nil || count.reads != 1 {
|
||||
t.Fatal("probe waited for busy runtime or read HEAD")
|
||||
}
|
||||
if _, err = r.Begin(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := count.reads
|
||||
names, err = probe.ProbeSnapshots(ctx)
|
||||
if err != nil || names != nil || count.reads != before {
|
||||
t.Fatal("probe read HEAD inside staged session")
|
||||
}
|
||||
if _, err = r.AbortOpenSession(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = r.Clean(ctx, func(context.Context, layout.HolderID, string) error {
|
||||
before := count.reads
|
||||
names, err := probe.ProbeSnapshots(ctx)
|
||||
if err != nil || names != nil || count.reads != before {
|
||||
t.Fatal("probe read HEAD during cleaning")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count.absent = true
|
||||
names, err = probe.ProbeSnapshots(ctx)
|
||||
if names != nil || !errors.Is(err, layout.ErrHeadAbsent) {
|
||||
t.Fatalf("absent HEAD: %v %v", names, err)
|
||||
}
|
||||
count.absent = false
|
||||
count.err = errors.New("filer unavailable")
|
||||
names, err = probe.ProbeSnapshots(ctx)
|
||||
if names != nil || !errors.Is(err, count.err) {
|
||||
t.Fatalf("failed HEAD: %v %v", names, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package chunkstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestLayoutStalledSessionYieldAllowsCleaning(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
lh := newLayoutHost(t)
|
||||
s, layer, remote := lh.attach("stalled", true, true)
|
||||
defer s.Close()
|
||||
data := block(71)
|
||||
key := remote.ChunkKey(0, layout.Sum(data))
|
||||
if err := remote.Put(ctx, key, data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clean := func() (removed int, err error) {
|
||||
err = remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error {
|
||||
st, reader, e := lh.cat.open(lh.v)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
r, e := layout.RemoveUnreachable(ctx, st, reader, st, me, session, layout.Shard(0), []layout.ChunkName{layout.NameChunk(0, data)})
|
||||
removed = len(r)
|
||||
return e
|
||||
})
|
||||
return
|
||||
}
|
||||
if _, err := clean(); !errors.Is(err, layout.ErrBusy) {
|
||||
t.Fatalf("cleaning an open session: %v", err)
|
||||
}
|
||||
stats := layer.Stats()
|
||||
if !layer.(storage.ChunkStagedDiscarder).DiscardStagedIfUnchanged(stats.StagedChunks, stats.CutSeq) {
|
||||
t.Fatal("idle stalled session was not discarded")
|
||||
}
|
||||
if n, err := clean(); err != nil || n != 1 {
|
||||
t.Fatalf("after yield: removed=%d err=%v; want the unreachable chunk removed", n, err)
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,9 @@ func TestLayoutRemoteSessionFieldSites(t *testing.T) {
|
||||
// Begin returns the session it opened; CASHead checks that it survived
|
||||
// a concurrent operator HEAD write before retrying, and keys its skip of
|
||||
// the object check to the session CheckCommit checked (checked.session).
|
||||
if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 5, "CheckCommit": 2, "prepareCommitLocked": 1, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1}) {
|
||||
// ProbeSnapshots skips open activity
|
||||
// (TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD).
|
||||
if !reflect.DeepEqual(fields, map[string]int{"openSessionLocked": 2, "rollBackLocked": 1, "Begin": 1, "PutPaced": 1, "CASHead": 5, "CheckCommit": 2, "prepareCommitLocked": 1, "CommitPendingSnapshot": 2, "writeRootLocked": 1, "Clean": 1, "syncSessionLocked": 3, "takeAbandonLocked": 1, "ProbeSnapshots": 1}) {
|
||||
t.Fatal("session field sites changed; enumerate and probe them", fields)
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,7 @@ type snapshotSchedule struct {
|
||||
next time.Time
|
||||
failure *ScheduledSnapshotFailure
|
||||
attempts int
|
||||
stalled int // consecutive failed attempts without new staging
|
||||
skipped map[string]int64
|
||||
}
|
||||
|
||||
@@ -130,15 +131,16 @@ func (s *snapshotSchedule) record(now time.Time, err error) {
|
||||
var skip *SnapshotSkip
|
||||
switch {
|
||||
case err == nil:
|
||||
s.lastOK, s.failure, s.attempts = now, nil, 0
|
||||
s.lastOK, s.failure, s.attempts, s.stalled = now, nil, 0, 0
|
||||
s.next = s.slotAfter(now)
|
||||
case errors.As(err, &skip):
|
||||
s.skipped[skip.Reason]++
|
||||
s.next = earlier(now.Add(snapshotRetryMax), s.slotAfter(now))
|
||||
default:
|
||||
s.attempts++
|
||||
s.stalled++
|
||||
s.failure = &ScheduledSnapshotFailure{Code: snapshotFailureCode(err), AtNs: now.UnixNano()}
|
||||
backoff := snapshotRetryMin << min(s.attempts-1, 30)
|
||||
backoff := snapshotRetryMin << min(s.stalled-1, 30)
|
||||
if backoff > snapshotRetryMax || backoff <= 0 {
|
||||
backoff = snapshotRetryMax
|
||||
}
|
||||
@@ -190,8 +192,42 @@ func earlier(a, b time.Time) time.Time {
|
||||
// snapshotSlot guards one running loop's schedule: the loop records
|
||||
// outcomes, status readers read it.
|
||||
type snapshotSlot struct {
|
||||
mu sync.Mutex
|
||||
s *snapshotSchedule
|
||||
mu sync.Mutex
|
||||
s *snapshotSchedule
|
||||
dueNow chan struct{} // coalesced explicit trigger; set before the loop starts
|
||||
workerDone chan struct{} // the snapshot worker, not the aggregate background group
|
||||
workerCtx context.Context
|
||||
}
|
||||
|
||||
// ScheduleSnapshotNow asks the existing daily/weekly loop for an attempt now.
|
||||
// It neither creates a second snapshot writer nor changes the configured slots.
|
||||
func (p *DurableProvider) ScheduleSnapshotNow(volumeID string) bool {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
h := p.volumes[volumeID]
|
||||
if h == nil || h.snapshots == nil || h.snapshots.dueNow == nil || h.chunkStop == nil || h.chunkDone == nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-h.chunkDone:
|
||||
return false
|
||||
default:
|
||||
}
|
||||
h.snapshots.mu.Lock()
|
||||
defer h.snapshots.mu.Unlock()
|
||||
if h.snapshots.workerDone == nil || h.snapshots.workerCtx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-h.snapshots.workerDone:
|
||||
return false
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case h.snapshots.dueNow <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (sl *snapshotSlot) status(now time.Time) ScheduledSnapshotStatus {
|
||||
@@ -218,7 +254,12 @@ func (sl *snapshotSlot) record(now time.Time, err error) {
|
||||
// the snapshot record. An attempt cut short by the loop's own end is not
|
||||
// recorded. chunkBackground joins it with its other workers
|
||||
// (INV-MAINT-JOIN).
|
||||
func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot) {
|
||||
func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, slot *snapshotSlot, attempted func(storage.ChunkLayerStats, storage.ChunkLayerStats, error)) {
|
||||
slot.mu.Lock()
|
||||
workerDone := make(chan struct{})
|
||||
slot.workerDone, slot.workerCtx = workerDone, ctx
|
||||
slot.mu.Unlock()
|
||||
defer close(workerDone)
|
||||
timer := time.NewTimer(time.Until(slot.due()))
|
||||
defer timer.Stop()
|
||||
timeout := 2 * p.cfg.ChunkCutTimeout
|
||||
@@ -234,11 +275,19 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
case <-slot.dueNow:
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil || layer.Fenced() || !current() {
|
||||
return
|
||||
}
|
||||
at := time.Now()
|
||||
before := layer.Stats()
|
||||
var err error
|
||||
if layer.Stats().AbsentChunks > 0 {
|
||||
// Restoring: HEAD names chunks this volume has not fetched yet.
|
||||
@@ -251,7 +300,17 @@ func (p *DurableProvider) chunkSnapshotLoop(ctx context.Context, volumeID string
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
after := layer.Stats()
|
||||
if attempted != nil {
|
||||
attempted(before, after, err)
|
||||
}
|
||||
slot.record(time.Now(), err)
|
||||
if err != nil && after.StagedChunks > before.StagedChunks {
|
||||
slot.mu.Lock()
|
||||
slot.s.next = time.Now()
|
||||
slot.s.stalled = 0 // progress breaks the backoff, not the reported attempt count
|
||||
slot.mu.Unlock()
|
||||
}
|
||||
if err != nil {
|
||||
next := time.Until(slot.due()).Round(time.Second)
|
||||
if note, stuck := capturePendingNote(err); stuck {
|
||||
|
||||
@@ -31,7 +31,7 @@ func TestChunkLoop_EndsWhenTheLayerIsFenced(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan struct{})
|
||||
go p.chunkLoop(ctx, "v1", layer, done, nil)
|
||||
go p.chunkLoop(ctx, "v1", layer, done, nil, nil)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for layer.cuts.Load() == 0 {
|
||||
if time.Now().After(deadline) {
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/hostlimit"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
// The public layer counters report completed staging even when its cut times out.
|
||||
type progressLoopLayer struct {
|
||||
storage.ChunkLayer
|
||||
staged atomic.Uint64
|
||||
calls atomic.Int32
|
||||
}
|
||||
|
||||
func (l *progressLoopLayer) Fenced() bool { return false }
|
||||
func (l *progressLoopLayer) Stats() storage.ChunkLayerStats {
|
||||
return storage.ChunkLayerStats{StagedChunks: l.staged.Load()}
|
||||
}
|
||||
func (l *progressLoopLayer) Cut(context.Context) (storage.ChunkCutResult, error) {
|
||||
l.calls.Add(1)
|
||||
l.staged.Add(1)
|
||||
return storage.ChunkCutResult{}, context.DeadlineExceeded
|
||||
}
|
||||
|
||||
func TestCutLoopProgressRetriesWithoutBackoff(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
layer := &progressLoopLayer{}
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go p.chunkLoop(ctx, "progress", layer, done, nil, nil)
|
||||
defer func() { cancel(); <-done }()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
if n := layer.calls.Load(); n < 3 {
|
||||
t.Fatalf("only %d attempts despite new staged chunks; progress must retry at the next poll, without backoff or minimum spacing", n)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestScheduledSnapshotProgressRetriesWithoutBackoff(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
layer := &progressLoopLayer{}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
calls := 0
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkScheduledSnapshot: func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error {
|
||||
calls++
|
||||
if calls < 3 {
|
||||
layer.staged.Add(1)
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return nil
|
||||
}}}
|
||||
slot := &snapshotSlot{s: newSnapshotSchedule("v1", 24*time.Hour, time.Now())}
|
||||
slot.s.next = time.Now()
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkSnapshotLoop(ctx, "v1", layer, func() bool { return true }, slot, nil)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
synctest.Wait()
|
||||
if calls != 3 {
|
||||
t.Fatalf("got %d attempts, want two progress retries then success without advancing the clock", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type firstAttemptLayer struct {
|
||||
progressLoopLayer
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (l *firstAttemptLayer) Stats() storage.ChunkLayerStats {
|
||||
return storage.ChunkLayerStats{DirtyChunks: 1, CutsFailed: uint64(l.calls.Load())}
|
||||
}
|
||||
func (l *firstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) {
|
||||
select {
|
||||
case l.entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-l.release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
l.calls.Add(1)
|
||||
return storage.ChunkCutResult{}, context.DeadlineExceeded
|
||||
}
|
||||
func TestDirtyStartCleaningWaitsForFirstCutAttempt(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
var cleaned atomic.Int32
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}}
|
||||
kick := make(chan struct{}, 1)
|
||||
kick <- struct{}{}
|
||||
go p.chunkBackground(ctx, cancel, "dirty", layer, done, func() bool { return true }, nil, nil, kick)
|
||||
defer func() { cancel(); <-done }()
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
select {
|
||||
case <-layer.entered:
|
||||
default:
|
||||
t.Fatal("first cut did not start")
|
||||
}
|
||||
if n := cleaned.Load(); n != 0 {
|
||||
t.Fatalf("%d cleaning passes ran before the dirty start's first cut returned", n)
|
||||
}
|
||||
close(layer.release)
|
||||
time.Sleep(2 * chunkSchedulePoll)
|
||||
synctest.Wait()
|
||||
if cleaned.Load() == 0 {
|
||||
t.Fatal("cleaning never ran after the first cut attempt")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type yieldingLayer struct {
|
||||
progressLoopLayer
|
||||
progressAt int32
|
||||
absent int
|
||||
err error
|
||||
discarded atomic.Int32
|
||||
}
|
||||
|
||||
func (l *yieldingLayer) Stats() storage.ChunkLayerStats {
|
||||
return storage.ChunkLayerStats{DirtyChunks: 1, StagedChunks: l.staged.Load(), CutsFailed: uint64(l.calls.Load()), AbsentChunks: l.absent}
|
||||
}
|
||||
func (l *yieldingLayer) Cut(context.Context) (storage.ChunkCutResult, error) {
|
||||
if l.calls.Add(1) == l.progressAt {
|
||||
l.staged.Add(1)
|
||||
}
|
||||
if l.err != nil {
|
||||
return storage.ChunkCutResult{}, l.err
|
||||
}
|
||||
return storage.ChunkCutResult{}, context.DeadlineExceeded
|
||||
}
|
||||
func (l *yieldingLayer) DiscardStagedIfUnchanged(staged, seq uint64) bool {
|
||||
l.discarded.Add(1)
|
||||
return true
|
||||
}
|
||||
func TestStalledCutYieldsSessionToCleaning(t *testing.T) {
|
||||
for _, progress := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "K_zero_progress", true: "progress_resets_K"}[progress], func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &yieldingLayer{}
|
||||
if progress {
|
||||
layer.progressAt = chunkZeroProgressLimit
|
||||
}
|
||||
var cleaned atomic.Int32
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error {
|
||||
if layer.discarded.Load() == 0 {
|
||||
t.Error("cleaning ran with the stalled session still open")
|
||||
}
|
||||
cleaned.Add(1)
|
||||
return nil
|
||||
}}}
|
||||
kick := make(chan struct{}, 1)
|
||||
go p.chunkBackground(ctx, cancel, "stalled", layer, done, func() bool { return true }, nil, nil, kick)
|
||||
defer func() { cancel(); <-done }()
|
||||
time.Sleep(3500 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
if progress {
|
||||
if layer.discarded.Load() != 0 || cleaned.Load() != 0 {
|
||||
t.Fatal("K-1 stalls followed by progress discarded a live session")
|
||||
}
|
||||
} else if layer.discarded.Load() != 1 || cleaned.Load() != 1 {
|
||||
t.Fatalf("discarded=%d cleaning=%d; K stalls must release the session and kick a pass", layer.discarded.Load(), cleaned.Load())
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirtyStartWithPeriodicCutsOffWaitsForRequestOrInterval(t *testing.T) {
|
||||
for _, request := range []bool{false, true} {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})}
|
||||
var cleaned atomic.Int32
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkMaintenanceInterval: time.Second, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}}
|
||||
kick := make(chan struct{}, 1)
|
||||
kick <- struct{}{}
|
||||
go p.chunkBackground(ctx, cancel, "request", layer, done, func() bool { return true }, nil, nil, kick)
|
||||
defer func() { cancel(); <-done }()
|
||||
synctest.Wait()
|
||||
if request {
|
||||
go layer.Cut(ctx)
|
||||
}
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
if cleaned.Load() != 0 {
|
||||
t.Fatal("cleaning ran before any request cut finished or the interval elapsed")
|
||||
}
|
||||
if request {
|
||||
close(layer.release)
|
||||
}
|
||||
time.Sleep(2 * chunkSchedulePoll)
|
||||
synctest.Wait()
|
||||
if request && cleaned.Load() != 1 {
|
||||
t.Fatal("cleaning did not observe the request cut's completion")
|
||||
}
|
||||
if !request {
|
||||
if cleaned.Load() != 0 {
|
||||
t.Fatal("no-attempt fallback ran before the interval")
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
if cleaned.Load() != 1 {
|
||||
t.Fatal("no-attempt fallback did not run after one interval")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnadmittedAttemptsDoNotDiscardStaging(t *testing.T) {
|
||||
for _, skip := range []bool{false, true} {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &yieldingLayer{err: storage.ErrChunkCaptureRefused}
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: 30 * 24 * time.Hour, ChunkMaintenance: func(context.Context, string) error { return nil }}}
|
||||
var snapshots *snapshotSlot
|
||||
wait := 8 * time.Second
|
||||
if skip {
|
||||
p.cfg.ChunkCaptureInterval = 0
|
||||
layer.absent = 1
|
||||
wait = 4 * time.Hour
|
||||
p.cfg.ChunkScheduledSnapshot = func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error {
|
||||
t.Error("restoring snapshot reached store")
|
||||
return nil
|
||||
}
|
||||
snapshots = &snapshotSlot{s: newSnapshotSchedule("skip", 24*time.Hour, time.Now())}
|
||||
snapshots.s.next = time.Now()
|
||||
}
|
||||
go p.chunkBackground(ctx, cancel, "unadmitted", layer, done, func() bool { return true }, snapshots, nil, make(chan struct{}, 1))
|
||||
defer func() { cancel(); <-done }()
|
||||
time.Sleep(wait)
|
||||
synctest.Wait()
|
||||
if skip {
|
||||
snapshots.mu.Lock()
|
||||
n := snapshots.s.skipped[SnapshotSkipRestoring]
|
||||
snapshots.mu.Unlock()
|
||||
if n < 3 {
|
||||
t.Fatal("did not exercise three snapshot skips")
|
||||
}
|
||||
} else if layer.calls.Load() < 3 {
|
||||
t.Fatal("did not exercise three capture refusals")
|
||||
}
|
||||
if layer.discarded.Load() != 0 {
|
||||
t.Fatal("unadmitted attempts discarded an unfinished session")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestStagingBreaksBackgroundStallStreak(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &yieldingLayer{}
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond, ChunkMaintenanceInterval: time.Hour, ChunkMaintenance: func(context.Context, string) error { return nil }}}
|
||||
go p.chunkBackground(ctx, cancel, "request-progress", layer, done, func() bool { return true }, nil, nil, make(chan struct{}, 1))
|
||||
defer func() { cancel(); <-done }()
|
||||
time.Sleep(2 * time.Second)
|
||||
synctest.Wait()
|
||||
if layer.calls.Load() != 2 {
|
||||
t.Fatalf("want K-1 background stalls, got %d", layer.calls.Load())
|
||||
}
|
||||
layer.staged.Add(1) // an interposed request stages a new chunk and fails
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
synctest.Wait()
|
||||
if layer.calls.Load() != 3 || layer.discarded.Load() != 0 {
|
||||
t.Fatalf("calls=%d discarded=%d: request progress must reset the streak", layer.calls.Load(), layer.discarded.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type timedProgressLayer struct {
|
||||
progressLoopLayer
|
||||
times chan time.Time
|
||||
}
|
||||
|
||||
func (l *timedProgressLayer) Cut(context.Context) (storage.ChunkCutResult, error) {
|
||||
if l.calls.Add(1) == 1 {
|
||||
l.staged.Add(1)
|
||||
}
|
||||
l.times <- time.Now()
|
||||
return storage.ChunkCutResult{}, context.DeadlineExceeded
|
||||
}
|
||||
func TestProgressThenTwoStallsKeepDoublingWaits(t *testing.T) {
|
||||
for _, scheduled := range []bool{false, true} {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &timedProgressLayer{times: make(chan time.Time, 16)}
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkCaptureInterval: time.Millisecond}}
|
||||
duration, unit := 3500*time.Millisecond, time.Second
|
||||
if scheduled {
|
||||
unit = time.Minute
|
||||
duration = 3*time.Minute + time.Second
|
||||
p.cfg.ChunkScheduledSnapshot = func(ctx context.Context, _ string, _ time.Time, _ func(context.Context) (storage.ChunkHead, error)) error {
|
||||
_, err := layer.Cut(ctx)
|
||||
return err
|
||||
}
|
||||
slot := &snapshotSlot{s: newSnapshotSchedule("waits", 24*time.Hour, time.Now())}
|
||||
slot.s.next = time.Now()
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkSnapshotLoop(ctx, "waits", layer, func() bool { return true }, slot, nil)
|
||||
}()
|
||||
} else {
|
||||
go p.chunkLoop(ctx, "waits", layer, done, nil, nil)
|
||||
}
|
||||
defer func() { cancel(); <-done }()
|
||||
time.Sleep(duration)
|
||||
synctest.Wait()
|
||||
if len(layer.times) != 4 {
|
||||
t.Fatalf("got %d attempts, want four", len(layer.times))
|
||||
}
|
||||
ts := []time.Time{<-layer.times, <-layer.times, <-layer.times, <-layer.times}
|
||||
if ts[1].Sub(ts[0]) > chunkSchedulePoll || ts[2].Sub(ts[1]) != unit || ts[3].Sub(ts[2]) != 2*unit {
|
||||
t.Fatalf("retry gaps=%v,%v,%v; want immediate,%v,%v", ts[1].Sub(ts[0]), ts[2].Sub(ts[1]), ts[3].Sub(ts[2]), unit, 2*unit)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Refusals change the engine's refusal counters without completing a store cut.
|
||||
type refusedFirstAttemptLayer struct {
|
||||
firstAttemptLayer
|
||||
requests atomic.Int32
|
||||
}
|
||||
|
||||
func (l *refusedFirstAttemptLayer) Stats() storage.ChunkLayerStats {
|
||||
st := l.firstAttemptLayer.Stats()
|
||||
st.CutsRefused = map[string]uint64{"admission": uint64(min(l.requests.Load(), 2))}
|
||||
return st
|
||||
}
|
||||
|
||||
func (l *refusedFirstAttemptLayer) Cut(ctx context.Context) (storage.ChunkCutResult, error) {
|
||||
if l.requests.Add(1) <= 2 {
|
||||
return storage.ChunkCutResult{}, storage.ErrChunkCaptureRefused
|
||||
}
|
||||
return l.firstAttemptLayer.Cut(ctx)
|
||||
}
|
||||
|
||||
func TestDirtyStartCaptureRefusalsDoNotReleaseCleaning(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
layer := &refusedFirstAttemptLayer{firstAttemptLayer: firstAttemptLayer{entered: make(chan struct{}, 1), release: make(chan struct{})}}
|
||||
var cleaned atomic.Int32
|
||||
const volume = "refused-first-cut"
|
||||
const interval = time.Hour
|
||||
p := &DurableProvider{cfg: ProviderConfig{ChunkStagger: true, ChunkMaintenanceInterval: interval, ChunkMaintenance: func(context.Context, string) error { cleaned.Add(1); return nil }}}
|
||||
go p.chunkBackground(ctx, cancel, volume, layer, done, func() bool { return true }, nil, nil, nil)
|
||||
defer func() { cancel(); <-done }()
|
||||
synctest.Wait()
|
||||
for range 2 {
|
||||
if _, err := layer.Cut(ctx); err != storage.ErrChunkCaptureRefused {
|
||||
t.Fatalf("expected capture refusal, got %v", err)
|
||||
}
|
||||
}
|
||||
// Pass the ordinary staggered cleaning time, before the fallback bound.
|
||||
due := hostlimit.Phase(volume+":maintenance", interval)
|
||||
if due+4*chunkSchedulePoll >= interval {
|
||||
t.Fatal("fixture needs room before the no-attempt fallback")
|
||||
}
|
||||
time.Sleep(due + 2*chunkSchedulePoll)
|
||||
synctest.Wait()
|
||||
if cleaned.Load() != 0 {
|
||||
t.Fatal("two capture refusals released first cleaning without a store attempt")
|
||||
}
|
||||
go layer.Cut(ctx)
|
||||
synctest.Wait()
|
||||
if cleaned.Load() != 0 {
|
||||
t.Fatal("cleaning ran while the first real attempt was still in flight")
|
||||
}
|
||||
close(layer.release)
|
||||
time.Sleep(2 * chunkSchedulePoll)
|
||||
synctest.Wait()
|
||||
if cleaned.Load() != 1 {
|
||||
t.Fatal("first completed store attempt did not release cleaning")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package durable_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"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"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/durable/testutil"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type stalledLayoutUpload struct {
|
||||
*chunkstore.LayoutRemote
|
||||
puts atomic.Int32
|
||||
}
|
||||
|
||||
func (r *stalledLayoutUpload) Put(context.Context, string, []byte) error {
|
||||
r.puts.Add(1)
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
|
||||
// Three actual failed cut attempts must reach guarded discard, the provider's
|
||||
// maintenance kick, and the real kernel's conditional removal in one run.
|
||||
func TestStalledBackgroundCutsCleanRealLayout(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
fixture := testutil.NewLayoutFixture(t, "v1", pcBlocks, pcChunkBlocks)
|
||||
ready := make(chan struct{})
|
||||
cleaned := make(chan int, 1)
|
||||
var remote *stalledLayoutUpload
|
||||
var p *durable.DurableProvider
|
||||
cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: pcBlocks, BlockSize: 4096, ChunkBlocks: pcChunkBlocks, ChunkCOWSpillLimit: 2 * pcChunkBlocks * 4096,
|
||||
ChunkSnapshotPeriod: time.Second, ChunkCutTimeout: 100 * time.Millisecond, ChunkMaintenanceInterval: 24 * time.Hour}
|
||||
fixture.Configure(&cfg)
|
||||
original := cfg.ChunkLayoutRemoteFor
|
||||
cfg.ChunkLayoutRemoteFor = func(v string, me layout.HolderID) (storage.ChunkRemote, error) {
|
||||
r, err := original(v, me)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remote = &stalledLayoutUpload{LayoutRemote: r.(*chunkstore.LayoutRemote)}
|
||||
return remote, nil
|
||||
}
|
||||
cfg.ChunkScheduledSnapshot = func(ctx context.Context, _ string, _ time.Time, cut func(context.Context) (storage.ChunkHead, error)) error {
|
||||
select {
|
||||
case <-ready:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
_, err := cut(ctx)
|
||||
return err
|
||||
}
|
||||
cfg.ChunkMaintenance = func(ctx context.Context, _ string) error {
|
||||
if remote.puts.Load() < 3 || fcutStats(t, p).CutsFailed != 3 {
|
||||
t.Error("cleaning ran before K actual failed store attempts")
|
||||
}
|
||||
return remote.Clean(ctx, func(ctx context.Context, me layout.HolderID, session string) error {
|
||||
st, err := fixture.Catalog.Store(fixture.Ref)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader, err := layout.NewReader("/provider-test", fixture.Ref.Dir(), st.Fetch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := layout.RemoveUnreachable(ctx, st, reader, st, me, session, layout.Shard(15), []layout.ChunkName{layout.NameChunk(15, block(99))})
|
||||
select {
|
||||
case cleaned <- len(result):
|
||||
default:
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
p, err := durable.NewDurableProvider(cfg, v1View())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer p.Close()
|
||||
st := fcutOpen(t, context.Background(), p)
|
||||
for i := 0; i < 4; i++ {
|
||||
if _, err := st.Write(uint32(i*pcChunkBlocks), block(byte(i+1))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := st.Sync(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data := block(99)
|
||||
if err := remote.LayoutRemote.Put(context.Background(), remote.ChunkKey(15, layout.Sum(data)), data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
close(ready)
|
||||
time.Sleep(4 * time.Minute)
|
||||
synctest.Wait()
|
||||
select {
|
||||
case n := <-cleaned:
|
||||
if n != 1 {
|
||||
t.Fatalf("cleaning removed=%d, want the orphan", n)
|
||||
}
|
||||
default:
|
||||
t.Fatal("K failed attempts never kicked real cleaning")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func runLoop(t *testing.T, p *DurableProvider, kick chan struct{}) {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", maintenanceStubLayer{}, func() bool { return true }, kick)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", maintenanceStubLayer{}, func() bool { return true }, kick, nil)
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
|
||||
@@ -13,7 +13,8 @@ import (
|
||||
|
||||
type maintenanceStubLayer struct{ storage.ChunkLayer }
|
||||
|
||||
func (maintenanceStubLayer) Fenced() bool { return false }
|
||||
func (maintenanceStubLayer) Fenced() bool { return false }
|
||||
func (maintenanceStubLayer) Stats() storage.ChunkLayerStats { return storage.ChunkLayerStats{} }
|
||||
func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) {
|
||||
for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} {
|
||||
t.Run(field, func(t *testing.T) {
|
||||
@@ -43,7 +44,7 @@ func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) {
|
||||
p.cfg.ChunkMaintenance = func(context.Context, string) error { calls++; return nil }
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) }, nil)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return p.maintenanceCurrent("v1", h, layer, lin) }, nil, nil)
|
||||
if calls != 0 {
|
||||
t.Fatalf("foreign attachment admitted %d passes", calls)
|
||||
}
|
||||
@@ -117,7 +118,7 @@ func TestMaintenanceRefusalReachesTheLayer(t *testing.T) {
|
||||
}}}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
go p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil)
|
||||
go p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil, nil)
|
||||
select {
|
||||
case err := <-layer.seen:
|
||||
if !errors.Is(err, storage.ErrChunkLayerFenced) {
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
type maintenanceProbeStore struct {
|
||||
storage.ChunkRemote
|
||||
head layout.Head
|
||||
found bool
|
||||
err error
|
||||
reads int
|
||||
}
|
||||
|
||||
func TestMaintenanceSnapshotProbeKeepsBusyRetryAndDirtyStartGate(t *testing.T) {
|
||||
for _, dirty := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "busy", true: "dirty-start"}[dirty], func(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}}}}
|
||||
layer := &firstAttemptLayer{}
|
||||
passes := 0
|
||||
p := &DurableProvider{cfg: ProviderConfig{
|
||||
ChunkMaintenanceInterval: time.Hour,
|
||||
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return nil, nil },
|
||||
ChunkMaintenance: func(context.Context, string) error {
|
||||
passes++
|
||||
if passes == 1 {
|
||||
return layout.ErrBusy
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}}
|
||||
var start *maintenanceStart
|
||||
if dirty {
|
||||
start = &maintenanceStart{deadline: time.Now().Add(time.Hour)}
|
||||
}
|
||||
p.volumes = map[string]*volHandle{"v1": {layoutRemote: st}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", layer, func() bool { return true }, nil, start)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
synctest.Wait()
|
||||
delete(st.head.Snapshots, "a")
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if dirty {
|
||||
if passes != 0 {
|
||||
t.Fatal("snapshot probe bypassed first store attempt")
|
||||
}
|
||||
layer.calls.Add(1)
|
||||
time.Sleep(chunkSchedulePoll)
|
||||
synctest.Wait()
|
||||
}
|
||||
if passes != 1 {
|
||||
t.Fatalf("first pass=%d", passes)
|
||||
}
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 2 {
|
||||
t.Fatalf("busy retry=%d; waited for ordinary interval", passes)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *maintenanceProbeStore) ReadHead(context.Context) (layout.Head, bool, error) {
|
||||
s.reads++
|
||||
return s.head, s.found, s.err
|
||||
}
|
||||
|
||||
func (s *maintenanceProbeStore) ProbeSnapshots(ctx context.Context) (map[string]struct{}, error) {
|
||||
h, found, err := s.ReadHead(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !found {
|
||||
return nil, layout.ErrHeadAbsent
|
||||
}
|
||||
names := make(map[string]struct{}, len(h.Snapshots))
|
||||
for n := range h.Snapshots {
|
||||
names[n] = struct{}{}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func TestMaintenanceNoticesSnapshotDeleteWithoutNotification(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
st := &maintenanceProbeStore{found: true, head: layout.Head{Snapshots: map[string]layout.Snapshot{"a": {}, "b": {}}}}
|
||||
passes := 0
|
||||
p := &DurableProvider{cfg: ProviderConfig{
|
||||
ChunkMaintenanceInterval: time.Hour,
|
||||
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return nil, nil },
|
||||
ChunkMaintenance: func(context.Context, string) error { passes++; return nil },
|
||||
}}
|
||||
p.volumes = map[string]*volHandle{"v1": {layoutRemote: st}}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkMaintenanceLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return true }, nil, nil)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
synctest.Wait()
|
||||
if st.reads != 1 || passes != 0 {
|
||||
t.Fatalf("baseline: reads=%d passes=%d", st.reads, passes)
|
||||
}
|
||||
delete(st.head.Snapshots, "a")
|
||||
st.err = errors.New("filer unavailable")
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 0 {
|
||||
t.Fatal("failed read inferred a deletion")
|
||||
}
|
||||
st.err = nil
|
||||
st.found = false
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 0 {
|
||||
t.Fatal("absent HEAD inferred a deletion")
|
||||
}
|
||||
st.found = true
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 1 || st.reads != 4 {
|
||||
t.Fatalf("delete: reads=%d passes=%d", st.reads, passes)
|
||||
}
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 1 || st.reads != 5 {
|
||||
t.Fatalf("unchanged: reads=%d passes=%d", st.reads, passes)
|
||||
}
|
||||
st.head.Snapshots["c"] = layout.Snapshot{}
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 1 {
|
||||
t.Fatal("growing snapshot set triggered cleaning")
|
||||
}
|
||||
delete(st.head.Snapshots, "c")
|
||||
st.head.Snapshots["d"] = layout.Snapshot{} // equal count still contains a deletion
|
||||
time.Sleep(30 * time.Second)
|
||||
synctest.Wait()
|
||||
if passes != 2 {
|
||||
t.Fatal("new snapshot's deletion was not noticed")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -432,7 +432,7 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st
|
||||
if !snapshotsOn {
|
||||
h.snapshots = nil
|
||||
} else if h.snapshots == nil {
|
||||
h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now())}
|
||||
h.snapshots = &snapshotSlot{s: newSnapshotSchedule(volumeID, p.cfg.ChunkSnapshotPeriod, time.Now()), dueNow: make(chan struct{}, 1)}
|
||||
}
|
||||
if p.cfg.ChunkCaptureInterval <= 0 {
|
||||
h.cutWait = nil
|
||||
@@ -693,11 +693,12 @@ func (r *closeBoundRemote) Abort() { r.ChunkRemote.Abort() }
|
||||
|
||||
// Cut scheduler constants (B9 W3 ruling).
|
||||
const (
|
||||
chunkSchedulePoll = 100 * time.Millisecond
|
||||
chunkCutMinSpacing = time.Second
|
||||
chunkCutBackoffMin = time.Second
|
||||
chunkCutBackoffMax = 30 * time.Second
|
||||
chunkSlotDelayMax = 200 * time.Millisecond
|
||||
chunkSchedulePoll = 100 * time.Millisecond
|
||||
chunkCutMinSpacing = time.Second
|
||||
chunkCutBackoffMin = time.Second
|
||||
chunkCutBackoffMax = 30 * time.Second
|
||||
chunkSlotDelayMax = 200 * time.Millisecond
|
||||
chunkZeroProgressLimit = 3 // yield an unfinished session to cleaning after this many stalled attempts
|
||||
)
|
||||
|
||||
// cutPolicy decides when an automatic cut is due. The remote holds
|
||||
@@ -709,7 +710,8 @@ const (
|
||||
// - the dirty-chunk count never triggers a cut;
|
||||
// - automatic cuts are at least minSpacing apart (explicit ones are not
|
||||
// subject to it);
|
||||
// - a failed automatic cut resets nothing and is retried after a backoff
|
||||
// - a failed cut with new staging retries at the next poll; without
|
||||
// progress it resets nothing and is retried after a backoff
|
||||
// doubling from backoffMin to backoffMax; any later successful cut (a
|
||||
// no-op cut and an explicit cut included) clears the backoff and
|
||||
// restarts the timer;
|
||||
@@ -837,6 +839,18 @@ func (pol cutPolicy) after(s cutSchedule, start, end time.Time, err error, seq u
|
||||
return s
|
||||
}
|
||||
|
||||
// afterStaging retries at the next poll when a failed attempt completed new
|
||||
// staging. Minimum spacing and exponential backoff apply only without progress.
|
||||
func (pol cutPolicy) afterStaging(s cutSchedule, start, end time.Time, err error, seq, staged uint64) cutSchedule {
|
||||
s = pol.after(s, start, end, err, seq)
|
||||
if err != nil && staged > 0 {
|
||||
s.lastAuto = time.Time{}
|
||||
s.backoff = 0
|
||||
s.retryAt = end
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// initialCutSchedule starts a fresh schedule at now; seq is the layer's
|
||||
// CutSeq at start, so a cut already made is not taken in as new.
|
||||
func initialCutSchedule(volumeID string, interval time.Duration, now time.Time, stagger bool, seq uint64) cutSchedule {
|
||||
@@ -853,7 +867,7 @@ func initialCutSchedule(volumeID string, interval time.Duration, now time.Time,
|
||||
// cut (not a healthy primary of this lineage, BASE install) is expected
|
||||
// and logged only when it is something else. A fenced layer can never
|
||||
// publish again: the loop ends.
|
||||
func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}, wait *cutWaitSlot) {
|
||||
func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, done chan struct{}, wait *cutWaitSlot, attempted func(storage.ChunkLayerStats, storage.ChunkLayerStats, error)) {
|
||||
defer close(done)
|
||||
pol := cutPolicy{
|
||||
interval: p.cfg.ChunkCaptureInterval,
|
||||
@@ -900,6 +914,9 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
trace("cut", ls.LastCutNs, skipped)
|
||||
}
|
||||
if skipped {
|
||||
if attempted != nil {
|
||||
attempted(ls, layer.Stats(), nil)
|
||||
}
|
||||
cancel()
|
||||
continue
|
||||
}
|
||||
@@ -910,7 +927,11 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
s = pol.after(s, start, time.Now(), err, layer.Stats().CutSeq)
|
||||
after := layer.Stats()
|
||||
if attempted != nil {
|
||||
attempted(ls, after, err)
|
||||
}
|
||||
s = pol.afterStaging(s, start, time.Now(), err, after.CutSeq, after.StagedChunks-ls.StagedChunks)
|
||||
wait.record(s)
|
||||
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
|
||||
if note, stuck := capturePendingNote(err); stuck {
|
||||
@@ -925,25 +946,73 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
|
||||
// chunkBackground owns both workers and their cancellation. A fence is observed
|
||||
// even while either worker is waiting on a cooperative remote call. INV-MAINT-JOIN:
|
||||
// done closes only after every admitted worker has returned.
|
||||
func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot, cutWait *cutWaitSlot, kick <-chan struct{}) {
|
||||
func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.CancelFunc, volumeID string, layer storage.ChunkLayer, done chan struct{}, current func() bool, snapshots *snapshotSlot, cutWait *cutWaitSlot, kick chan struct{}) {
|
||||
defer close(done)
|
||||
defer cancel()
|
||||
var workers sync.WaitGroup
|
||||
// Both background publishers share this in-process stall count. The layer
|
||||
// rechecks its counters under its capture lock before discarding anything.
|
||||
var attemptMu sync.Mutex
|
||||
var firstAttempt *maintenanceStart
|
||||
initial := layer.Stats()
|
||||
if initial.DirtyChunks > 0 {
|
||||
firstAttempt = &maintenanceStart{attempts: cutAttempts(initial), deadline: time.Now().Add(p.cfg.ChunkMaintenanceInterval)}
|
||||
}
|
||||
zeroProgress := 0
|
||||
lastStaged, lastSeq := initial.StagedChunks, initial.CutSeq
|
||||
attempted := func(before, after storage.ChunkLayerStats, err error) {
|
||||
attemptMu.Lock()
|
||||
defer attemptMu.Unlock()
|
||||
// Requests do not run this callback. Their intervening progress must
|
||||
// still break the streak, even if this background attempt staged nothing.
|
||||
intervened := before.StagedChunks != lastStaged || before.CutSeq != lastSeq
|
||||
lastStaged = max(lastStaged, before.StagedChunks, after.StagedChunks)
|
||||
lastSeq = max(lastSeq, before.CutSeq, after.CutSeq)
|
||||
if intervened {
|
||||
zeroProgress = 0
|
||||
}
|
||||
if after.StagedChunks < lastStaged || after.CutSeq < lastSeq {
|
||||
return
|
||||
}
|
||||
if err == nil || after.StagedChunks > before.StagedChunks || after.CutSeq != before.CutSeq {
|
||||
zeroProgress = 0
|
||||
return
|
||||
}
|
||||
var skip *SnapshotSkip
|
||||
if errors.Is(err, hostlimit.ErrSlotsHeld) || errors.Is(err, storage.ErrChunkCaptureRefused) || errors.As(err, &skip) {
|
||||
return // no attempt against the store ran
|
||||
}
|
||||
zeroProgress++
|
||||
if zeroProgress < chunkZeroProgressLimit || p.cfg.ChunkMaintenance == nil {
|
||||
return
|
||||
}
|
||||
if drop, ok := layer.(storage.ChunkStagedDiscarder); ok && drop.DiscardStagedIfUnchanged(after.StagedChunks, after.CutSeq) {
|
||||
log.Printf("durable: maintenance volume=%s: yielding staged session after %d zero-progress attempts", volumeID, zeroProgress)
|
||||
zeroProgress = 0
|
||||
select {
|
||||
case kick <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
if p.cfg.ChunkCaptureInterval > 0 {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
cutDone := make(chan struct{})
|
||||
p.chunkLoop(ctx, volumeID, layer, cutDone, cutWait)
|
||||
p.chunkLoop(ctx, volumeID, layer, cutDone, cutWait, attempted)
|
||||
}()
|
||||
}
|
||||
if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil {
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current, kick) }()
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
p.chunkMaintenanceLoop(ctx, volumeID, layer, current, kick, firstAttempt)
|
||||
}()
|
||||
}
|
||||
if snapshots != nil {
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots) }()
|
||||
go func() { defer workers.Done(); p.chunkSnapshotLoop(ctx, volumeID, layer, current, snapshots, attempted) }()
|
||||
}
|
||||
timer := time.NewTicker(chunkSchedulePoll)
|
||||
defer timer.Stop()
|
||||
@@ -973,6 +1042,28 @@ func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, laye
|
||||
// (a cut session open: the cleaning never runs during one) is tried again.
|
||||
var maintenanceKickRetry = 30 * time.Second // a var only so tests can shorten it
|
||||
|
||||
// maintenanceSnapshotProbeInterval costs one HEAD read per attached volume per
|
||||
// 30 seconds (about 7 reads/s at 200 volumes). This is a scheduling hint only;
|
||||
// the existing cleaning session still requires an idle, matching HEAD.
|
||||
const maintenanceSnapshotProbeInterval = 30 * time.Second
|
||||
|
||||
func (p *DurableProvider) maintenanceSnapshots(ctx context.Context, volumeID string) (map[string]struct{}, error) {
|
||||
p.mu.Lock()
|
||||
h := p.volumes[volumeID]
|
||||
var remote storage.ChunkRemote
|
||||
if h != nil {
|
||||
remote = h.layoutRemote
|
||||
}
|
||||
p.mu.Unlock()
|
||||
probe, ok := remote.(interface {
|
||||
ProbeSnapshots(context.Context) (map[string]struct{}, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, nil
|
||||
} // no attached runtime, no scheduling inference
|
||||
return probe.ProbeSnapshots(ctx)
|
||||
}
|
||||
|
||||
// KickMaintenance asks the volume's maintenance loop for one pass now, as
|
||||
// after a snapshot delete. It reports whether a running loop was there to
|
||||
// ask (a stopped or ended loop is not); kicks coalesce, and the pass is the
|
||||
@@ -996,7 +1087,19 @@ func (p *DurableProvider) KickMaintenance(volumeID string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}) {
|
||||
// maintenanceStart bounds only the first cleaning of an initially dirty layer.
|
||||
// Store-attempt counters include periodic, scheduled, and operator-request cuts.
|
||||
// Refusals did not attempt the store and cannot release this startup wait.
|
||||
type maintenanceStart struct {
|
||||
attempts uint64
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
func cutAttempts(st storage.ChunkLayerStats) uint64 {
|
||||
return st.CutsOK + st.CutsNoop + st.CutsFailed
|
||||
}
|
||||
|
||||
func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool, kick <-chan struct{}, firstAttempt *maintenanceStart) {
|
||||
interval := p.cfg.ChunkMaintenanceInterval
|
||||
due := time.Now().Add(interval)
|
||||
if p.cfg.ChunkStagger {
|
||||
@@ -1004,12 +1107,71 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
|
||||
}
|
||||
timer := time.NewTimer(time.Until(due))
|
||||
defer timer.Stop()
|
||||
var probe <-chan time.Time
|
||||
var seen, observed map[string]struct{}
|
||||
readSnapshots := func() {
|
||||
if ctx.Err() != nil || layer.Fenced() || !current() {
|
||||
return
|
||||
}
|
||||
timeout := p.cfg.ChunkMaintenanceTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = time.Minute
|
||||
}
|
||||
_ = boundedPass(ctx, layer, current, timeout, func(readCtx context.Context) error {
|
||||
names, err := p.maintenanceSnapshots(readCtx, volumeID)
|
||||
if err == nil {
|
||||
observed = names
|
||||
}
|
||||
return err
|
||||
})
|
||||
}
|
||||
if p.cfg.ChunkLayoutHeadFor != nil {
|
||||
tick := time.NewTicker(maintenanceSnapshotProbeInterval)
|
||||
defer tick.Stop()
|
||||
probe = tick.C
|
||||
readSnapshots() // establish a baseline without asking for a pass
|
||||
seen = observed
|
||||
}
|
||||
kicked := false
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
case <-probe:
|
||||
if ctx.Err() != nil || layer.Fenced() || !current() {
|
||||
return
|
||||
}
|
||||
observed = nil
|
||||
readSnapshots()
|
||||
if observed == nil {
|
||||
continue
|
||||
} // unknown is never an empty set
|
||||
missing := false
|
||||
for name := range seen {
|
||||
if _, ok := observed[name]; !ok {
|
||||
missing = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if seen == nil {
|
||||
seen = make(map[string]struct{})
|
||||
}
|
||||
// Remember additions too: deleting one before the next ordinary pass
|
||||
// must still be noticed. Keep missing names pending until a pass ends.
|
||||
for name := range observed {
|
||||
seen[name] = struct{}{}
|
||||
}
|
||||
if !missing {
|
||||
continue
|
||||
}
|
||||
kicked = true
|
||||
if !timer.Stop() {
|
||||
select {
|
||||
case <-timer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
case <-kick:
|
||||
kicked = true
|
||||
if !timer.Stop() {
|
||||
@@ -1019,6 +1181,23 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
|
||||
}
|
||||
}
|
||||
}
|
||||
if firstAttempt != nil {
|
||||
// The engine counters cover request cuts too, not just these workers.
|
||||
// One interval bounds this scheduling wait; HEAD still decides safety.
|
||||
if cutAttempts(layer.Stats()) == firstAttempt.attempts && time.Now().Before(firstAttempt.deadline) {
|
||||
log.Printf("durable: maintenance volume=%s: waiting for first cut attempt (startup interval remaining %s)", volumeID, time.Until(firstAttempt.deadline))
|
||||
}
|
||||
for cutAttempts(layer.Stats()) == firstAttempt.attempts && time.Now().Before(firstAttempt.deadline) && !layer.Fenced() && current() {
|
||||
pause := time.NewTimer(min(chunkSchedulePoll, time.Until(firstAttempt.deadline)))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
pause.Stop()
|
||||
return
|
||||
case <-pause.C:
|
||||
}
|
||||
}
|
||||
firstAttempt = nil
|
||||
}
|
||||
if ctx.Err() != nil || layer.Fenced() {
|
||||
return
|
||||
}
|
||||
@@ -1032,6 +1211,9 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str
|
||||
err := boundedPass(ctx, layer, current, timeout, func(passCtx context.Context) error {
|
||||
return p.cfg.ChunkMaintenance(passCtx, volumeID)
|
||||
})
|
||||
if err == nil && observed != nil {
|
||||
seen = observed
|
||||
}
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Printf("durable: maintenance volume=%s: %v", volumeID, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package durable
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/storage"
|
||||
)
|
||||
|
||||
func TestScheduledSnapshotDueNowUsesExistingLoop(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
slot := &snapshotSlot{s: newSnapshotSchedule("v1", 24*time.Hour, time.Now()), dueNow: make(chan struct{}, 1)}
|
||||
slot.s.next = time.Now().Add(24 * time.Hour)
|
||||
calls := 0
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v1": {snapshots: slot, chunkStop: cancel, chunkDone: done}}}
|
||||
p.cfg.ChunkScheduledSnapshot = func(context.Context, string, time.Time, func(context.Context) (storage.ChunkHead, error)) error {
|
||||
calls++
|
||||
return nil
|
||||
}
|
||||
go func() {
|
||||
defer close(done)
|
||||
p.chunkSnapshotLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return true }, slot, nil)
|
||||
}()
|
||||
defer func() { cancel(); <-done }()
|
||||
synctest.Wait()
|
||||
if calls != 0 {
|
||||
t.Fatal("schedule ran before due")
|
||||
}
|
||||
trigger, ok := any(p).(interface{ ScheduleSnapshotNow(string) bool })
|
||||
if !ok {
|
||||
t.Fatal("scheduled due-now hook is not wired")
|
||||
}
|
||||
if !trigger.ScheduleSnapshotNow("v1") {
|
||||
t.Fatal("running schedule refused trigger")
|
||||
}
|
||||
synctest.Wait()
|
||||
if calls != 1 {
|
||||
t.Fatalf("attempts=%d; want one existing scheduled callback", calls)
|
||||
}
|
||||
if !slot.due().After(time.Now()) {
|
||||
t.Fatal("trigger changed the subsequent daily schedule")
|
||||
}
|
||||
if trigger.ScheduleSnapshotNow("missing") {
|
||||
t.Fatal("trigger accepted unknown volume")
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
if trigger.ScheduleSnapshotNow("v1") {
|
||||
t.Fatal("trigger accepted an ended loop")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestScheduledSnapshotDueNowRefusesEndedWorkerWithBackgroundAlive(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
background := make(chan struct{})
|
||||
worker := make(chan struct{})
|
||||
slot := &snapshotSlot{s: newSnapshotSchedule("v1", 24*time.Hour, time.Now()), dueNow: make(chan struct{}, 1)}
|
||||
p := &DurableProvider{volumes: map[string]*volHandle{"v1": {snapshots: slot, chunkStop: cancel, chunkDone: background}}}
|
||||
current := true
|
||||
go func() {
|
||||
defer close(worker)
|
||||
p.chunkSnapshotLoop(ctx, "v1", &progressLoopLayer{}, func() bool { return current }, slot, nil)
|
||||
}()
|
||||
synctest.Wait()
|
||||
current = false
|
||||
slot.dueNow <- struct{}{}
|
||||
<-worker
|
||||
if p.ScheduleSnapshotNow("v1") {
|
||||
t.Fatal("queued into ended snapshot worker while background group stayed alive")
|
||||
}
|
||||
select {
|
||||
case <-background:
|
||||
t.Fatal("test closed aggregate background")
|
||||
default:
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -239,6 +239,7 @@ func (s *StatusServer) chunkMux() http.Handler {
|
||||
mux.HandleFunc("/chunk/snapshot", s.handleChunkSnapshot)
|
||||
mux.HandleFunc("/chunk/snapshots", s.handleChunkSnapshots)
|
||||
mux.HandleFunc("/chunk/snapshot/delete", s.handleChunkSnapshotDelete)
|
||||
mux.HandleFunc("/chunk/schedule/now", s.handleChunkScheduleNow)
|
||||
mux.HandleFunc("/chunk/detach", s.handleChunkDetach)
|
||||
// Any other /chunk path: a typed JSON 404, like every other /chunk
|
||||
// error, not net/http's plain-text page.
|
||||
@@ -553,6 +554,30 @@ func (s *StatusServer) handleChunkSnapshotDelete(w http.ResponseWriter, r *http.
|
||||
writeChunkJSON(w, http.StatusOK, chunkstore.SnapshotDeleteBody{VolumeID: req.VolumeID, Name: req.Name, State: state})
|
||||
}
|
||||
|
||||
// This is an explicit trigger of the configured schedule, not a new snapshot
|
||||
// writer. The normal scheduler retains admission, retry and retention behavior.
|
||||
func (s *StatusServer) handleChunkScheduleNow(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.chunkAdmit(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
VolumeID string `json:"volumeID"`
|
||||
}
|
||||
if !decodeChunkBody(w, r, &req) {
|
||||
return
|
||||
}
|
||||
ctl := s.chunkTarget(w, req.VolumeID)
|
||||
if ctl == nil {
|
||||
return
|
||||
}
|
||||
trigger, ok := ctl.(interface{ ScheduleSnapshotNow(string) bool })
|
||||
if !ok || !trigger.ScheduleSnapshotNow(req.VolumeID) {
|
||||
writeChunkErr(w, http.StatusConflict, "schedule_not_running", false, "volume %q has no running snapshot schedule", req.VolumeID)
|
||||
return
|
||||
}
|
||||
writeChunkJSON(w, http.StatusOK, map[string]string{"volumeID": req.VolumeID, "state": "queued"})
|
||||
}
|
||||
|
||||
func (s *StatusServer) handleChunkDetach(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.chunkAdmit(w, r, http.MethodPost) {
|
||||
return
|
||||
@@ -735,6 +760,14 @@ func (c *chunkControl) DeleteSnapshot(ctx context.Context, volumeID, name string
|
||||
return "deleted", nil
|
||||
}
|
||||
|
||||
func (c *chunkControl) ScheduleSnapshotNow(volumeID string) bool {
|
||||
if _, err := c.catalogVolume(volumeID); err != nil {
|
||||
return false
|
||||
}
|
||||
trigger, ok := c.p.(interface{ ScheduleSnapshotNow(string) bool })
|
||||
return ok && trigger.ScheduleSnapshotNow(volumeID)
|
||||
}
|
||||
|
||||
func (c *chunkControl) Usage(ctx context.Context, volumeID string) (chunkstore.Usage, error) {
|
||||
v, err := c.catalogVolume(volumeID)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package volume
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
|
||||
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
|
||||
)
|
||||
|
||||
type scheduleNowControl struct {
|
||||
fakeChunkControl
|
||||
queued bool
|
||||
calls int
|
||||
}
|
||||
|
||||
func TestChunkScheduleNowOptInAndProviderForwarding(t *testing.T) {
|
||||
p := &scheduleNowProvider{}
|
||||
ctl := NewChunkControl(p, &chunkstore.BCatalog{}, chunkstore.VolumeRef{Name: "v1", ID: layout.VolumeID{1}})
|
||||
trigger := ctl.(interface{ ScheduleSnapshotNow(string) bool })
|
||||
if !trigger.ScheduleSnapshotNow("v1") || trigger.ScheduleSnapshotNow("other") || p.calls != 1 {
|
||||
t.Fatal("control did not forward only its own volume to the configured provider")
|
||||
}
|
||||
s := chunkServer(t, ctl, false)
|
||||
if _, err := s.Start("127.0.0.1:0"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close(context.Background())
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/chunk/schedule/now", strings.NewReader(`{"volumeID":"v1"}`))
|
||||
req.RemoteAddr = "127.0.0.1:1000"
|
||||
s.srv.Handler.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound || p.calls != 1 {
|
||||
t.Fatalf("disabled endpoint: %d calls=%d", w.Code, p.calls)
|
||||
}
|
||||
}
|
||||
|
||||
type scheduleNowProvider struct {
|
||||
fakeChunkProvider
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *scheduleNowProvider) ScheduleSnapshotNow(string) bool { p.calls++; return true }
|
||||
|
||||
func (c *scheduleNowControl) ScheduleSnapshotNow(string) bool { c.calls++; return c.queued }
|
||||
|
||||
func TestChunkScheduleNowRunsOnlyThroughEnabledLocalControl(t *testing.T) {
|
||||
c := &scheduleNowControl{queued: true}
|
||||
s := chunkServer(t, c, true)
|
||||
w := serve(t, s, http.MethodPost, "/chunk/schedule/now", `{"volumeID":"v1"}`, "")
|
||||
if w.Code != http.StatusOK || c.calls != 1 {
|
||||
t.Fatalf("due-now: status=%d calls=%d body=%s", w.Code, c.calls, w.Body.String())
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, body, remote string
|
||||
code int
|
||||
}{
|
||||
{http.MethodGet, `{"volumeID":"v1"}`, "", http.StatusMethodNotAllowed},
|
||||
{http.MethodPost, `{"volumeID":"other"}`, "", http.StatusNotFound},
|
||||
{http.MethodPost, `{"volumeID":"v1"}`, "192.0.2.1:1000", http.StatusForbidden},
|
||||
} {
|
||||
if got := serve(t, s, tc.method, "/chunk/schedule/now", tc.body, tc.remote); got.Code != tc.code {
|
||||
t.Fatalf("refusal status=%d want=%d", got.Code, tc.code)
|
||||
}
|
||||
}
|
||||
if c.calls != 1 {
|
||||
t.Fatal("refused transport reached schedule")
|
||||
}
|
||||
c.queued = false
|
||||
if got := serve(t, s, http.MethodPost, "/chunk/schedule/now", `{"volumeID":"v1"}`, ""); got.Code != http.StatusConflict {
|
||||
t.Fatalf("disabled schedule status=%d", got.Code)
|
||||
}
|
||||
}
|
||||
@@ -29,3 +29,24 @@ func (l *chunkLayerImpl) CutUnlessCutSince(ctx context.Context, seq uint64) (chu
|
||||
r, err := l.captureLocked(ctx, false)
|
||||
return r, false, err
|
||||
}
|
||||
|
||||
// ChunkStagedDiscarder yields stalled uploads to cleaning. A pending publication
|
||||
// is never discarded, and progress made by another cut invalidates the request.
|
||||
type ChunkStagedDiscarder interface {
|
||||
DiscardStagedIfUnchanged(staged, seq uint64) bool
|
||||
}
|
||||
|
||||
func (l *chunkLayerImpl) DiscardStagedIfUnchanged(staged, seq uint64) bool {
|
||||
if !l.capMu.TryLock() {
|
||||
return false
|
||||
}
|
||||
defer l.unlockCap()
|
||||
l.stMu.Lock()
|
||||
safe := !l.closed && l.pending == nil && !l.fenced && l.detached == nil && l.stats.StagedChunks == staged && l.stats.CutSeq == seq
|
||||
l.stMu.Unlock()
|
||||
if !safe {
|
||||
return false
|
||||
}
|
||||
l.discardStaged()
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package storage
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestDiscardStagedRechecksCaptureState(t *testing.T) {
|
||||
for _, name := range []string{"idle", "staging_advanced", "cut_advanced", "pending_commit", "fenced", "detached", "closed", "cut_running"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
r := newFakeChunkRemote()
|
||||
l := &chunkLayerImpl{remote: r, stats: chunkLayerStats{StagedChunks: 3, CutSeq: 2}, reusable: map[uint64]stagedChunk{1: {}}}
|
||||
switch name {
|
||||
case "staging_advanced":
|
||||
l.stats.StagedChunks++
|
||||
case "cut_advanced":
|
||||
l.stats.CutSeq++
|
||||
case "pending_commit":
|
||||
l.pending = &chunkHead{}
|
||||
case "fenced":
|
||||
l.fenced = true
|
||||
case "detached":
|
||||
l.detached = &chunkCutResult{}
|
||||
case "closed":
|
||||
l.closed = true
|
||||
case "cut_running":
|
||||
l.capMu.Lock()
|
||||
defer l.capMu.Unlock()
|
||||
}
|
||||
if got := l.DiscardStagedIfUnchanged(3, 2); got != (name == "idle") {
|
||||
t.Fatalf("discard=%v for %s", got, name)
|
||||
}
|
||||
if (len(l.reusable) == 0) != (name == "idle") {
|
||||
t.Fatal("staged uploads changed on a refused discard")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -425,7 +425,8 @@ B stores snapshots, restore dependencies and the active session in HEAD. The tra
|
||||
| Abort or settle | Keep reusable uploads in their session; retain an unresolved proposal for settlement. Dropped work aborts the open session; a landed commit has already ended it. | `core/storage/chunk_layer.go` `discardStaged`, `captureLocked`, `Close`; `core/frontend/chunkstore/layout_remote.go` `AbortOpenSession` | `INV-CUT-INTENT-CLOSE-001`, `INV-WS-CAS-UNKNOWN-001` |
|
||||
| Restore | Record the target as a source dependent before creating its root and unclaimed HEAD; owner-qualified references resolve in the source pool. | `core/frontend/chunkstore/catalog_b.go` `BCatalog.Restore`; `core/frontend/chunkstore/layout/create.go` | `INV-SNAPK-COMMIT-REACH-001` |
|
||||
| Remove snapshot | Remove the name through a conditional HEAD transition; its objects remain governed by the roots and dependents still recorded. | `core/frontend/chunkstore/catalog_b.go` `DeleteSnapshot`; `core/frontend/chunkstore/layout/snapshots.go` | `INV-SNAPK-HEAD-WRITE-001` |
|
||||
| Clean | Cleaning excludes an open snapshot session. Read and validate HEAD reachability before marking an unreachable pool entry; delete only under the matching mark. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `RemoveUnreachable` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` |
|
||||
| Clean | Cleaning excludes an open snapshot session. Read tags, validate HEAD, then conditionally mark/delete unreferenced roots, segments and chunks in that order. | `core/frontend/chunkstore/layout/clean.go`; `core/frontend/chunkstore/layout/remove.go` `Cleaner.removePlanned` | `INV-SNAPK-CLEAN-EXCL-001`, `INV-SNAPK-REMOVE-MARK-001`, `INV-SNAPK-REMOVE-STOP-001` |
|
||||
| Background cut/clean ordering | New staging retries promptly; zero progress backs off. Dirty-start cleaning waits for a completed store attempt or one interval. After K=3 admitted stalls, guarded discard releases the session and kicks cleaning; request progress resets the streak. | `core/frontend/durable/provider_chunk.go`; `core/storage/chunk_periodic_cut.go` | `INV-CUT-RETRY-FAIRNESS-001` |
|
||||
| Delete volume | Reserve deletion, check no live lease inside the deleting transition, release the reservation, remove objects and mark deleted. | `core/frontend/chunkstore/catalog_b.go` `DeleteVolume`; `core/frontend/chunkstore/layout/delete.go` | `INV-WS-DELETE-NO-LIVE-HOLDER-001` |
|
||||
|
||||
---
|
||||
@@ -533,7 +534,7 @@ stateDiagram-v2
|
||||
clean --> idle: Claim(e, claim id), c void
|
||||
idle --> clean: BeginClean(c)
|
||||
clean --> idle: EndClean(c)
|
||||
clean --> clean: RemoveUnreachable(shard)
|
||||
clean --> clean: roots, segments, chunk shards (conditional removal)
|
||||
idle --> deleting: MarkDeleting (no holder, no dependents)
|
||||
deleting --> deleted: MarkDeleted (after release and pool)
|
||||
```
|
||||
@@ -549,7 +550,7 @@ stateDiagram-v2
|
||||
| any (Start) | idle at epoch e, claim id k | Start only: at HEAD's epoch it continues on the root carrying HEAD's claim id at or above HEAD's position, else refuses; above, a fresh root or the continuing lineage claims, validated against the HEAD the claim updates | start.go `Start`; claim.go `RunClaim` | `INV-SNAPK-START-ROOT-001`, `INV-SNAPK-START-LINEAGE-001`, `INV-SNAPK-START-POSITION-001`, `INV-SNAPK-START-ACTIVITY-001` |
|
||||
| idle | clean(c) | holder at HEAD's epoch (epoch, server and claim id); activity idle (clean(c) again is a replay) | clean.go `Head.BeginClean` | `INV-SNAPK-CLEAN-EXCL-001` |
|
||||
| clean(c) | idle | holder at HEAD's epoch (epoch, server and claim id); activity clean(c); over idle it succeeds without a write | clean.go `Head.EndClean` | `INV-SNAPK-CLEAN-EXCL-001` |
|
||||
| clean(c) | clean(c), names removed | holder at HEAD's epoch (epoch, server and claim id) with clean(c) open (HEAD read once, after BeginClean); a name is deleted only if no root in HEAD (current or snapshot) names it in this volume's pool; each removal is a mark conditional on the plan's metadata, then a delete conditional on that mark | remove.go `RemoveUnreachable` | `INV-SNAPK-REMOVE-MARK-001` |
|
||||
| clean(c) | clean(c), names removed | holder at HEAD's epoch, server and claim id with clean(c) open; candidate tags precede each HEAD validation; unreachable roots, then segments, then chunks; mark conditional on the planned tag, delete conditional on its own mark | remove.go `Cleaner.removePlanned` | `INV-SNAPK-REMOVE-MARK-001`, `INV-CLEAN-METADATA-001`, `INV-CLEAN-CURSOR-001` |
|
||||
| idle (live or detached) | deleting | the master reserved the volume for delete (no line granted after), then no line holds a live lease, checked between the HEAD read and the update; no open activity, no snapshot with dependents; deleting again is a replay | delete.go `Head.MarkDeleting`, `RunMarkDeleting` (`DeleteAuthority`) | `INV-SNAPK-DELETE-ORDER-001` |
|
||||
| absent | deleted (tombstone) | the operator's remove-dependent, for a restore target without HEAD (never created, or a restore died between its two creates); one exclusive create, so a later HEAD create of the restore fails; a HEAD appearing first refuses | delete.go `OperatorReleaseDependent` (`TargetStore.CreateDeletedHead`) | `INV-SNAPK-TOMBSTONE-001`, `INV-SNAPK-HEAD-WRITE-001` |
|
||||
| source: any live | source: target released | by the target's volume id, from every snapshot: from DeleteVolume once the target's HEAD is deleting, or from the operator's command once the target is deleted, of another id, no longer naming the source, or tombstoned; an absent target writes nothing | delete.go `Head.ReleaseDependent`, `RunReleaseDependent`, `OperatorReleaseDependent` | `INV-SNAPK-RELEASE-001`, `INV-SNAPK-RELEASE-CALLERS-001`, `INV-SNAPK-RELEASE-OPERATOR-001` |
|
||||
@@ -891,6 +892,7 @@ Notes:
|
||||
| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-BIRTH-001` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | ARCHIVED |
|
||||
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for a completed store attempt or one maintenance interval. K=3 admitted stalled background attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestDirtyStartCaptureRefusalsDoNotReleaseCleaning`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE |
|
||||
| `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | ACTIVE |
|
||||
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
|
||||
| `INV-CUT-FRESH-KNOWN-ZERO-001` | A store this start created (in memory) and still fresh at its attach (marker present, no BASE) starts known-zero for each chunk its claimed HEAD does not name whose entry is still {LSN 0, UNKNOWN}. Order: retire the marker, then make the marking durable, then serve. | M1 Recovering → Serving (fresh attach: commit, marking, then serving) | `core/storage/chunk_fresh_known_zero.go` `freshKnownZeroCandidates`, `ApplyFreshKnownZero`; `core/frontend/durable/provider_chunk.go` `attachChunk`; `core/frontend/durable/provider.go` `openOrCreate` (`createdThisStart`; non-chunk implementations refuse chunk roots) | `TestRedFirstCutOfAFreshVolumeScansOnlyWrittenChunks`, `TestFirstCutAgainstAClaimedHeadCertifiesUnnamedChunks`, `TestFirstCutOfARestoreTargetKeepsItsHydrationPath`, `TestExplicitWALStoreRefusesAFreshChunkRoot` (`core/frontend/durable/first_cut_known_zero_test.go`); `TestNoWriteReachesAFreshStoreBeforeItsAttachCommit`, `TestNoFetchOrFillReachesAFreshStoreBeforeItsAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeTheAttachCommit`, `TestFreshKnownZeroNotAfterARestartBeforeAnyAttach`, `TestFreshKnownZeroCrashBetweenMarkerRetireAndMarking` (`core/frontend/durable/known_zero_premise_test.go`); `TestFreshKnownZeroNeverCertifiesARecordedWrite`, `TestFreshKnownZeroNotWithoutTheFreshPremise`, `TestFreshKnownZeroSkipsAChunkWrittenAfterTheSample`, `TestFreshKnownZeroNeedsThisStartsCreate` (`core/storage/chunk_fresh_known_zero_test.go`) | `KnownZero`. Premise: no write, fill or other implementation reaches a store before its attach commit; a marker an earlier start, an older binary or another opener left is never trusted (created-this-start is in memory). A crash between retirement and marking costs one scan. | ACTIVE |
|
||||
@@ -1083,7 +1085,7 @@ Notes:
|
||||
|---|---|---|---|---|---|---|
|
||||
| `INV-SNAPK-NAME-CANONICAL-001` | A chunk is named by its index and the SHA-256 of its bytes under `pool/<index/10000>/`; a segment and a root are named by the SHA-256 of their canonical encoding, and decoding refuses any bytes the encoder would not write, so an object has one encoding and one name. | Content-named layout (no state transition) | `core/frontend/chunkstore/layout` `layout.go` `ParseChunkName`, `DecodeSegment`, `DecodeRoot` | `TestParseChunkName_RoundTripAndRefusals`, `TestDecodeSegment_RefusesNonCanonical`, `TestRoot_Refusals`, `TestBuild_ShardsAndIncrementalReuse` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `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 RemoveUnreachable and the ordered DeleteVolume. | M9 every transition | `core/frontend/chunkstore/layout` (source scan of the package) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (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 100 snapshots 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-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 |
|
||||
@@ -1095,10 +1097,15 @@ Notes:
|
||||
| `INV-SNAPK-CLEAN-EXCL-001` | A cleaning and a snapshot exclude each other through HEAD's one activity field, so no name is removed while a snapshot is open; a claim voids an open cleaning. | M9 idle → clean → idle | `core/frontend/chunkstore/layout` `clean.go` `Head.BeginClean`, `Head.EndClean` | `TestBeginClean_Closure`, `TestEndClean_Closure`, `TestEndClean_IdleMeansNoActivityRemains`, `TestClean_ExcludesSnapshot`, `TestRunBeginClean_InterruptAtEveryStep`, `TestRunEndClean_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-CLEAN-HOLDER-PASS-001` | The holder's periodic cleaning runs as the identity Start established: Begin refuses any other holder, claim or epoch; a pass with no identity, or whose retention failed, removes nothing; every opened cleaning is closed, also on error. | M9 idle → clean → idle (holder pass) | `core/frontend/chunkstore/clean_b.go` `BCatalog.Clean`; `cmd/blockvolume/chunk_maintenance.go` `newChunkMaintenance` | `TestBCatalog_CleanIsHolderOnly`, `TestBCatalog_CleanClosesOnError`, `TestBCatalog_CleanRemovesOnlyUnreachable`, `TestBCatalog_CleanWaitsForAnOpenSnapshot`, `TestBCatalog_CleanAfterOverwriteAndSnapshotDelete` (`core/frontend/chunkstore/clean_b_test.go`); `TestMaintenanceCleansOnlyAsTheHolder`, `TestMaintenanceRetentionFailureNeverStartsCleaning` (`cmd/blockvolume/chunk_maintenance_test.go`) | — | ACTIVE |
|
||||
| `INV-SNAPK-READ-MISSING-001` | A read resolves root, segment, chunk; an index the root does not name is zeros; a root, segment or chunk the root reaches but the store lacks is ErrMissing, never zeros; bytes that do not hash to their name are ErrCorrupt; a foreign chunk is read from its owner's pool. | Content-named layout (read path, no state transition) | `core/frontend/chunkstore/layout` `read.go` `Reader.Open`, `Image.Segment`, `Image.Chunk` | `TestRead_AbsentIndexIsZeros`, `TestRead_ForeignChunkFromSourcePool`, `TestRead_MissingObjectIsAnErrorNeverZeros`, `TestRead_FetchFailureAndCorruption`, `TestRead_SegmentOfAnotherShardRefused` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-MARK-001` | A pool name is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `RemoveUnreachable` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as RemoveUnreachable's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-CLEAN-DEPENDENTS-001` | A snapshot with restore dependents never leaves HEAD through operator deletion or retention expiry/pruning; its root stays in HeadRoots, so cleaning needs no separate Dependent.Root walk. | M9 snapshot remove (K: HEAD) | `core/frontend/chunkstore/layout/snapshots.go`; `core/frontend/chunkstore/retain_b.go` | `TestSnapshotWithDependentsSurvivesEveryRemovalTransition` (`core/frontend/chunkstore/layout/snapshot_dependents_guard_test.go`); `TestDependentSnapshotSurvivesOperatorExpiryAndRetentionPrune` (`core/frontend/chunkstore/clean_dependents_test.go`) | CommitReach2 assumption A5; rows 71-75 and model-code trace | ACTIVE |
|
||||
| `INV-CLEAN-SNAPSHOT-PROBE-001` | A 30-second holder probe reads only snapshot names; open local activity or a busy runtime skips the read. Missing names ask for ordinary cleaning; unknown reads imply nothing. The probe neither rolls back activity nor changes the engine view. | M9 maintenance scheduling (K: HEAD) | `core/frontend/chunkstore/layout_remote.go` `ProbeSnapshots`; `core/frontend/durable/provider_chunk.go` | `TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD` (`core/frontend/chunkstore/layout_snapshot_probe_test.go`); `TestMaintenanceNoticesSnapshotDeleteWithoutNotification` (`core/frontend/durable/maintenance_probe_test.go`) | CommitReach2 CBegin (scheduling only; BeginClean remains the idle guard) | ACTIVE |
|
||||
| `INV-SCHEDULE-DUE-NOW-001` | The local opt-in due-now request queues only a running configured schedule, using its existing worker and admission. A cancelled or ended snapshot worker refuses even while the aggregate background group remains alive. | M9 scheduled capture (K: HEAD) | `core/frontend/durable/chunk_snapshot_schedule.go`; `core/host/volume/chunk_control.go` | `TestScheduledSnapshotDueNowUsesExistingLoop`, `TestScheduledSnapshotDueNowRefusesEndedWorkerWithBackgroundAlive` (`core/frontend/durable/snapshot_due_now_test.go`); `TestChunkScheduleNowRunsOnlyThroughEnabledLocalControl` (`core/host/volume/chunk_schedule_now_test.go`) | EngineAdapter.StartStop; CommitReach WCommit (ordinary capture) | ACTIVE |
|
||||
| `INV-CLEAN-METADATA-001` | Cleaning preserves Current and snapshot roots and their segments. Dependents keep their snapshot in HEAD. Unnamed roots go before segments and chunks; reuse defeats conditional removal. | M9 clean | `core/frontend/chunkstore/layout/remove.go`; `core/frontend/chunkstore/clean_b.go` | `TestCleanerMetadataRetainsCurrentSnapshotAndDependent`, `TestCleanerMetadataReuseDefeatsLateMarkAndDelete`, `TestCleanerRecreatesRemovedRootBeforeRenamingIt` (`core/frontend/chunkstore/layout/clean_metadata_test.go`); `TestCleaningInterruptsAfterMetadataBeforeChunks` (`core/frontend/chunkstore/clean_cursor_test.go`) ; `TestCleaningSegmentResumeReplansRootsBeforeRemovingSegments` (`core/frontend/chunkstore/clean_cursor_test.go`) | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-CLEAN-CURSOR-001` | Every new session scans roots first, preserves segment/chunk progress, and wraps after the final shard. Each page validates HEAD after parallel tags; reachability caches a conservative root set only within that session. | M9 clean (liveness) | `core/frontend/chunkstore/clean_b.go`; `core/frontend/chunkstore/layout/remove.go` | `TestCleaningCursorResumesAfterTimeoutAndWraps` (`core/frontend/chunkstore/clean_cursor_test.go`); `TestCleanerReachableOncePerShardAndRechecksHead`, `TestCleanerPlansTagsInBoundedParallelBeforeHead` (`core/frontend/chunkstore/layout/clean_scale_test.go`) | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-MARK-001` | A content-named object is removed only inside the holder's own cleaning, when no root in HEAD names it: tags read first, HEAD read and validated after, then a mark conditional on the tag and a delete conditional on the mark. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_RemovesOnlyWhatNoRootNames`, `TestCleaningPass_InterruptAtEveryStep`, `TestHolderFunctions_RefuseAStaleHolder` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-STOP-001` | A reuse of an object after the plan, or after the mark, makes the remover's mark or delete fail its condition, however late it lands; an unreadable root stops the pass before any write; an open snapshot refuses it. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ASuccessorAfterTheHeadViewDefeatsTheMark`, `TestRemoveUnreachable_ASuccessorBeforeTheHeadViewStopsThePass`, `TestRemoveUnreachable_AReuseAfterThePlanDefeatsTheMark`, `TestRemoveUnreachable_AReuseDefeatsALateMarkOrDelete`, `TestRemoveUnreachable_NothingRemovedOnAPartialView`, `TestRemoveUnreachable_RefusedOutsideItsCleaning` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-CONVERGE-001` | A name a cleaning marked and did not delete (the remover died in between) is planned again by the next cleaning: the re-mark replaces the old mark, so the dead remover's late delete fails, and every unreachable name goes once a cleaning completes. | M9 clean → clean | `core/frontend/chunkstore/layout` `remove.go` `Cleaner.removePlanned` | `TestRemoveUnreachable_ReclaimsAnAbandonedMark`, `TestCleaningPass_InterruptAtEveryStep`, `TestLayoutStoreCleaningReclaimsAnAbandonedMark` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REMOVE-GUARD-001` | A source scan requires DeleteMarked as Cleaner.removePlanned's only removal, each immediately after an if on its Mark's error that leaves: an unconditional delete, an ignored mark, a reused mark or another method fails. | M9 clean → clean (RemoveUnreachable) | `core/frontend/chunkstore/layout` (source scan of `remove.go`) | `TestGuard_WritersTransitionsAndRemovers`, `TestGuard_Controls` | CommitReach rows 65-70; CommitReach2 rows 71-75 (CPlan, CView, CIssueMark/LandMark, CIssueDel/LandDel; model-code trace) | ACTIVE |
|
||||
| `INV-SNAPK-REUSE-001` | Writing an object for a session creates it, or reuses an existing one by a conditional update that sets the session and clears any mark; a commit names only objects its session wrote or reused, unmarked. | M9 snap → idle (Upload, Commit) | `core/frontend/chunkstore/layout` `objects.go` `EnsureObject`; `commit.go` `RunCommit` | `TestEnsureObject`, `TestRunCommit_NeedsObjectsOfItsOwnSession`, `TestSnapshotSession_InterruptAtEveryStep`, `TestLayoutStoreCreateExistsReclaimsOnlyItsUnusedUpload`, `TestLayoutStoreCreateUnknownOutcomeKeepsItsUpload` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
| `INV-START-LAYOUT-ID-001` | The launcher's full layout id must match VOLUME and HEAD, even when id8 collides; mismatch is ErrIdentity and startup exits 78 without claiming or serving. The flag comes from the master's volume record. | M9 Start refusal | `core/frontend/chunkstore/layout_create.go` `ReadVolumeRecord`; `core/frontend/chunkstore/layout_store.go` `ReadHead`; `core/frontend/durable/provider_startup.go`; `cmd/blockvolume/process_exit.go`; `core/lifecycle/workload_plan.go` | `TestLayoutIDMismatchIsTypedAndExits78`; `TestLauncherCarriesTheMasterLayoutIdentity`; `TestG15d_WorkloadPlan_BlankPoolRF2CreatesReplicaWorkloads` | K1; full identity, not the directory suffix | ACTIVE |
|
||||
| `INV-SNAPK-IDENTITY-001` | A volume is identified by the random id in its VOLUME record, never by its name alone; HEAD carries the volume id and refuses to encode without it. | Content-named layout; M9 every transition | `core/frontend/chunkstore/layout` `volume.go` `Volume`, `VolumeID`; `head.go` `Head.check` | `TestVolumeID_RandomAndParsed`, `TestVolume_GoldenEncodingRoundTrip`, `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals` | — (the snapshot kernel model is not in this repository) | ACTIVE |
|
||||
|
||||
@@ -5,6 +5,7 @@ what a user or reviewer can actually run, what QA evidence backs it, and what
|
||||
is still outside the supported boundary.
|
||||
|
||||
- [v1.0.0](v1.0.0.md)
|
||||
- [Planned cleaning convergence after v1.0.0](cleaning-convergence.md)
|
||||
- [Holder identity and pre-release upgrades](holder-identity.md)
|
||||
- [One live process per volume per host](one-process-per-volume.md)
|
||||
- [Local disk headroom at volume create](local-disk-headroom.md)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Planned cleaning changes after v1.0.0
|
||||
|
||||
These changes are proposed for v1.0.1. They are not a claim about v1.0.0 or
|
||||
qualification of a published binary. The v1.0.0 release note's cleaning limits
|
||||
describe that release; this change replaces those limits when it is released.
|
||||
|
||||
- Cleaning removes unreferenced roots, then segments, then chunks. It no longer
|
||||
waits for volume deletion to reclaim abandoned roots and segments.
|
||||
- Bounded passes preserve segment and chunk shard/name progress. Every new
|
||||
session first scans roots again, then resumes the cursor, and a completed pass
|
||||
wraps. Space may return over several passes; a process restart resets progress.
|
||||
- A snapshot with restore dependents stays in HEAD when an operator or retention
|
||||
tries to delete it. Its root therefore remains reachable throughout cleaning.
|
||||
- The holder notices removed snapshot names through a 30-second HEAD probe,
|
||||
skipping open sessions/cleaning. The 200-volume and AG1b measurements must
|
||||
report its read rate per host and filer-capacity percentage; above 1% requires
|
||||
revisiting the design.
|
||||
- The local opt-in schedule control can queue an immediate daily/weekly attempt
|
||||
through the existing worker. Queued is not completed; an ended worker refuses.
|
||||
|
||||
See [cleaning and the schedule command](../standalone-deployment.md#resuming-cleaning-passes).
|
||||
Linux/race qualification and the production-layout CLI verifier evidence remain
|
||||
separate gates. A live graph/count check is not a `verify`-clean result.
|
||||
@@ -753,6 +753,28 @@ Space comes back in two steps. Neither is immediate.
|
||||
# or, in weed shell: volume.list and volume.vacuum -garbageThreshold 0.01
|
||||
```
|
||||
|
||||
### Cut retries and cleaning after a dirty start
|
||||
|
||||
Automatic cuts and scheduled snapshots retry at the next scheduling opportunity
|
||||
when a failed attempt finished staging new chunks. An attempt with no new staging
|
||||
keeps the ordinary doubling backoff. The per-attempt deadline is unchanged; retry
|
||||
progress is in-process, and a restart recovers objects by their content names.
|
||||
|
||||
When the layer starts dirty, its first cleaning pass waits for the first cut
|
||||
attempt that reached the store (periodic, scheduled or requested) to return, or for one
|
||||
maintenance interval from startup, whichever comes first. This also applies when
|
||||
periodic cuts are disabled; it does not enable them. Refused cuts do not end this
|
||||
wait because they did not reach the store. Clean starts are unchanged. After three consecutive failed background
|
||||
attempts without staging progress, the holder drops its reusable staging session
|
||||
and kicks cleaning. Capture refusals, restoring-snapshot skips and host-slot refusals do not count:
|
||||
no store attempt ran. Progress or a successful cut resets the count. K counts
|
||||
attempts, not elapsed time: the first two zero-progress waits are 1 and 2 seconds
|
||||
for automatic cuts, or 1 and 2 minutes for scheduled snapshots, plus the time spent
|
||||
in each attempt. Discard permits cleaning to remove unreferenced uploads; the next
|
||||
cut reuses only content-named chunks that cleaning left behind. A running cut,
|
||||
a newer completed cut or staging counter, and an unresolved commit prevent that
|
||||
discard. The kernel's session exclusion and conditional removal remain authoritative.
|
||||
|
||||
### SeaweedFS maintenance commands that destroy chunk volumes
|
||||
|
||||
A walstore-chunk volume keeps its data in SeaweedFS as needles that **no file's chunk list names**: the volume's
|
||||
@@ -824,6 +846,54 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i
|
||||
- **`ops chunk release` is a repair step, not part of this procedure.** `sw-block ops chunk release --master MASTER --source v1 --target v2 --chunk-filer FILER` removes a restore target from its source snapshot's dependents. It works only when the target no longer names the source's chunks (it was deleted), or when the target never got its first HEAD (an interrupted restore). In the second case it first tombstones the target's name, so that name can never be created. A live target is refused with `target_live`.
|
||||
|
||||
|
||||
|
||||
### Comparing master and holder revisions
|
||||
|
||||
`ClusterEvidenceService.GetClusterStatus.product_revision` and the holder's local `GET /status?volume=<name>` field `Version` both report component-independent buildinfo provenance as `<revision> modified=<true/false/unknown>`. The modified flag is appended so clean and modified source trees do not compare equal. Compare these values to check for different source revisions; the holder field is read on its host through the existing loopback status endpoint. Neither value is carried in `HeartbeatReport`. An absent value or `unknown` revision/modified field means provenance is unavailable: even matching unknown values do not establish equal builds. Matching provenance does not prove byte-identical binaries, and two dirty trees can differ despite matching revision/modified fields; the daemon's `--version` reports these same fields with its component name. These fields are diagnostic and do not affect readiness, leases or admissions.
|
||||
|
||||
### Resuming cleaning passes
|
||||
|
||||
A holder's cleaning removes unreferenced roots first, then segments, then chunk
|
||||
objects. Current and every snapshot root remain reachable; a restore dependent
|
||||
prevents its source snapshot from being deleted, including by retention.
|
||||
The holder's maintenance loop probes HEAD every 30 seconds and asks for an early
|
||||
pass when a previously observed snapshot name disappears, including after a
|
||||
master-resolved snapshot delete. There is no notification channel or lease-loop
|
||||
work. A busy runtime or an open cut session/cleaning skips the probe without a
|
||||
HEAD read. When idle this adds one HEAD read per volume per 30 seconds (about
|
||||
7 reads/s for 200 volumes), plus a baseline read when maintenance starts. The
|
||||
200-volume and AG1b (thousands of volumes per host) qualification rows measure
|
||||
this added read rate per host against filer capacity; above 1% the probe design
|
||||
must be revisited. A failed or absent HEAD
|
||||
read never means the snapshot set is empty. Space returns over several bounded
|
||||
passes as the cleaning cursor advances; a probe does not bypass an active cut.
|
||||
Each object is marked conditionally on its planned tag and deleted conditionally
|
||||
on that mark. An object reused by a successor defeats those late writes.
|
||||
|
||||
The bounded pass retains in-process segment and chunk shard/name progress. Each
|
||||
new session starts at the first root before resuming that progress: a snapshot
|
||||
may have been deleted since the previous session. It wraps to the beginning
|
||||
after the last shard. Restarting the process resets the cursor. Every new pass re-reads tags and
|
||||
HEAD; the cursor carries no authority. Tag reads run with bounded concurrency,
|
||||
and a shard's reachable set is resolved once against that session's initial
|
||||
root set. Snapshot deletes keep that conservative superset until the session
|
||||
ends; an unexpected newly named root stops the pass for a fresh plan. Planned/removed counts include metadata;
|
||||
root and segment removals are also counted separately.
|
||||
|
||||
### Request a scheduled snapshot now
|
||||
|
||||
With `--chunk-control-endpoint`, a volume whose daily/weekly schedule is enabled
|
||||
accepts a local request to make an attempt now:
|
||||
|
||||
```sh
|
||||
curl --fail -H 'Content-Type: application/json' \
|
||||
-d '{"volumeID":"v1"}' http://127.0.0.1:9181/chunk/schedule/now
|
||||
```
|
||||
|
||||
The reply is `{"volumeID":"v1","state":"queued"}`; it confirms scheduling, not
|
||||
snapshot completion. Check scheduled-snapshot status for its result. This runs
|
||||
the existing scheduler's capture, admission, retry and retention steps. It does
|
||||
not enable an off schedule or change the subsequent daily/weekly slots. An off
|
||||
or stopped schedule returns `schedule_not_running`. The route shares the other
|
||||
chunk control routes' opt-in and loopback-only restrictions.
|
||||
|
||||
Reference in new issue
Block a user