Merge #318 (periodic cut + per-volume maintenance) into train 6

This commit is contained in:
pingqiu committed 2026-11-20 20:25:14 -08:00
commit 6692d5a4e4
29 files changed
+1483 -47

No files matched your search

@@ -0,0 +1,59 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Automatic GC stays default-off until restart-safe unknown-CAS settlement and
// the 50/200-volume root-scan measurement both pass. Retention remains enabled.
// The CLI fixes the maximum cut/copy lifetime at five minutes and the HEAD
// hydration reader at thirty seconds. A one-minute mark fits strictly inside
// the one-hour grace. No elapsed TTL alone authorizes capture-intent expiry.
func newChunkMaintenance(cat *chunkstore.Catalog, blobs chunkstore.BlobDeleter, collect bool, master string) (func(context.Context, string) error, func() error, error) {
closeFn := func() error { return nil }
cfg := chunkstore.GCConfig{Grace: defaultChunkGCGrace, IntentTTL: defaultChunkIntentTTL}
if collect {
if master == "" {
return nil, closeFn, errors.New("automatic chunk GC requires blockmaster authority")
}
if defaultChunkGCGrace <= max(defaultChunkCutTimeout, chunkstore.DefaultOpDeadline)+defaultChunkMaintenanceTimeout {
return nil, closeFn, errors.New("automatic GC grace does not cover cut/copy and mark bounds")
}
conn, err := grpc.NewClient(master, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, closeFn, err
}
closeFn = conn.Close
evidence := control.NewEvidenceServiceClient(conn)
cfg.IssuedEpoch = func(ctx context.Context, vol string) (uint64, error) {
reply, err := evidence.QueryVolumeStatus(ctx, &control.StatusRequest{VolumeId: vol})
if err != nil {
return 0, err
}
if reply.GetVolumeId() != vol || !reply.GetAssigned() || reply.GetEpoch() == 0 {
return 0, fmt.Errorf("blockmaster has no issued authority for %s", vol)
}
return reply.Epoch, nil
}
}
return func(ctx context.Context, vol string) error {
retained, err := cat.Retain(ctx, vol, false)
if err != nil {
return fmt.Errorf("retain deleted=%d not_attempted=%d: %w", len(retained.Deleted), len(retained.NotAttempted), err)
}
if !collect {
return nil
}
out, err := cat.ExecuteVolumeGC(ctx, vol, blobs, cfg, true)
log.Printf("blockvolume: maintenance volume=%s mark=%s reclaimed=%d settled=%d unknown=%v", vol, out.MarkOutcome, out.Reclaimed, out.SettledCopies, out.UnknownOutcomes)
return err
}, closeFn, nil
}
@@ -0,0 +1,114 @@
package main
import (
"context"
"errors"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
"path"
"testing"
"time"
)
type maintenanceGCFiler struct {
chunkstore.Filer
gcCalls, marked, freed int
failSecond bool
}
func (f *maintenanceGCFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
if name == "_GC_MARK" {
f.gcCalls++
return nil, errors.New("witness: GC reached")
}
return f.Filer.LookupEntry(ctx, dir, name)
}
func (f *maintenanceGCFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
if string(e.Extended["swb.snap.state"]) == chunkstore.SnapDeleting {
if f.failSecond && f.marked == 1 {
return errors.New("second retention mark refused")
}
f.marked++
}
return f.Filer.UpdateEntry(ctx, dir, e, expected)
}
func (f *maintenanceGCFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
err := f.Filer.DeleteEntry(ctx, dir, name, expected)
if err == nil && path.Base(dir) == "snapnames" {
f.freed++
}
return err
}
type maintenanceBlobs struct{}
func (maintenanceBlobs) DeleteBlob(context.Context, string) error { return nil }
func (maintenanceBlobs) Put(context.Context, []byte) (string, error) { return "unused", nil }
func (maintenanceBlobs) Get(context.Context, string) ([]byte, error) {
return nil, errors.New("unexpected blob read")
}
func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) {
for _, partial := range []bool{false, true} {
t.Run(map[bool]string{false: "missing", true: "partial"}[partial], func(t *testing.T) {
ctx := context.Background()
f := &maintenanceGCFiler{Filer: chunkstore.NewMemFiler(), failSecond: partial}
cat, err := chunkstore.NewCatalog(f, defaultChunkPath)
if err != nil {
t.Fatal(err)
}
vol := "missing-volume"
if partial {
vol = "v1"
if _, err = cat.EnsureVolume(ctx, vol, chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
t.Fatal(err)
}
if err = cat.SetRetentionPolicy(ctx, vol, chunkstore.RetentionPolicy{}); err != nil {
t.Fatal(err)
}
now := time.Now().Add(-48 * time.Hour)
cat.SetClock(func() time.Time { return now })
for _, name := range []string{"a", "b"} {
if _, err = cat.CreateSnapshot(ctx, vol, chunkstore.SnapshotRequest{Name: name, RequestID: "req"}, storage.ChunkHead{Gen: 1, Epoch: 1, Holder: "h1", RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
t.Fatal(err)
}
now = now.Add(time.Second)
}
now = time.Now()
}
pass, closeFn, err := newChunkMaintenance(cat, maintenanceBlobs{}, true, "unused-master:1234")
if err != nil {
t.Fatal(err)
}
defer closeFn()
if err = pass(ctx, vol); err == nil {
t.Fatal("retention failure accepted")
}
if f.gcCalls != 0 {
t.Fatalf("retention failure entered GC %d times", f.gcCalls)
}
if partial && (f.marked != 1 || f.freed != 1) {
t.Fatalf("partial retention effects not retained: marked=%d freed=%d err=%v", f.marked, f.freed, err)
}
})
}
}
func TestMaintenanceDefaultRetainNeedsNoEpochClient(t *testing.T) {
f := chunkstore.NewMemFiler()
cat, err := chunkstore.NewCatalog(f, defaultChunkPath)
if err != nil {
t.Fatal(err)
}
if _, err = cat.EnsureVolume(context.Background(), "v", chunkstore.Geometry{NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 8}); err != nil {
t.Fatal(err)
}
pass, closeFn, err := newChunkMaintenance(cat, nil, false, "")
if err != nil {
t.Fatal(err)
}
defer closeFn()
if err = pass(context.Background(), "v"); err != nil {
t.Fatal(err)
}
}
+34 -12
View File
@@ -21,12 +21,15 @@ import (
const (
defaultChunkPath = "/swblock/chunks"
// The remote holds snapshots, not live data: cuts are published at
// snapshots, at detach/stop and on explicit request. The timer is off
// by default (an operator may set one, e.g. 15m, as a host-loss safety
// net); the dirty threshold only bounds how large one cut can grow.
defaultChunkCaptureInterval = 0
defaultChunkDirtyThreshold = 512 // chunks, 2 GiB at 4 MiB chunks
// Periodic HEAD publication bounds the host-loss recovery point. Automatic
// named snapshots remain explicit catalog operations.
defaultChunkCaptureInterval = 15 * time.Minute
defaultChunkMaintenanceInterval = time.Hour
defaultChunkCutTimeout = 5 * time.Minute
defaultChunkMaintenanceTimeout = time.Minute
defaultChunkGCGrace = time.Hour
defaultChunkIntentTTL = time.Hour
defaultChunkDirtyThreshold = 512 // chunks, 2 GiB at 4 MiB chunks
)
type chunkFlags struct {
@@ -37,6 +40,8 @@ type chunkFlags struct {
collection string
replication string
captureInterval time.Duration
maintenanceInterval time.Duration
automaticGC bool
dirtyThreshold int
uploadConcurrency int
hydrationWorkers int
@@ -56,7 +61,7 @@ func validateChunkFlags(f flags) error {
}
if f.durableImpl != "walstore-chunk" {
if c.filer != "" || c.collection != "" || c.replication != "" || c.path != defaultChunkPath ||
c.captureInterval != defaultChunkCaptureInterval || c.dirtyThreshold != defaultChunkDirtyThreshold ||
c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || c.dirtyThreshold != defaultChunkDirtyThreshold ||
c.uploadConcurrency != 8 || c.hydrationWorkers != 2 || c.hydrationQueueDepth != 64 || c.controlEndpoint || c.detachPrecopy || c.hostLimit.Directory != "" {
return errors.New("--chunk-* flags require --durable-impl=walstore-chunk")
}
@@ -77,6 +82,12 @@ func validateChunkFlags(f flags) error {
if !path.IsAbs(c.path) || path.Clean(c.path) != c.path || c.path == "/" {
return fmt.Errorf("--chunk-path=%q must be a clean absolute filer directory other than /", c.path)
}
if c.maintenanceInterval < 0 {
return errors.New("--chunk-maintenance-interval must not be negative")
}
if c.captureInterval > 0 && c.captureInterval < 5*time.Minute {
return errors.New("--chunk-capture-interval must be 0 or at least 5m")
}
if c.captureInterval < 0 {
return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval)
}
@@ -106,14 +117,15 @@ const chunkRF1Reason = "chunk snapshots take the cut LSN from the local WAL, whi
// provider's per-volume remotes, the catalog under the same base (VOLUME
// entries, snapshots) and the client's closer.
type chunkWiring struct {
remoteFor func(volumeID string) (storage.ChunkRemote, error)
catalog *chunkstore.Catalog
close func() error
remoteFor func(volumeID string) (storage.ChunkRemote, error)
catalog *chunkstore.Catalog
maintenance func(context.Context, string) error
close func() error
}
// newChunkWiring dials the filer and refuses unless it is the only filer of
// its group (chunkstore.CheckSingleFiler).
func newChunkWiring(c chunkFlags) (chunkWiring, error) {
func newChunkWiring(c chunkFlags, master ...string) (chunkWiring, error) {
client, err := chunkstore.DialSWFS(chunkstore.SWFSConfig{
FilerGRPC: c.filer,
Collection: c.collection,
@@ -133,7 +145,17 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) {
_ = client.Close()
return chunkWiring{}, err
}
var masterAddr string
if len(master) > 0 {
masterAddr = master[0]
}
maintenance, closeMaintenance, err := newChunkMaintenance(cat, client, c.automaticGC, masterAddr)
if err != nil {
_ = client.Close()
return chunkWiring{}, err
}
return chunkWiring{
maintenance: maintenance,
remoteFor: func(volumeID string) (storage.ChunkRemote, error) {
root, err := chunkVolumeRoot(c.path, volumeID)
if err != nil {
@@ -142,7 +164,7 @@ func newChunkWiring(c chunkFlags) (chunkWiring, error) {
return chunkstore.NewSWFSChunkRemote(client, root)
},
catalog: cat,
close: client.Close,
close: func() error { return errors.Join(closeMaintenance(), client.Close()) },
}, nil
}
@@ -15,11 +15,11 @@ func TestWALStoreChunkFlags(t *testing.T) {
return append(phase150RequiredBlockvolumeArgs(), extra...)
}
f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
"--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=30s"))
"--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=5m"))
if err != nil {
t.Fatalf("walstore-chunk with a filer: %v", err)
}
if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 30*time.Second || f.chunk.controlEndpoint {
if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 5*time.Minute || f.chunk.controlEndpoint {
t.Fatalf("parsed chunk flags = %+v", f.chunk)
}
f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
@@ -31,8 +31,8 @@ func TestWALStoreChunkFlags(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if d.chunk.captureInterval != 0 || d.chunk.dirtyThreshold != 512 {
t.Fatalf("scheduler defaults interval %s threshold %d, want timer off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold)
if d.chunk.captureInterval != 15*time.Minute || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC || d.chunk.dirtyThreshold != 512 {
t.Fatalf("scheduler defaults interval %s threshold %d, want capture 15m, maintenance 1h, GC off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold)
}
off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
"--chunk-capture-interval=0", "--chunk-dirty-threshold=0"))
@@ -43,13 +43,15 @@ func TestWALStoreChunkFlags(t *testing.T) {
t.Fatalf("walstore with the chunk defaults untouched: %v", err)
}
refused := map[string][]string{
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"),
"no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"),
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"),
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"),
"negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"),
"chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"),
"chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"),
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"),
"no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"),
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"),
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"),
"below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"),
"negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"),
"negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"),
"chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"),
"chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"),
"control endpoint on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--status-addr=127.0.0.1:0",
"--chunk-control-endpoint"),
"control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
+8 -2
View File
@@ -203,7 +203,9 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)")
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: automatic cut once this long has passed since the last successful cut; 0 (default) disables the timer, e.g. 15m as a host-loss safety net")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 15m, minimum 5m); 0 disables")
fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables")
fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification")
fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)")
fs.IntVar(&f.chunk.hydrationWorkers, "chunk-hydration-workers", 2, "walstore-chunk: concurrent lazy chunk fetches per volume (1..64)")
fs.IntVar(&f.chunk.hydrationQueueDepth, "chunk-hydration-queue-depth", 64, "walstore-chunk: distinct queued/in-flight hydration chunks per volume (1..65536)")
@@ -658,8 +660,12 @@ func run(f flags) int {
var chunkErr error
var chunk chunkWiring
if cfg.Impl == durable.ImplWALStoreChunk {
chunk, chunkErr = newChunkWiring(f.chunk)
chunk, chunkErr = newChunkWiring(f.chunk, f.masterAddr)
cfg.ChunkCaptureInterval = f.chunk.captureInterval
cfg.ChunkCutTimeout = defaultChunkCutTimeout
cfg.ChunkMaintenanceInterval = f.chunk.maintenanceInterval
cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout
cfg.ChunkMaintenance = chunk.maintenance
cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy
cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold
cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency
+6 -1
View File
@@ -77,6 +77,7 @@ type gcIntent struct {
// Different collectors may duplicate idempotent blob deletes but cannot
// shorten either collector's independent two-mark grace requirement.
type Collector struct {
scope string // empty traces and reclaims the entire namespace
cat *Catalog
blobs BlobDeleter
cfg GCConfig
@@ -218,7 +219,7 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
// and the actual CAS domain must have
// advanced. Mere lease loss, or issuance without takeover,
// cannot authorize expiry of a paused publisher's intent.
expire = authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued
expire = (g.scope == "" || g.scope == vol) && authorityErr == nil && issued > in.Epoch && h.Epoch > in.Epoch && h.Epoch <= issued
}
if expire {
expired = append(expired, gcIntent{r, in})
@@ -256,6 +257,10 @@ func (g *Collector) run(ctx context.Context, apply bool) (result GCResult, err e
}
}
}
// INV-MAINT-SCOPE: roots above remain catalog-wide; candidates are local.
if g.scope != "" && g.scope != vol {
continue
}
pageAfter := ""
for {
page, e := g.cat.f.ListEntries(ctx, r.keyDir(), "", pageAfter, listPage)
@@ -31,6 +31,9 @@ func (g *Collector) SweepCopies(ctx context.Context) (settled int, err error) {
}
var pending []copyAttempt
for _, vol := range vols {
if g.scope != "" && g.scope != vol {
continue
}
r, e := NewChunkRemote(g.cat.f, nilBlobs{}, path.Join(g.cat.base, vol))
if e != nil {
return 0, e
@@ -25,6 +25,7 @@ type savedGCCandidate struct {
Digest string `json:"digest"`
}
type savedGCMark struct {
Scope string `json:"scope,omitempty"`
Format int `json:"format"`
Base string `json:"base"`
GraceNs int64 `json:"grace_ns"`
@@ -53,6 +54,19 @@ type GCExecution struct {
// and identify uncertain stages, rather than asserting remote absence.
// The catalog namespace is the scope; permanent tombstones are untouched.
func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool) (out GCExecution, err error) {
return c.executeGC(ctx, blobs, cfg, apply, "")
}
// ExecuteVolumeGC reclaims only volumeID's objects while tracing every volume's
// roots. Its persisted two-mark coverage never aliases namespace-wide coverage.
func (c *Catalog) ExecuteVolumeGC(ctx context.Context, volumeID string, blobs BlobDeleter, cfg GCConfig, apply bool) (GCExecution, error) {
if err := CheckVolumeID(volumeID); err != nil {
return GCExecution{GCResult: GCResult{UnknownUnbound: true}}, err
}
return c.executeGC(ctx, blobs, cfg, apply, volumeID)
}
func (c *Catalog) executeGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig, apply bool, scope string) (out GCExecution, err error) {
// Pre-binding needles remain unenumerable even if admission/readback fails.
out.UnknownUnbound = true
out.DryRun = !apply
@@ -62,6 +76,7 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig
if err != nil {
return out, err
}
g.scope = scope
mark, previous, err := g.readMark(ctx)
if err != nil {
return out, err
@@ -109,7 +124,7 @@ func (c *Catalog) ExecuteGC(ctx context.Context, blobs BlobDeleter, cfg GCConfig
}
func (g *Collector) mark(ready bool) savedGCMark {
m := savedGCMark{Format: 1, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
m := savedGCMark{Format: 1, Scope: g.scope, Base: g.cat.base, GraceNs: int64(g.cfg.Grace), TTLNs: int64(g.cfg.IntentTTL), OpDeadlineNs: int64(g.cat.deadline()), Ready: ready, Candidates: map[string]savedGCCandidate{}}
if ready {
m.LastNs = g.last.UnixNano()
for p, c := range g.candidates {
@@ -119,8 +134,15 @@ func (g *Collector) mark(ready bool) savedGCMark {
return m
}
func (g *Collector) markDir() string {
if g.scope != "" {
return path.Join(g.cat.base, g.scope)
}
return g.cat.base
}
func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error) {
e, err := g.cat.f.LookupEntry(ctx, g.cat.base, gcMarkName)
e, err := g.cat.f.LookupEntry(ctx, g.markDir(), gcMarkName)
if errors.Is(err, ErrNotFound) {
return nil, "", nil
}
@@ -141,7 +163,7 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error)
if err = d.Decode(&trailing); err != io.EOF {
return nil, "", errors.New("chunkstore: trailing GC mark content")
}
if m.Format != 1 || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 {
if m.Format != 1 || m.Scope != g.scope || m.Base != g.cat.base || m.GraceNs <= 0 || m.TTLNs <= 0 || m.OpDeadlineNs <= 0 {
return nil, "", errors.New("chunkstore: incompatible GC mark")
}
if m.Ready {
@@ -151,7 +173,7 @@ func (g *Collector) readMark(ctx context.Context) (*savedGCMark, string, error)
}
for p, c := range m.Candidates {
digest, err := hex.DecodeString(c.Digest)
if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.cat.base+"/") || !strings.Contains(p, "/"+keysDir+"/") {
if err != nil || len(digest) != 32 || c.SinceNs <= 0 || c.SinceNs > m.LastNs || path.Clean(p) != p || !strings.HasPrefix(p, g.markDir()+"/") || !strings.Contains(p, "/"+keysDir+"/") {
return nil, "", errors.New("chunkstore: invalid GC candidate state")
}
}
@@ -176,9 +198,9 @@ func (g *Collector) writeMark(ctx context.Context, m savedGCMark, expected strin
now := g.cfg.Now().Unix()
e := &filerpb.Entry{Name: gcMarkName, Attributes: &filerpb.FuseAttributes{FileSize: uint64(len(body)), Crtime: now, Mtime: now, FileMode: 0600}, Content: body, Extended: map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(token)}}
if expected == "" {
err = g.cat.f.CreateEntry(ctx, g.cat.base, e, true)
err = g.cat.f.CreateEntry(ctx, g.markDir(), e, true)
} else {
err = g.cat.f.UpdateEntry(ctx, g.cat.base, e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)})
err = g.cat.f.UpdateEntry(ctx, g.markDir(), e, map[string][]byte{extKind: []byte(gcMarkKind), gcToken: []byte(expected)})
}
if err != nil {
return "", fmt.Errorf("chunkstore: GC watermark changed or unavailable: %w", err)
@@ -0,0 +1,239 @@
package chunkstore
import (
"context"
"errors"
"path"
"reflect"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
t.Fatal(err)
}
v1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
v2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2"))
for _, key := range []string{"rooted-only-from-v2", "local-orphan"} {
if err := v1.Put(ctx, key, []byte(key)); err != nil {
t.Fatal(err)
}
}
if err := v2.Put(ctx, "foreign-orphan", []byte("foreign")); err != nil {
t.Fatal(err)
}
if _, err := v2.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "snapshot:v2/s1/req", Keys: []string{"@v1/rooted-only-from-v2"}}); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil {
t.Fatal(err)
}
*now = now.Add(2 * time.Hour)
}
if _, err := v1.Get(ctx, "local-orphan"); err == nil {
t.Error("local orphan not reclaimed")
}
if _, err := v1.Get(ctx, "rooted-only-from-v2"); err != nil {
t.Errorf("foreign root lost: %v", err)
}
if _, err := v2.Get(ctx, "foreign-orphan"); err != nil {
t.Errorf("scoped pass reclaimed foreign candidate: %v", err)
}
}
func TestGC_GraceConstructorRejectsCopyDeadline(t *testing.T) {
_, b, c, g, _ := gcFixture(t)
for _, grace := range []time.Duration{0, c.deadline() - time.Nanosecond, c.deadline()} {
cfg := g.cfg
cfg.Grace = grace
if _, err := NewCollector(c, b, cfg); err == nil {
t.Errorf("accepted grace %s <= copy deadline", grace)
}
}
cfg := g.cfg
cfg.Grace = c.deadline() + time.Nanosecond
if _, err := NewCollector(c, b, cfg); err != nil {
t.Fatal(err)
}
}
func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil {
t.Fatal(err)
}
if _, err := c.ExecuteGC(ctx, b, g.cfg, true); err != nil {
t.Fatal(err)
}
*now = now.Add(2 * time.Hour)
// A separate scope must take its own first mark, even with mature global coverage.
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
if err != nil || result.Reclaimed != 0 {
t.Fatalf("scope imported namespace coverage: %+v %v", result, err)
}
if _, err = f.LookupEntry(ctx, path.Join(catBase, "v1"), gcMarkName); errors.Is(err, ErrNotFound) {
t.Fatal("scoped watermark absent")
}
}
func TestVolumeGC_IncompletePassAndConfigChangeDiscardCoverage(t *testing.T) {
for _, mode := range []string{"incomplete", "config"} {
t.Run(mode, func(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if err := r.Put(ctx, "orphan", []byte("bytes")); err != nil {
t.Fatal(err)
}
if _, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil {
t.Fatal(err)
}
*now = now.Add(2 * time.Hour)
if mode == "incomplete" {
g.scope = "v1"
_, token, err := g.readMark(ctx)
if err != nil {
t.Fatal(err)
}
if _, err = g.writeMark(ctx, g.mark(false), token); err != nil {
t.Fatal(err)
}
} else {
g.cfg.IntentTTL += time.Second
}
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
if err != nil || result.Reclaimed != 0 {
t.Fatalf("stale coverage used: %+v %v", result, err)
}
*now = now.Add(2 * time.Hour)
result, err = c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
if err != nil || result.Reclaimed != 1 {
t.Fatalf("fresh coverage did not progress: %+v %v", result, err)
}
})
}
}
func TestVolumeGC_ForeignForkHeadIsSoleRoot(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x22)})
if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "req"}, h); err != nil {
t.Fatal(err)
}
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "fork"}); err != nil {
t.Fatal(err)
}
r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1"))
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: h.Gen, Epoch: h.Epoch}, storage.ChunkHead{Epoch: 1, Holder: "h1", RemoteLSN: h.RemoteLSN, Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
t.Fatal(err)
}
if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
if out, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true); err != nil || out.Reclaimed != 0 {
t.Fatalf("foreign-only fork root reclaimed: %+v %v", out, err)
}
*now = now.Add(2 * time.Hour)
}
for _, ref := range h.Chunks {
if _, err := r.Get(ctx, ref.Key); err != nil {
t.Fatal("fork bytes reclaimed", err)
}
}
}
func TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
t.Fatal(err)
}
remotes := map[string]*ChunkRemote{}
for _, vol := range []string{"v1", "v2"} {
remote, _ := NewChunkRemote(f, b, path.Join(catBase, vol))
remotes[vol] = remote
if err := remote.Put(ctx, "capture", []byte("protected")); err != nil {
t.Fatal(err)
}
if _, err := remote.PutIntent(ctx, storage.ChunkIntent{Epoch: 1, Holder: "old", Keys: []string{"capture"}}); err != nil {
t.Fatal(err)
}
cur, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if _, err := remote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, storage.ChunkHead{Epoch: 2, Holder: "new", Chunks: map[uint64]storage.ChunkRef{}}); err != nil {
t.Fatal(err)
}
}
g.cfg.IssuedEpoch = func(context.Context, string) (uint64, error) { return 2, nil }
*now = time.Now().Add(3 * time.Hour)
foreign, _ := remotes["v2"].ListIntents(ctx)
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
local, _ := remotes["v1"].ListIntents(ctx)
after, _ := remotes["v2"].ListIntents(ctx)
if err != nil || result.ExpiredIntents != 1 || len(local) != 0 || !reflect.DeepEqual(foreign, after) {
t.Fatalf("capture scope mutated foreign intent: %+v %v before=%+v after=%+v", result, err, foreign, after)
}
if _, err := remotes["v2"].Get(ctx, "capture"); err != nil {
t.Fatal("foreign protection lost", err)
}
result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true)
if err != nil || result.ExpiredIntents != 1 {
t.Fatalf("foreign positive eligibility not witnessed: %+v %v", result, err)
}
}
func TestVolumeGC_ForeignEligibleCopyIsNotSettled(t *testing.T) {
f, b, c, g, now := gcFixture(t)
ctx := context.Background()
c.SetClock(func() time.Time { return *now })
if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil {
t.Fatal(err)
}
if _, err := c.EnsureVolume(ctx, "v2", catGeo); err != nil {
t.Fatal(err)
}
for _, vol := range []string{"v1", "v2"} {
h := publishSource(t, f, b.fakeBlobs, vol, map[uint64][]byte{0: chunkBytes(0x55)})
snapshotDir(t, f, vol, "held")
holdFirst(f, path.Join(catBase, vol, snapsDir, "held")+"/")
if _, err := c.CreateSnapshot(ctx, vol, SnapshotRequest{Name: "held", RequestID: "dead"}, h); CodeOf(err) != CodeOutcomeUnknown {
t.Fatalf("copy not held: %v", err)
}
}
before := intentsOf(t, f, "v2")
foreignPath := snapPath(t, f, "v2", "held")
*now = now.Add(DefaultOpDeadline + time.Second)
result, err := c.ExecuteVolumeGC(ctx, "v1", b, g.cfg, true)
after := intentsOf(t, f, "v2")
if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v1")) != 0 || !reflect.DeepEqual(before, after) {
t.Fatalf("copy scope changed foreign attempt: %+v %v", result, err)
}
if _, err := f.LookupEntry(ctx, path.Dir(foreignPath), path.Base(foreignPath)); !errors.Is(err, ErrNotFound) {
t.Fatalf("foreign pending copy claimed: %v", err)
}
result, err = c.ExecuteVolumeGC(ctx, "v2", b, g.cfg, true)
if err != nil || result.SettledCopies != 1 || len(intentsOf(t, f, "v2")) != 0 {
t.Fatalf("foreign positive settlement not witnessed: %+v %v", result, err)
}
}
@@ -0,0 +1,92 @@
package durable
import (
"context"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/storage"
"testing"
"time"
)
type maintenanceStubLayer struct{ storage.ChunkLayer }
func (maintenanceStubLayer) Fenced() bool { return false }
func TestMaintenanceRejectsForeignLineageBeforeAdmission(t *testing.T) {
for _, field := range []string{"epoch", "replica", "endpoint", "handle", "layer"} {
t.Run(field, func(t *testing.T) {
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
lin := chunkLineage{"v1", "r1", 3, 1}
layer := &maintenanceStubLayer{}
h := &volHandle{chunk: layer}
p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}}
if !p.maintenanceCurrent("v1", h, layer, lin) {
t.Fatal("healthy same attachment refused")
}
switch field {
case "epoch":
id.Epoch++
case "replica":
id.ReplicaID = "r2"
case "endpoint":
id.EndpointVersion++
case "handle":
p.volumes["v1"] = &volHandle{chunk: layer}
case "layer":
h.chunk = &maintenanceStubLayer{}
}
p.view = precopyQueueView{id}
p.cfg.ChunkMaintenanceInterval = time.Nanosecond
calls := 0
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) })
if calls != 0 {
t.Fatalf("foreign attachment admitted %d passes", calls)
}
})
}
}
func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) {
id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}
layer := &maintenanceStubLayer{}
h := &volHandle{chunk: layer, chunkLineage: chunkLineage{"v1", "r1", 3, 1}}
entered := make(chan struct{}, 2)
p := &DurableProvider{volumes: map[string]*volHandle{"v1": h}, view: precopyQueueView{id}, cfg: ProviderConfig{ChunkMaintenanceInterval: time.Nanosecond, ChunkMaintenance: func(ctx context.Context, _ string) error { entered <- struct{}{}; <-ctx.Done(); return ctx.Err() }}}
var stopperDone chan struct{}
t.Cleanup(func() {
p.mu.Lock()
stop, ownerDone := h.chunkStop, h.chunkDone
p.mu.Unlock()
if stop != nil {
stop()
}
for _, done := range []<-chan struct{}{stopperDone, ownerDone} {
if done != nil {
select {
case <-done:
case <-time.After(time.Second):
t.Error("cleanup did not join outstanding maintenance stopper/owner")
}
}
}
})
for i := 0; i < 2; i++ {
p.mu.Lock()
p.startChunkLoop("v1", h, layer)
p.mu.Unlock()
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("same handle did not arm")
}
done := make(chan struct{})
stopperDone = done
go func() { p.stopChunkLoop(h); close(done) }()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("stopped owner did not join")
}
}
}
@@ -0,0 +1,60 @@
package durable
import (
"context"
"fmt"
"sync"
"testing"
"testing/synctest"
"time"
)
func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) {
interval := 15 * time.Minute
seen := map[time.Duration]bool{}
for i := 0; i < 200; i++ {
s := initialCutSchedule(fmt.Sprintf("volume-%d", i), interval, t0, true)
offset := s.firstDue.Sub(t0)
if offset <= 0 || offset >= interval {
t.Fatalf("phase outside interval: %s", offset)
}
seen[offset] = true
if _, due := testPolicy().due(s, s.firstDue.Add(-time.Nanosecond), false); due {
t.Fatal("published before own phase")
}
}
if len(seen) < 190 {
t.Fatalf("200 volumes collapsed into %d phases", len(seen))
}
}
// Virtual quiescence observes the join boundary directly, so a slow storage
// Close cannot accidentally make an omitted scheduler join look correct.
func TestMaintenanceStopJoinsBeforeRelease(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done, release, cancelled := make(chan struct{}), make(chan struct{}), make(chan struct{})
var once sync.Once
finish := func() { once.Do(func() { close(release) }) }
defer finish()
p := &DurableProvider{}
h := &volHandle{chunkStop: cancel, chunkDone: done}
go func() { <-ctx.Done(); close(cancelled); <-release; close(done) }()
returned1, returned2 := make(chan struct{}), make(chan struct{})
go func() { p.stopChunkLoop(h); close(returned1) }()
<-cancelled
go func() { p.stopChunkLoop(h); close(returned2) }()
synctest.Wait()
for _, returned := range []chan struct{}{returned1, returned2} {
select {
case <-returned:
t.Error("stop released before worker join")
default:
}
}
finish()
<-returned1
<-returned2
})
}
@@ -172,6 +172,13 @@ type ProviderConfig struct {
// passed since the volume's last successful cut (of any kind). Zero
// disables the timer.
ChunkCaptureInterval time.Duration
// ChunkCutTimeout bounds a cut as a whole; zero uses five minutes.
ChunkCutTimeout time.Duration
// Maintenance runs serially for an attached healthy volume. Zero interval disables
// it. Callback ownership ends only after cancellation and worker settlement.
ChunkMaintenanceInterval time.Duration
ChunkMaintenanceTimeout time.Duration
ChunkMaintenance func(context.Context, string) error
// DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest
// I/O stopped before it resumes or settles: the drain and final cut get
// three quarters of it, the settlement of a failed cut the rest (the
@@ -266,9 +273,10 @@ type volHandle struct {
// wait, 0 if none: a recovered volume whose layer waits for master
// authority. A wait only acts while its generation is still the
// latest recovery's.
recoverGen uint64
waitGen uint64
chunk storage.ChunkLayer // after RecoverVolume
recoverGen uint64
waitGen uint64
chunk storage.ChunkLayer // after RecoverVolume
chunkLineage chunkLineage // immutable authority captured by this attachment
// Private until the owner commit succeeds; retained for attach retry.
chunkPending storage.ChunkLayer
// chunkDetach is set (under attachMu) when DetachVolume starts and
@@ -336,6 +344,12 @@ func NewDurableProvider(cfg ProviderConfig, view frontend.ProjectionView) (*Dura
if cfg.Impl == ImplWALStoreChunk && cfg.ChunkRemoteFor == nil {
return nil, fmt.Errorf("durable: impl %q requires ProviderConfig.ChunkRemoteFor", ImplWALStoreChunk)
}
if cfg.ChunkCaptureInterval < 0 || cfg.ChunkCutTimeout < 0 || cfg.ChunkMaintenanceInterval < 0 || cfg.ChunkMaintenanceTimeout < 0 {
return nil, fmt.Errorf("durable: chunk schedule durations must not be negative")
}
if cfg.ChunkMaintenanceInterval > 0 && cfg.ChunkMaintenance == nil {
return nil, fmt.Errorf("durable: chunk maintenance interval requires its callback")
}
if cfg.ChunkBlocks == 0 {
cfg.ChunkBlocks = defaultChunkBlocks
}
@@ -320,12 +320,14 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v
// startChunkLoop starts the periodic cuts of an attached layer, if configured
// and not already running. The caller holds h.attachMu and p.mu.
func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) {
if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil {
if (p.cfg.ChunkCaptureInterval <= 0 && (p.cfg.ChunkMaintenanceInterval <= 0 || p.cfg.ChunkMaintenance == nil)) || h.chunkStop != nil {
return
}
loopCtx, cancel := context.WithCancel(context.Background())
h.chunkStop, h.chunkDone = cancel, make(chan struct{})
go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone)
lin := h.chunkLineage
current := func() bool { return p.maintenanceCurrent(volumeID, h, layer, lin) }
go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone, current)
}
func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) {
@@ -466,7 +468,11 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
cfg.RestoreGuard = &storage.ChunkHeadVersion{Gen: head.Gen, Epoch: head.Epoch}
}
return storage.AttachChunkLayer(ws, remote, cfg)
layer, attachErr := storage.AttachChunkLayer(ws, remote, cfg)
if attachErr == nil {
h.chunkLineage = lin
}
return layer, attachErr
}
// closeBoundRemote ends every remote call when the provider closes, so a
@@ -635,7 +641,7 @@ const (
// cutPolicy decides when an automatic cut is due. The remote holds
// snapshots, not live data: cuts are published at Snapshot, Detach/stop
// and explicit Cut, and automatically only by the operator's timer:
// and explicit Cut, and automatically by the configured timer:
// - the timer fires once interval has passed since the last successful
// cut of any kind (explicit Cut, Snapshot and Detach included); zero
// disables it, and with it every automatic cut;
@@ -760,6 +766,7 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
if !ok {
continue
}
cutCtx, cancel := p.chunkCutContext(ctx)
trace := p.testChunkLoopTrace
if trace != nil {
trace("due", ls.LastCutNs, false)
@@ -769,19 +776,21 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer
// A cut that completed after this decision (an explicit one
// running meanwhile) restarted the timer: no cut now.
var skipped bool
_, skipped, err = pc.CutUnlessCutSince(ctx, ls.LastCutNs)
_, skipped, err = pc.CutUnlessCutSince(cutCtx, ls.LastCutNs)
if trace != nil {
trace("cut", ls.LastCutNs, skipped)
}
if skipped {
cancel()
continue
}
} else {
_, err = layer.Cut(ctx)
_, err = layer.Cut(cutCtx)
if trace != nil {
trace("cut", ls.LastCutNs, false)
}
}
cancel()
s = pol.after(s, start, time.Now(), err)
if err != nil && !errors.Is(err, storage.ErrChunkCaptureRefused) && ctx.Err() == nil {
log.Printf("durable: %s chunk cut for volume=%s: %v (retry in %s)", reason, volumeID, err, s.backoff)
@@ -789,15 +798,122 @@ 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) {
defer close(done)
defer cancel()
var workers sync.WaitGroup
if p.cfg.ChunkCaptureInterval > 0 {
workers.Add(1)
go func() {
defer workers.Done()
cutDone := make(chan struct{})
p.chunkLoop(ctx, volumeID, layer, cutDone)
}()
}
if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil {
workers.Add(1)
go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }()
}
timer := time.NewTicker(chunkSchedulePoll)
defer timer.Stop()
for ctx.Err() == nil {
select {
case <-ctx.Done():
case <-timer.C:
if layer.Fenced() {
cancel()
}
}
}
workers.Wait()
}
// maintenanceCurrent binds the pass to the attached handle AND its lineage.
// The projection can remain healthy while a different owner replaces it.
func (p *DurableProvider) maintenanceCurrent(volumeID string, h *volHandle, layer storage.ChunkLayer, lin chunkLineage) bool {
p.mu.Lock()
active := !p.closed && p.volumes[volumeID] == h && h.chunk == layer
p.mu.Unlock()
cur := p.view.Projection()
return active && chunkAuthority(cur, volumeID) && cur.VolumeID == lin.volumeID && cur.ReplicaID == lin.replicaID && cur.Epoch == lin.epoch && cur.EndpointVersion == lin.endpoint
}
func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer, current func() bool) {
interval := p.cfg.ChunkMaintenanceInterval
due := time.Now().Add(interval)
if p.cfg.ChunkStagger {
due = time.Now().Add(hostlimit.Phase(volumeID+":maintenance", interval))
}
timer := time.NewTimer(time.Until(due))
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-timer.C:
}
if ctx.Err() != nil || layer.Fenced() {
return
}
if !current() {
return
}
timeout := p.cfg.ChunkMaintenanceTimeout
if timeout <= 0 {
timeout = time.Minute
}
passCtx, cancel := context.WithTimeout(ctx, timeout)
// The projection has no change channel. One bounded watcher belongs to
// this pass, never to an individual tick; cancellation is joined below.
watchDone := make(chan struct{})
go func() {
defer close(watchDone)
tick := time.NewTicker(chunkSchedulePoll)
defer tick.Stop()
for {
select {
case <-passCtx.Done():
return
case <-tick.C:
if layer.Fenced() || !current() {
cancel()
return
}
}
}
}()
err := p.cfg.ChunkMaintenance(passCtx, volumeID)
cancel()
<-watchDone
if err != nil && ctx.Err() == nil {
log.Printf("durable: maintenance volume=%s: %v", volumeID, err)
}
// Completion-relative reset coalesces all elapsed ticks; no catch-up queue.
timer.Reset(interval)
}
}
func (p *DurableProvider) stopChunkLoop(h *volHandle) {
p.mu.Lock()
stop, done := h.chunkStop, h.chunkDone
h.chunkStop = nil
p.mu.Unlock()
if stop != nil {
stop()
}
// Every concurrent stopper joins the same lifetime; none can clear ownership
// while an earlier stopper is still waiting for an admitted remote call.
if done != nil {
<-done
}
p.mu.Lock()
if h.chunkDone == done {
h.chunkStop = nil
h.chunkDone = nil
}
p.mu.Unlock()
}
func (p *DurableProvider) chunkLayer(volumeID string) (storage.ChunkLayer, error) {
@@ -831,6 +947,8 @@ func (p *DurableProvider) chunkHandle(volumeID string) (*volHandle, storage.Chun
// CaptureVolume takes one quiesced cut of volumeID and publishes it to the
// remote. It returns the cut's LSN.
func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (uint64, error) {
ctx, cancel := p.chunkCutContext(ctx)
defer cancel()
layer, err := p.chunkLayer(volumeID)
if err != nil {
return 0, err
@@ -841,6 +959,8 @@ func (p *DurableProvider) CaptureVolume(ctx context.Context, volumeID string) (u
// MakeVolumeRemoteDurable returns nil only once volumeID's writes up to lsn
// are published in the remote HEAD (snapshot, detach, migrate).
func (p *DurableProvider) MakeVolumeRemoteDurable(ctx context.Context, volumeID string, lsn uint64) error {
ctx, cancel := p.chunkCutContext(ctx)
defer cancel()
layer, err := p.chunkLayer(volumeID)
if err != nil {
return err
@@ -863,7 +983,17 @@ func chunkFenced(volumeID string, h *volHandle) error {
// and the cut's statistics (B9 W2 §2.4, §3.1). With minLSN > 0 it is
// MakeRemoteDurable(minLSN) returning the cut: an LSN never written is
// refused before anything is published, and the cut must reach minLSN.
func (p *DurableProvider) chunkCutContext(ctx context.Context) (context.Context, context.CancelFunc) {
timeout := p.cfg.ChunkCutTimeout
if timeout <= 0 {
timeout = 5 * time.Minute
}
return context.WithTimeout(ctx, timeout)
}
func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN uint64) (storage.ChunkCutResult, error) {
ctx, cancel := p.chunkCutContext(ctx)
defer cancel()
h, layer, err := p.chunkHandle(volumeID)
if err != nil {
return storage.ChunkCutResult{}, err
@@ -0,0 +1,360 @@
package durable_test
import (
"context"
"errors"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) {
entered, cancelled, release := make(chan struct{}), make(chan struct{}), make(chan struct{})
var once sync.Once
finish := func() { once.Do(func() { close(release) }) }
remote := storage.NewMemChunkRemote()
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
ChunkMaintenanceInterval: time.Millisecond,
ChunkMaintenance: func(ctx context.Context, vol string) error {
close(entered)
<-ctx.Done()
close(cancelled)
<-release
return ctx.Err()
},
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { finish(); _ = p.Close() })
s := openRecovered(t, p)
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("maintenance did not start with cut timer off")
}
writeDone := make(chan error, 1)
writerSettled := make(chan struct{})
go func() { defer close(writerSettled); _, err := s.Write(1, block(0x51)); writeDone <- err }()
t.Cleanup(func() {
finish()
_ = p.Close()
select {
case <-writerSettled:
case <-time.After(5 * time.Second):
t.Error("writer cleanup did not settle")
}
})
select {
case err := <-writeDone:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("maintenance held a guest lock")
}
closed := make(chan error, 1)
closeSettled := make(chan struct{})
go func() { defer close(closeSettled); closed <- p.Close() }()
t.Cleanup(func() {
finish()
select {
case <-closeSettled:
case <-time.After(5 * time.Second):
t.Error("Close cleanup did not settle")
}
})
select {
case <-cancelled:
case <-time.After(5 * time.Second):
t.Fatal("Close did not cancel maintenance")
}
select {
case err := <-closed:
t.Fatalf("Close released resources before worker join: %v", err)
default:
}
finish()
select {
case err := <-closed:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("Close did not join")
}
}
func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) {
view := v1View()
entered, cancelled := make(chan struct{}), make(chan struct{})
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
ChunkMaintenanceInterval: time.Millisecond,
ChunkMaintenance: func(ctx context.Context, _ string) error {
close(entered)
<-ctx.Done()
close(cancelled)
return ctx.Err()
},
}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
openRecovered(t, p)
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("no pass")
}
view.set(frontend.Projection{VolumeID: "v1", ReplicaID: "r1"})
select {
case <-cancelled:
case <-time.After(5 * time.Second):
t.Fatal("lost authority did not cancel held pass")
}
}
func TestMaintenancePassHasOneDeadline(t *testing.T) {
entered := make(chan error, 1)
three := make(chan struct{})
var completed atomic.Int32
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
ChunkMaintenanceInterval: time.Millisecond, ChunkMaintenanceTimeout: 10 * time.Millisecond,
ChunkMaintenance: func(ctx context.Context, _ string) error {
<-ctx.Done()
select {
case entered <- ctx.Err():
default:
}
if completed.Add(1) == 3 {
close(three)
}
return ctx.Err()
},
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
done := make(chan struct{})
go func() { _ = p.Close(); close(done) }()
timer := time.NewTimer(5 * time.Second)
defer timer.Stop()
for {
select {
case <-done:
return
case <-entered:
case <-timer.C:
t.Error("deadline callback cleanup failed to join")
return
}
}
})
openRecovered(t, p)
// Deliberately leave the one-slot observation full across recurring passes.
select {
case <-three:
case <-time.After(5 * time.Second):
t.Fatal("recurring callback blocked with delayed receiver")
}
select {
case err := <-entered:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatal(err)
}
default:
t.Fatal("no deadline observation")
}
}
type pendingMaintenancePut struct{ *storage.MemChunkRemote }
func (r pendingMaintenancePut) Put(ctx context.Context, _ string, _ []byte) error {
<-ctx.Done()
return ctx.Err()
}
func TestCutDeadlineIncludesUploadWithBackgroundCaller(t *testing.T) {
remote := pendingMaintenancePut{storage.NewMemChunkRemote()}
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, ChunkCutTimeout: 10 * time.Millisecond,
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
s := openRecovered(t, p)
if _, err = s.Write(1, block(0x48)); err != nil {
t.Fatal(err)
}
_, err = p.CaptureVolume(context.Background(), "v1")
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("whole cut did not expire: %v", err)
}
h, err := remote.GetHead(context.Background())
if err != nil || h.Gen != 0 {
t.Fatalf("expired upload published: %+v %v", h, err)
}
}
func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) {
entered, release := make(chan struct{}), make(chan struct{})
var once sync.Once
finish := func() { once.Do(func() { close(release) }) }
var calls atomic.Int32
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
ChunkMaintenanceInterval: time.Millisecond,
ChunkMaintenance: func(ctx context.Context, _ string) error {
if calls.Add(1) == 1 {
close(entered)
}
select {
case <-release:
case <-ctx.Done():
}
return ctx.Err()
},
}, v1View())
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { finish(); _ = p.Close() })
openRecovered(t, p)
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("no pass")
}
time.Sleep(30 * time.Millisecond)
if got := calls.Load(); got != 1 {
t.Fatalf("held pass started %d workers", got)
}
// Close cancels the held pass before release; there is no queued retry to drain.
if err := p.Close(); err != nil {
t.Fatal(err)
}
if got := calls.Load(); got != 1 {
t.Fatalf("Close dispatched %d elapsed ticks", got)
}
finish()
}
func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) {
remote := storage.NewMemChunkRemote()
p := schedProvider(t, remote, time.Millisecond, 0)
s := openRecovered(t, p)
lsn, err := s.Write(1, block(0x91))
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var first storage.ChunkHead
for {
first, err = remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if first.RemoteLSN >= lsn {
break
}
select {
case <-ctx.Done():
t.Fatal(ctx.Err())
case <-time.After(time.Millisecond):
}
}
var before int64
for before == 0 {
before = p.DurableStatuses()[0].Chunk.Stats.LastCutNs
select {
case <-ctx.Done():
t.Fatal("first cut did not settle", ctx.Err())
case <-time.After(time.Millisecond):
}
}
for {
status := p.DurableStatuses()[0]
if status.Chunk.Stats.LastCutNs > before {
break
}
select {
case <-ctx.Done():
t.Fatal("no periodic noop", ctx.Err())
case <-time.After(time.Millisecond):
}
}
after, err := remote.GetHead(ctx)
if err != nil || after.Gen != first.Gen {
t.Fatalf("noop churned HEAD: before=%d after=%d err=%v", first.Gen, after.Gen, err)
}
}
func TestMaintenanceHealthyLineageChangeCancelsHeldPass(t *testing.T) {
for _, field := range []string{"epoch", "replica", "endpoint"} {
t.Run(field, func(t *testing.T) {
view := v1View()
entered, cancelled := make(chan struct{}), make(chan struct{})
var enterOnce, cancelOnce sync.Once
p, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil },
ChunkMaintenanceInterval: time.Millisecond,
ChunkMaintenance: func(ctx context.Context, _ string) error {
enterOnce.Do(func() { close(entered) })
<-ctx.Done()
cancelOnce.Do(func() { close(cancelled) })
return ctx.Err()
},
}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
done := make(chan struct{})
go func() { _ = p.Close(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Error("lineage cleanup did not join")
}
})
openRecovered(t, p)
select {
case <-entered:
case <-time.After(5 * time.Second):
t.Fatal("no held pass")
}
cur := view.Projection()
switch field {
case "epoch":
cur.Epoch++
case "replica":
cur.ReplicaID = "r2"
case "endpoint":
cur.EndpointVersion++
}
view.set(cur)
select {
case <-cancelled:
case <-time.After(5 * time.Second):
t.Fatal("healthy foreign lineage did not cancel pass")
}
})
}
}
@@ -121,3 +121,90 @@ func TestChunkStageV3_FourTimesCapConvergesUnderSteadyWrites(t *testing.T) {
assertEveryHeadIsPrefixImage(t, f, w)
assertNoIntentsLeft(t, f)
}
// Each of two deadlines interrupts the third upload, after two immutable chunks
// completed. The next pass must reuse those chunks rather than restart the set.
type deadlineProgressRemote struct {
successful map[string][]byte
*fakeChunkRemote
completed int
calls int
}
func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) error {
r.calls++
if r.completed == 2 {
<-ctx.Done()
return ctx.Err()
}
err := r.fakeChunkRemote.Put(ctx, key, b)
if err == nil {
r.completed++
if _, exists := r.successful[key]; exists {
return errors.New("test: retransmitted unchanged successful key")
}
if r.successful == nil {
r.successful = map[string][]byte{}
}
r.successful[key] = append([]byte(nil), b...)
}
return err
}
func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 5)
l.cfg.COWSpillLimit = ctChunkBytes
l.cfg.UploadConcurrency = 1
r := &deadlineProgressRemote{fakeChunkRemote: f}
l.remote = r
base := f.stats().head.Gen
previous := 0
lastSubmitted := s.NextLSN() - 1
expectedImage := w.imageAt(lastSubmitted)
var finalHead chunkHead
for pass := 0; pass < 3; pass++ {
r.completed = 0
r.calls = 0
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
result, err := l.Cut(ctx)
cancel()
if pass < 2 {
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("pass %d did not reach injected deadline: %v", pass, err)
}
if f.stats().head.Gen != base {
t.Fatal("deadline moved HEAD")
}
l.stMu.Lock()
cached := len(l.reusable)
l.stMu.Unlock()
if cached <= previous {
t.Fatalf("pass %d restarted dirty set: cached=%d previous=%d", pass, cached, previous)
}
previous = cached
} else if err != nil || result.Head.Gen != base+1 {
t.Fatalf("third pass failed to publish: %+v %v", result, err)
} else {
finalHead = result.Head
}
}
// Five changed chunks, five successful puts, no retransmission after expiry.
if len(r.successful) != 5 {
t.Fatalf("successful upload keys=%d want5", len(r.successful))
}
totalBytes := 0
for _, payload := range r.successful {
totalBytes += len(payload)
}
if totalBytes != 5*ctChunkBytes {
t.Fatalf("uploaded bytes=%d want%d", totalBytes, 5*ctChunkBytes)
}
assertEveryHeadIsPrefixImage(t, f, w)
if finalHead.RemoteLSN != lastSubmitted {
t.Fatalf("final frontier=%d want last submitted=%d", finalHead.RemoteLSN, lastSubmitted)
}
assertImage(t, "final complete submitted image", f.imageOf(t, finalHead), expectedImage)
if previous != 4 {
t.Fatalf("reusable chunks=%d", previous)
}
assertNoIntentsLeft(t, f)
}
@@ -72,8 +72,8 @@ A workspace runs one replica (RF=1). It does not use the replication engine of t
| Permanent host loss | the image at the last successful cut (HEAD `RemoteLSN`); writes after it are lost |
| Clean move (Detach) | everything written before Detach: guest I/O is stopped, then Detach publishes a final cut before the host releases the volume |
- **When cuts happen.** At semantic points chosen by the integrator (after an agent step, before a risky command, on detach) and on explicit request (`sw-block ops chunk cut`). The periodic timer is off by default (`cmd/blockvolume/chunk_remote.go` `defaultChunkCaptureInterval = 0`); an operator may set one as a host-loss safety net. `--chunk-dirty-threshold` (default 512 chunks, 2 GiB) bounds pre-copy staging work; native COW copies the remainder outside its barrier. It never triggers a cut.
- **So the default RPO is unbounded** until the integrator cuts. This is a design choice for workspaces, where a cut at a semantic point is more useful than a timer.
- **When cuts happen.** At semantic points chosen by the integrator, on explicit request, and by the periodic timer (default 15m, minimum 5m in the OSS CLI; 0 disables). Periodic cuts update HEAD without creating named snapshots. `--chunk-dirty-threshold` bounds staging work and never triggers a cut.
- **Recoverable frontier.** The confirmed remote HEAD is the recovery point after host loss. The default capture interval is 15m; failed or expired attempts retry with bounded backoff and reusable uploads, and do not claim a newly durable recovery point.
- Multi-replica workspaces combined with chunk snapshots are not supported.
## 3. Remote layout
@@ -235,6 +235,33 @@ stateDiagram-v2
The attempt path is never removed, so a late create can never land after a delete.
### Attached-volume scheduling
Blockvolume defaults to periodic HEAD capture every 15 minutes (minimum 5
minutes, 0 disables) and retention every hour. Named snapshots remain explicit.
A five-minute context covers the whole cut; completed immutable uploads survive
an expired attempt only under matching version/HEAD generation. Automatic GC is
opt-in until the 50/200-volume metadata/RSS qualification accepts its full-catalog
scan cost. Scoped GC changes candidates, not the catalog root domain; each volume
has independent persisted mark coverage. CLI catalog mutations also check the
single-filer deployment constraint before mutation.
```mermaid
stateDiagram-v2
[*] --> PendingAttach
PendingAttach --> Armed: attached and healthy
Armed --> Running: staggered due event
Running --> Armed: retention and optional scoped GC settle
Running --> Draining: detach, fence, close
Armed --> Draining: detach, fence, close
Draining --> Closed: cancel and join every worker
Draining --> Armed: safe detach abort, same current handle
```
No catch-up queue is accumulated. Retention failure skips GC; incomplete marks
and configuration changes do not authorize reclamation. Unknown same-epoch CAS
intents remain rooted after restart; elapsed TTL is not a settlement proof.
## 7. Lease, takeover and host moves
**Host guard** (`core/host/volume/workspace_lease.go` `WorkspaceLeaseGuard`, enabled with `blockvolume --workspace-lease`; see [workspace lease](../workspace-lease.md)): frontend I/O and cuts are admitted only with a granted, unexpired lease for the exact `{volume, replica, epoch}`. Validity is anchored to the renewal request's start time, and blockmaster's `ValidForNs` already subtracts half the clock-skew bound (`core/host/master/workspace_service.go` `leaseFact`). A late reply cannot extend admission. A fenced guard never reopens. The lease is 30 s (`core/authority/authority.go`, `workspaceTTL`); the skew bound defaults to 20 s (`blockmaster --workspace-max-clock-skew`).
+20 -3
View File
@@ -258,6 +258,11 @@ stateDiagram-v2
| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` |
Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes;
0 explicitly disables); they do not create named snapshots. One five-minute
context covers a cut, including uploads. Deadline-aborted uploads remain rooted
and reusable only while their chunk version and HEAD generation match.
### M6 Chunk lifecycle
HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete).
@@ -345,9 +350,19 @@ snapshot lifetime; local persistence does not bypass it.
`free -> admitted -> draining -> joined -> released`; process death releases its OS slot. Configuration is published by temporary-file sync and rename under its OS lock; a killed initializer leaves no partially visible configuration. Admission precedes staging/barrier; expiry cancels the cut but keeps its slot until workers join. Urgent can borrow normal slots; normal cannot borrow urgent. Unavailable pools skip background work with an alarm; urgent move-final and named seals may use per-process fallback with no coordinated host-cap claim. Guest COW only accounts locally; guest I/O and WAL reclamation never acquire slots.
### M8. Attached-volume maintenance
`PendingAttach -> Armed -> Due -> Running -> Armed`; elapsed ticks coalesce.
A stable volume phase staggers the one-hour retention schedule. GC is opt-in
pending density qualification. Detach/fence/Close cancels and joins before
catalog/storage release; only a still-current handle may re-arm after safe abort.
A pass has one minute for retention and optional GC; retention failure skips GC.
A scoped GC pass traces the whole catalog but mutates only its target volume,
with a separate scope/config-bound mark. Incomplete marks carry no coverage.
## Part B. Invariant ledger
118 rows: 99 ACTIVE, 19 STUB; 15 kept from the internal ledger, 103 new.
124 rows: 105 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 109 new.
The "Machine / transition" column refers to Part A. Notes under a table record what a row does not cover and, for kept rows, what was narrowed from the internal ledger.
@@ -519,10 +534,13 @@ Notes:
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE |
| `INV-MAINT-ONE-OWNER` | Only the current attached handle with matching replica/epoch/endpoint admits maintenance; one attached volume admits at most one pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline`, `TestMaintenanceRejectsForeignLineageBeforeAdmission`, `TestMaintenanceSameHandleRearmsAfterJoinedStop` | `MaintenanceOwner` `OneOwner`, `CurrentHandleAtAdmission` | ACTIVE |
| `INV-MAINT-SCOPE` | Per-volume GC traces foreign roots while restricting candidate reclamation, intent expiry and copy settlement to its volume; namespace coverage is not imported. | M8 scoped GC | `gc.go` `Collector.run`; `gc_copy.go` `SweepCopies`; `gc_execution.go` `ExecuteVolumeGC` | `TestVolumeGC_ForeignIntentRootsAndLocalCandidates`, `TestVolumeGC_DoesNotImportGlobalMark`, `TestVolumeGC_ForeignEligibleCaptureIntentStaysProtected`, `TestVolumeGC_ForeignEligibleCopyIsNotSettled` | `ScopedMaintenanceGC` `ForeignRootSurvives`, `ForeignCandidatesUntouched`, `OwnCoverageOnly` | ACTIVE |
| `INV-MAINT-JOIN` | Detach/fence/Close cancels maintenance and joins admitted workers before releasing its catalog/storage lifetime. | M8 Running → Draining → Closed | `provider_chunk.go` `chunkBackground`, `stopChunkLoop` | `TestMaintenanceStopJoinsBeforeRelease`, `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass`, `TestMaintenanceHealthyLineageChangeCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | ACTIVE |
| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE |
| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE |
| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB |
| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRejectsCopyDeadline` | `RetentionGCTiming` `NoLiveDelete` | ACTIVE |
| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE |
| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE |
| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE |
@@ -530,7 +548,6 @@ Notes:
Notes:
- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace.
### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing
@@ -0,0 +1,37 @@
------------------------- MODULE MaintenanceOwner -------------------------
EXTENDS Naturals, TLC
CONSTANT AllowOverlap, ReleaseBeforeJoin, AllowStaleRearm
VARIABLES state, due, workers, released, owner, current, arms, closing
vars == <<state,due,workers,released,owner,current,arms,closing>>
Init == /\ state = "pending" /\ due = FALSE /\ workers = 0 /\ released = FALSE
/\ owner = 1 /\ current = 1 /\ arms = 0 /\ closing = FALSE
Attach == /\ state = "pending" /\ state' = "armed" /\ arms' = arms+1
/\ UNCHANGED <<due,workers,released,owner,current,closing>>
Tick == /\ state = "armed" /\ due' = TRUE
/\ UNCHANGED <<state,workers,released,owner,current,arms,closing>>
Start == /\ state = "armed" /\ due /\ (workers = 0 \/ AllowOverlap)
/\ workers < 2 /\ workers' = workers+1 /\ due' = FALSE
/\ UNCHANGED <<state,released,owner,current,arms,closing>>
Finish == /\ workers > 0 /\ workers' = workers-1
/\ UNCHANGED <<state,due,released,owner,current,arms,closing>>
Stop == /\ state = "armed" /\ state' = "draining" /\ due' = FALSE
/\ closing' \in BOOLEAN /\ UNCHANGED <<workers,released,owner,current,arms>>
Join == /\ state = "draining" /\ (workers = 0 \/ ReleaseBeforeJoin)
/\ state' = IF closing THEN "closed" ELSE "idle"
/\ released' = TRUE /\ UNCHANGED <<due,workers,owner,current,arms,closing>>
Rearm == /\ state = "idle" /\ arms < 3 /\ (owner = current \/ AllowStaleRearm)
/\ state' = "armed" /\ released' = FALSE /\ arms' = arms+1
/\ UNCHANGED <<due,workers,owner,current,closing>>
ReplaceHandle == /\ state = "idle" /\ workers = 0 /\ current = 1
/\ current' = 2
/\ UNCHANGED <<state,due,workers,released,owner,arms,closing>>
AttachCurrent == /\ state = "idle" /\ workers = 0 /\ owner # current /\ arms < 3
/\ owner' = current /\ state' = "armed" /\ released' = FALSE
/\ arms' = arms+1 /\ UNCHANGED <<due,workers,current,closing>>
Next == Attach \/ Tick \/ Start \/ Finish \/ Stop \/ Join \/ Rearm \/ ReplaceHandle \/ AttachCurrent
Spec == Init /\ [][Next]_vars
OneOwner == workers <= 1
JoinedBeforeRelease == released => workers = 0
NoCatchupQueue == due \in BOOLEAN
CurrentHandleAtAdmission == workers > 0 => owner = current
=============================================================================
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS AllowOverlap = FALSE
ReleaseBeforeJoin = TRUE
AllowStaleRearm = FALSE
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
CHECK_DEADLOCK FALSE
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS AllowOverlap = TRUE
ReleaseBeforeJoin = FALSE
AllowStaleRearm = FALSE
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
CHECK_DEADLOCK FALSE
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS AllowOverlap = FALSE
ReleaseBeforeJoin = FALSE
AllowStaleRearm = FALSE
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
CHECK_DEADLOCK FALSE
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS AllowOverlap = FALSE
ReleaseBeforeJoin = FALSE
AllowStaleRearm = TRUE
INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission
CHECK_DEADLOCK FALSE
+47
View File
@@ -335,6 +335,53 @@ four negative controls separately remove retirement, the frame join, the
readiness guard or ACK progress restoration. This abstracts successful admitted
frames and does not prove physical-I/O, authority rollback or timing behavior.
## Attached-volume maintenance
`MaintenanceOwner.tla` now includes joined-stop re-arm on the same current
handle, and replacement followed by a new attachment. At most three arms and
two handles make the graph finite. Local review-fold run 2026-11-21 03:47 UTC,
TLC2.19 / Java21 /512MiB, jar SHA256
`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`:
```sh
java -Xmx512m -cp /path/to/tla2tools.jar tlc2.TLC -deadlock -config MaintenanceOwner_safe.cfg MaintenanceOwner
```
Positive exited0,105generated/54distinct, queue empty, depth12. Negative configs
`overlap` exited12 at OneOwner (20/14 depth6), `early_release` at
JoinedBeforeRelease (25/14 depth6), and `stale_rearm` at
CurrentHandleAtAdmission (50/33 depth8). Unique `-metadir` paths were used.
Native tests separately bind replica/epoch/endpoint and current handle/layer,
witness cancellation while held, and same-handle stop/join/re-arm. This finite
model does not establish physical-I/O cancellation or a fleet scheduling bound.
`ScopedMaintenanceGC.tla` extends S9's scope correspondence: three keys across
two volumes, one foreign-only root, independent local coverage and crash/config
invalidation. `ScopedMaintenanceGC_safe.cfg` checks foreign-root preservation,
local candidate scope and coverage ownership: 20 generated / 10 distinct states,
depth 9, with the same TLC/jar. Its three negative configs narrow
the root domain, widen reclamation or import namespace coverage. Native tests
exercise the persisted mark records and real catalog root traversal; the finite
model abstracts the complete mark and grace, whose timing remains in S9.
No 50/200-volume density or metadata-RPC qualification is claimed; automatic GC
remains opt-in, while periodic HEAD capture and retention are enabled by the CLI.
The unchanged S9 timing models were replayed with the same TLC/jar:
`cfg/S9_rule_G4.cfg` (`RetentionGCTiming`, D=2/G=4/MD=1/MaxT=10)
passed with 26,341 generated / 10,798 distinct states, depth 23;
`cfg/S9b_G3_MD1.cfg` (`RetentionGCMulti`, G=3/MD=1/MaxT=12)
passed with 11,303 / 5,743, depth 23.
`cfg/Maintenance_lifecycle.cfg` replays unchanged `ChunkLifecycleFixed` with
one snapshot caller/deleter, MaxHostOps=1 and MaxRuns=1, fork/delete/create,
lost replies/pending/sweep enabled. Safety invariants and HeadMonotone passed:
42,133,769 generated / 7,224,016 distinct states, depth 47 (TLC 2.19, same jar).
This config permits terminal stuttering (`CHECK_DEADLOCK FALSE`); it does not
prove deadlock freedom. The original `Fix_mix_small` replay stopped with a
terminal deadlock at depth 23 after 28,242,446 / 5,592,191 states (callers Done,
gc_loop); it is not reported as a completed green run. No protocol guards in
ChunkLifecycleFixed were changed.
`PrecopyFixedAdmission.tla` checks cost admission over five physical rounds.
A known estimate fits the 1.2-second allowance, or uses the five-second declared
freeze limit when it is at least 90% of the previous comparable known estimate or on the final
@@ -0,0 +1,25 @@
------------------------ MODULE ScopedMaintenanceGC ------------------------
EXTENDS Naturals, FiniteSets, TLC
CONSTANTS TraceForeign, LocalSweep, ImportGlobal
VARIABLES marks, localPasses, deleted, complete, early
vars == <<marks, localPasses, deleted, complete, early>>
Keys == {"rooted", "local", "foreign"}
Init == /\ marks = 0 /\ localPasses = 0 /\ deleted = {} /\ complete = FALSE /\ early = FALSE
\* A foreign-volume intent is the only root of the target's local key.
Roots == IF TraceForeign THEN {"rooted"} ELSE {}
Start == /\ ~complete /\ complete' = TRUE /\ UNCHANGED <<marks, localPasses, deleted, early>>
Finish == /\ complete /\ localPasses < 2
/\ LET coverage == IF ImportGlobal THEN 1 ELSE marks
scope == IF LocalSweep THEN {"rooted", "local"} ELSE Keys
IN /\ deleted' = deleted \cup (IF coverage = 1 THEN scope \ Roots ELSE {})
/\ early' = (early \/ (coverage = 1 /\ localPasses = 0))
/\ marks' = 1
/\ localPasses' = localPasses + 1 /\ complete' = FALSE
CrashOrConfigChange == /\ marks' = 0 /\ localPasses' = 0 /\ complete' = FALSE
/\ UNCHANGED <<deleted, early>>
Next == Start \/ Finish \/ CrashOrConfigChange
Spec == Init /\ [][Next]_vars
ForeignRootSurvives == "rooted" \notin deleted
OwnCoverageOnly == ~early
ForeignCandidatesUntouched == "foreign" \notin deleted
=============================================================================
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS TraceForeign = TRUE
LocalSweep = TRUE
ImportGlobal = TRUE
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
CHECK_DEADLOCK FALSE
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS TraceForeign = FALSE
LocalSweep = TRUE
ImportGlobal = FALSE
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
CHECK_DEADLOCK FALSE
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS TraceForeign = TRUE
LocalSweep = TRUE
ImportGlobal = FALSE
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
CHECK_DEADLOCK FALSE
@@ -0,0 +1,6 @@
SPECIFICATION Spec
CONSTANTS TraceForeign = TRUE
LocalSweep = FALSE
ImportGlobal = FALSE
INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly
CHECK_DEADLOCK FALSE
@@ -0,0 +1,20 @@
\* Maintenance safety replay: one snapshot caller/deleter, one host operation/run.
SPECIFICATION Spec
CONSTANTS
SnapCallers = {s1}
Deleters = {d1}
ForkOn = TRUE
DelSnapOn = TRUE
CreateOn = TRUE
MaxHostOps = 1
MaxRuns = 1
LostReply = TRUE
PendingOn = TRUE
SweepOn = TRUE
defaultInitValue = defaultInitValue
SYMMETRY Symm
INVARIANT TypeOK GCSafe SnapOnlyExplicitDelete AckedChunksSurvive CommitClean NoPublishAfterCommit NoIdReuse GiveBackReleases
PROPERTY HeadMonotone
\* Bounded terminal states may stutter; safety, not deadlock freedom.
CHECK_DEADLOCK FALSE