From 2928563c5a89ccc79d22a5dd97492a1b243d95b4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:15:23 -0800 Subject: [PATCH 1/6] feat(chunk): schedule periodic HEAD capture and scoped maintenance --- .../cmd/blockvolume/chunk_maintenance.go | 57 +++++ .../cmd/blockvolume/chunk_maintenance_test.go | 46 ++++ seaweed-block/cmd/blockvolume/chunk_remote.go | 46 ++-- .../cmd/blockvolume/chunk_remote_test.go | 24 ++- seaweed-block/cmd/blockvolume/main.go | 10 +- seaweed-block/cmd/sw-block/chunk.go | 21 +- seaweed-block/cmd/sw-block/chunk_gc.go | 2 +- .../cmd/sw-block/chunk_single_filer_test.go | 49 +++++ seaweed-block/core/frontend/chunkstore/gc.go | 7 +- .../core/frontend/chunkstore/gc_copy.go | 3 + .../core/frontend/chunkstore/gc_execution.go | 34 ++- .../frontend/chunkstore/gc_volume_test.go | 126 +++++++++++ .../durable/maintenance_policy_test.go | 26 +++ .../core/frontend/durable/provider.go | 13 ++ .../core/frontend/durable/provider_chunk.go | 122 ++++++++++- .../durable/provider_maintenance_test.go | 203 ++++++++++++++++++ .../core/storage/chunk_cut_progress_test.go | 59 +++++ .../docs/design/agent-workspace-design.md | 27 +++ seaweed-block/docs/design/invariants.md | 23 +- seaweed-block/docs/spec/MaintenanceOwner.tla | 22 ++ .../spec/MaintenanceOwner_early_release.cfg | 5 + .../docs/spec/MaintenanceOwner_overlap.cfg | 5 + .../docs/spec/MaintenanceOwner_safe.cfg | 5 + seaweed-block/docs/spec/README.md | 21 ++ .../docs/spec/ScopedMaintenanceGC.tla | 25 +++ .../ScopedMaintenanceGC_import_global.cfg | 6 + .../spec/ScopedMaintenanceGC_narrow_roots.cfg | 6 + .../docs/spec/ScopedMaintenanceGC_safe.cfg | 6 + .../spec/ScopedMaintenanceGC_wide_sweep.cfg | 6 + .../docs/spec/cfg/Maintenance_lifecycle.cfg | 20 ++ 30 files changed, 984 insertions(+), 41 deletions(-) create mode 100644 seaweed-block/cmd/blockvolume/chunk_maintenance.go create mode 100644 seaweed-block/cmd/blockvolume/chunk_maintenance_test.go create mode 100644 seaweed-block/cmd/sw-block/chunk_single_filer_test.go create mode 100644 seaweed-block/core/frontend/chunkstore/gc_volume_test.go create mode 100644 seaweed-block/core/frontend/durable/maintenance_policy_test.go create mode 100644 seaweed-block/core/frontend/durable/provider_maintenance_test.go create mode 100644 seaweed-block/docs/spec/MaintenanceOwner.tla create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_safe.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC.tla create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg create mode 100644 seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg create mode 100644 seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go new file mode 100644 index 0000000000..2ed13be995 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -0,0 +1,57 @@ +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" +) + +// 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 +} diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go new file mode 100644 index 0000000000..8492464e70 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go @@ -0,0 +1,46 @@ +package main + +import ( + "context" + "errors" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "path" + "testing" +) + +func TestMaintenanceRetentionFailureNeverStartsGC(t *testing.T) { + f := chunkstore.NewMemFiler() + cat, err := chunkstore.NewCatalog(f, defaultChunkPath) + if err != nil { + t.Fatal(err) + } + pass, closeFn, err := newChunkMaintenance(cat, nil, true, "unused-master:1234") + if err != nil { + t.Fatal(err) + } + defer closeFn() + if err = pass(context.Background(), "missing-volume"); err == nil { + t.Fatal("missing retention volume accepted") + } + if _, err = f.LookupEntry(context.Background(), path.Join(defaultChunkPath, "missing-volume"), "_GC_MARK"); !errors.Is(err, chunkstore.ErrNotFound) { + t.Fatalf("failed retention entered GC: %v", 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) + } +} diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index ad55735dc9..7bc5d5eb20 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -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 } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 5bf1bfcdfb..c885307e7c 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -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", diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index de5e5739cf..9a9775ec84 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -202,7 +202,9 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.collection, "chunk-collection", "", "walstore-chunk: collection for chunk needles (empty = filer default / storage rule)") fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") 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 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)") @@ -657,8 +659,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 diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index ec9ac529ab..127b3e0590 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -42,6 +42,25 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { return c, c.Close, nil } +// Direct mutation commands use the same topology admission as blockvolume. +// Production SWFS implements this probe; metadata-only test filers may omit it. +func checkedChunkFiler(addr string) (chunkstore.Filer, func() error, error) { + f, closeFn, err := dialChunkFiler(addr) + if err != nil { + return nil, nil, err + } + if check, ok := f.(interface{ CheckSingleFiler(context.Context) error }); ok { + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + err = check.CheckSingleFiler(ctx) + cancel() + if err != nil { + _ = closeFn() + return nil, nil, err + } + } + return f, closeFn, nil +} + func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) @@ -247,7 +266,7 @@ func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunksto if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } - f, closeFn, err := dialChunkFiler(filer) + f, closeFn, err := checkedChunkFiler(filer) if err != nil { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..4efc9b4de8 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -36,7 +36,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { if fs.NArg() != 0 || filer == "" || master == "" || timeout <= 0 || ttl <= 0 || grace <= chunkstore.DefaultOpDeadline { return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false) } - f, closeFn, e := dialChunkFiler(filer) + f, closeFn, e := checkedChunkFiler(filer) if e != nil { return chunkResult("gc", nil, e, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/chunk_single_filer_test.go b/seaweed-block/cmd/sw-block/chunk_single_filer_test.go new file mode 100644 index 0000000000..51fd090628 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_single_filer_test.go @@ -0,0 +1,49 @@ +package main + +import ( + "bytes" + "context" + "errors" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +type cliFilerCheck struct { + chunkstore.Filer + checks, closes int +} + +func (f *cliFilerCheck) CheckSingleFiler(context.Context) error { + f.checks++ + return errors.New("different metadata point") +} +func TestChunkCatalogRefusesMultipleFilersBeforeMutation(t *testing.T) { + f := &cliFilerCheck{Filer: chunkstore.NewMemFiler()} + old := dialChunkFiler + t.Cleanup(func() { dialChunkFiler = old }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return f, func() error { f.closes++; return nil }, nil + } + var out, stderr bytes.Buffer + cat, closeFn, exit := chunkCatalog("fork", "filer", defaultChunkPathCLI, &out, &stderr) + if closeFn != nil { + _ = closeFn() + } + if cat != nil || exit < 0 || f.checks != 1 || f.closes != 1 { + t.Fatalf("unchecked CLI catalog: cat=%v exit=%d checks=%d closes=%d", cat, exit, f.checks, f.closes) + } +} + +func TestChunkGCRefusesMultipleFilersBeforeEffects(t *testing.T) { + f := &cliFilerCheck{Filer: chunkstore.NewMemFiler()} + old := dialChunkFiler + t.Cleanup(func() { dialChunkFiler = old }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { + return f, func() error { f.closes++; return nil }, nil + } + code, _, _ := runChunk("gc", "--chunk-filer=filer", "--master=master", "--apply") + if code == 0 || f.checks != 1 || f.closes != 1 { + t.Fatalf("GC skipped topology admission: code=%d checks=%d closes=%d", code, f.checks, f.closes) + } +} diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 7e8bf522f5..9277ecbe50 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -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) diff --git a/seaweed-block/core/frontend/chunkstore/gc_copy.go b/seaweed-block/core/frontend/chunkstore/gc_copy.go index 2da07b132e..87abeaa67b 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_copy.go +++ b/seaweed-block/core/frontend/chunkstore/gc_copy.go @@ -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 diff --git a/seaweed-block/core/frontend/chunkstore/gc_execution.go b/seaweed-block/core/frontend/chunkstore/gc_execution.go index 5d4b5ab560..43bb5cf7e9 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_execution.go +++ b/seaweed-block/core/frontend/chunkstore/gc_execution.go @@ -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) diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go new file mode 100644 index 0000000000..dcdf04e124 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -0,0 +1,126 @@ +package chunkstore + +import ( + "context" + "errors" + "path" + "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) + } + }) + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_policy_test.go b/seaweed-block/core/frontend/durable/maintenance_policy_test.go new file mode 100644 index 0000000000..531477d495 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_policy_test.go @@ -0,0 +1,26 @@ +package durable + +import ( + "fmt" + "testing" + "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)) + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 5aa210bce9..f977e6b75f 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -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 @@ -332,6 +339,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 } diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 415d804e56..c255a2819e 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -320,12 +320,12 @@ 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) + go p.chunkBackground(loopCtx, cancel, volumeID, layer, h.chunkDone) } func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { @@ -760,7 +760,9 @@ func (p *DurableProvider) chunkLoop(ctx context.Context, volumeID string, layer if !ok { continue } - _, err := layer.Cut(ctx) + cutCtx, cancel := p.chunkCutContext(ctx) + _, err := layer.Cut(cutCtx) + 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) @@ -768,15 +770,113 @@ 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{}) { + 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) }() + } + timer := time.NewTicker(chunkSchedulePoll) + defer timer.Stop() + for ctx.Err() == nil { + select { + case <-ctx.Done(): + case <-timer.C: + if layer.Fenced() { + cancel() + } + } + } + workers.Wait() +} + +func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer) { + 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 !chunkAuthority(p.view.Projection(), volumeID) { + timer.Reset(interval) + continue + } + 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() || !chunkAuthority(p.view.Projection(), volumeID) { + 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) { @@ -810,6 +910,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 @@ -820,6 +922,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 @@ -842,7 +946,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 diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go new file mode 100644 index 0000000000..44fe266f33 --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -0,0 +1,203 @@ +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) + go func() { _, err := s.Write(1, block(0x51)); writeDone <- err }() + 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) + go func() { closed <- p.Close() }() + 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) + 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(); entered <- ctx.Err(); return ctx.Err() }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + select { + case err := <-entered: + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("maintenance had no deadline") + } +} + +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() +} diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index a5d79f6fbf..274cccbef2 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -121,3 +121,62 @@ 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 { + *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++ + } + return err +} +func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { + _, f, l, _ := 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 + 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) + } + } + // Five changed chunks, five successful puts, no retransmission after expiry. + if previous != 4 { + t.Fatalf("reusable chunks=%d", previous) + } + assertNoIntentsLeft(t, f) +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index d4d621ecd1..067c1bc5fe 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -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`). diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cdd34e146d..cd984571ea 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -249,6 +249,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). @@ -336,9 +341,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 -117 rows: 98 ACTIVE, 19 STUB; 15 kept from the internal ledger, 102 new. +120 rows: 103 ACTIVE, 17 STUB; 15 kept from the internal ledger, 105 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. @@ -508,10 +523,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` | One attached volume admits at most one maintenance pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenancePassHasOneDeadline` | `MaintenanceOwner` `OneOwner` | 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` | `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` | `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass` | `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 | @@ -519,7 +537,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 diff --git a/seaweed-block/docs/spec/MaintenanceOwner.tla b/seaweed-block/docs/spec/MaintenanceOwner.tla new file mode 100644 index 0000000000..faec719597 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner.tla @@ -0,0 +1,22 @@ +------------------------- MODULE MaintenanceOwner ------------------------- +EXTENDS Naturals, TLC +CONSTANT AllowOverlap, ReleaseBeforeJoin +VARIABLES state, due, workers, released +vars == <> +Init == /\ state = "pending" /\ due = FALSE /\ workers = 0 /\ released = FALSE +Attach == /\ state = "pending" /\ state' = "armed" /\ UNCHANGED <> +Tick == /\ state = "armed" /\ due' = TRUE /\ UNCHANGED <> +Start == /\ state = "armed" /\ due /\ (workers = 0 \/ AllowOverlap) + /\ workers < 2 /\ workers' = workers + 1 /\ due' = FALSE + /\ UNCHANGED <> +Finish == /\ workers > 0 /\ workers' = workers - 1 /\ UNCHANGED <> +Stop == /\ state = "armed" /\ state' = "draining" /\ due' = FALSE + /\ UNCHANGED <> +Join == /\ state = "draining" /\ (workers = 0 \/ ReleaseBeforeJoin) + /\ state' = "closed" /\ released' = TRUE /\ UNCHANGED <> +Next == Attach \/ Tick \/ Start \/ Finish \/ Stop \/ Join +Spec == Init /\ [][Next]_vars +OneOwner == workers <= 1 +JoinedBeforeRelease == released => workers = 0 +NoCatchupQueue == due \in BOOLEAN +============================================================================= diff --git a/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg new file mode 100644 index 0000000000..eaa2d59505 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = TRUE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg new file mode 100644 index 0000000000..55fd95e332 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = TRUE + ReleaseBeforeJoin = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg new file mode 100644 index 0000000000..08aadb34d3 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 7b0862480e..c56185d257 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -334,3 +334,24 @@ one missing-probe/newer-ACK schedule. `R293_review_safe` checks four invariants; 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` models a single attached maintenance owner, coalesced due +work and joined release. `MaintenanceOwner_safe.cfg` completed with TLC 2.19 +(tla2tools v1.7.4, SHA256 +`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`), +15 generated / 8 distinct states, depth 5. The overlap and early-release configs +both failed their intended invariant (`OneOwner` / `JoinedBeforeRelease`). +This 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. diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC.tla b/seaweed-block/docs/spec/ScopedMaintenanceGC.tla new file mode 100644 index 0000000000..e04fda664f --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC.tla @@ -0,0 +1,25 @@ +------------------------ MODULE ScopedMaintenanceGC ------------------------ +EXTENDS Naturals, FiniteSets, TLC +CONSTANTS TraceForeign, LocalSweep, ImportGlobal +VARIABLES marks, localPasses, deleted, complete, early +vars == <> +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 <> +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 <> +Next == Start \/ Finish \/ CrashOrConfigChange +Spec == Init /\ [][Next]_vars +ForeignRootSurvives == "rooted" \notin deleted +OwnCoverageOnly == ~early +ForeignCandidatesUntouched == "foreign" \notin deleted +============================================================================= diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg new file mode 100644 index 0000000000..25bf2c2d66 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_import_global.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = TRUE + ImportGlobal = TRUE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg new file mode 100644 index 0000000000..80c34ce5a2 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_narrow_roots.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = FALSE + LocalSweep = TRUE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg new file mode 100644 index 0000000000..b428924006 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_safe.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = TRUE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg b/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg new file mode 100644 index 0000000000..49e7263fa9 --- /dev/null +++ b/seaweed-block/docs/spec/ScopedMaintenanceGC_wide_sweep.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS TraceForeign = TRUE + LocalSweep = FALSE + ImportGlobal = FALSE +INVARIANTS ForeignRootSurvives ForeignCandidatesUntouched OwnCoverageOnly +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg new file mode 100644 index 0000000000..48e1307254 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg @@ -0,0 +1,20 @@ +\* Fix_mix_small: model-checks ChunkLifecycleFixed.tla (run from docs/spec: ./run.sh Fix_mix_small) +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 From 3deba727977a53abae794256c9134cdeb18674c5 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:20:00 -0800 Subject: [PATCH 2/6] test(chunk): witness periodic no-op and foreign-fork protection --- .../frontend/chunkstore/gc_volume_test.go | 33 +++++++++ .../core/frontend/durable/provider_chunk.go | 2 +- .../durable/provider_maintenance_test.go | 74 ++++++++++++++++++- .../docs/design/agent-workspace-design.md | 4 +- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/README.md | 16 ++++ .../docs/spec/cfg/Maintenance_lifecycle.cfg | 2 +- 7 files changed, 126 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go index dcdf04e124..4ebfb7b26b 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -124,3 +124,36 @@ func TestVolumeGC_IncompletePassAndConfigChangeDiscardCoverage(t *testing.T) { }) } } + +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) + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index c255a2819e..85d8ff0539 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -635,7 +635,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; diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go index 44fe266f33..bbfe1549f4 100644 --- a/seaweed-block/core/frontend/durable/provider_maintenance_test.go +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -41,7 +41,17 @@ func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { t.Fatal("maintenance did not start with cut timer off") } writeDone := make(chan error, 1) - go func() { _, err := s.Write(1, block(0x51)); writeDone <- err }() + 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 { @@ -51,7 +61,16 @@ func TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock(t *testing.T) { t.Fatal("maintenance held a guest lock") } closed := make(chan error, 1) - go func() { closed <- p.Close() }() + 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): @@ -201,3 +220,54 @@ func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { } 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) + } +} diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 067c1bc5fe..4ebac8c31b 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -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 diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index cd984571ea..887e77817e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -523,7 +523,7 @@ 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` | One attached volume admits at most one maintenance pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenancePassHasOneDeadline` | `MaintenanceOwner` `OneOwner` | ACTIVE | +| `INV-MAINT-ONE-OWNER` | One attached volume admits at most one maintenance pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline` | `MaintenanceOwner` `OneOwner` | 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` | `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` | `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass` | `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 | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index c56185d257..76f2d07037 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -355,3 +355,19 @@ 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. diff --git a/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg index 48e1307254..c257d3d0a0 100644 --- a/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg +++ b/seaweed-block/docs/spec/cfg/Maintenance_lifecycle.cfg @@ -1,4 +1,4 @@ -\* Fix_mix_small: model-checks ChunkLifecycleFixed.tla (run from docs/spec: ./run.sh Fix_mix_small) +\* Maintenance safety replay: one snapshot caller/deleter, one host operation/run. SPECIFICATION Spec CONSTANTS SnapCallers = {s1} From e04b2cf28ec5b3db9ee381c69197b8dadca3f228 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:25:19 -0800 Subject: [PATCH 3/6] test(chunk): witness every scheduler stopper joining its worker --- .../durable/maintenance_policy_test.go | 34 +++++++++++++++++++ seaweed-block/docs/design/invariants.md | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/frontend/durable/maintenance_policy_test.go b/seaweed-block/core/frontend/durable/maintenance_policy_test.go index 531477d495..734e5b89e6 100644 --- a/seaweed-block/core/frontend/durable/maintenance_policy_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_policy_test.go @@ -1,8 +1,11 @@ package durable import ( + "context" "fmt" + "sync" "testing" + "testing/synctest" "time" ) @@ -24,3 +27,34 @@ func TestMaintenanceVolumePhasesDoNotAlign(t *testing.T) { 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 + }) +} diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 887e77817e..d78b2040dc 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -525,7 +525,7 @@ Notes: | `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` | One attached volume admits at most one maintenance pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline` | `MaintenanceOwner` `OneOwner` | 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` | `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` | `TestMaintenanceCloseCancelsAndJoinsWithoutGuestLock`, `TestMaintenanceAuthorityLossCancelsHeldPass` | `MaintenanceOwner` `JoinedBeforeRelease` | 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` | `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 | From 96713212955a65fed77e961f21fbcb3bd296da2e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 17:39:47 -0800 Subject: [PATCH 4/6] fix(maintenance): leave shared CLI admission to verification --- .../cmd/blockvolume/chunk_maintenance.go | 2 + seaweed-block/cmd/blockvolume/main.go | 2 +- seaweed-block/cmd/sw-block/chunk.go | 21 +------- seaweed-block/cmd/sw-block/chunk_gc.go | 2 +- .../cmd/sw-block/chunk_single_filer_test.go | 49 ------------------- 5 files changed, 5 insertions(+), 71 deletions(-) delete mode 100644 seaweed-block/cmd/sw-block/chunk_single_filer_test.go diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance.go b/seaweed-block/cmd/blockvolume/chunk_maintenance.go index 2ed13be995..023a76c2f8 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance.go @@ -12,6 +12,8 @@ import ( "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. diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 9a9775ec84..b2afde162d 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -204,7 +204,7 @@ func parseFlags(args []string) (flags, error) { 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: 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 density qualification") + 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)") diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 127b3e0590..ec9ac529ab 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -42,25 +42,6 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { return c, c.Close, nil } -// Direct mutation commands use the same topology admission as blockvolume. -// Production SWFS implements this probe; metadata-only test filers may omit it. -func checkedChunkFiler(addr string) (chunkstore.Filer, func() error, error) { - f, closeFn, err := dialChunkFiler(addr) - if err != nil { - return nil, nil, err - } - if check, ok := f.(interface{ CheckSingleFiler(context.Context) error }); ok { - ctx, cancel := context.WithTimeout(context.Background(), time.Minute) - err = check.CheckSingleFiler(ctx) - cancel() - if err != nil { - _ = closeFn() - return nil, nil, err - } - } - return f, closeFn, nil -} - func runOpsChunk(args []string, stdout, stderr io.Writer) int { if len(args) == 0 { return chunkFail("", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "expected cut|snapshot|snapshots|snapshot-delete|fork|detach|show|gc|usage|retain|volume-delete", false) @@ -266,7 +247,7 @@ func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunksto if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } - f, closeFn, err := checkedChunkFiler(filer) + f, closeFn, err := dialChunkFiler(filer) if err != nil { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index 4efc9b4de8..a5a8cdfc61 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -36,7 +36,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { if fs.NArg() != 0 || filer == "" || master == "" || timeout <= 0 || ttl <= 0 || grace <= chunkstore.DefaultOpDeadline { return chunkFail("gc", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer and --master are required; durations must be positive and grace must exceed the operation deadline", false) } - f, closeFn, e := checkedChunkFiler(filer) + f, closeFn, e := dialChunkFiler(filer) if e != nil { return chunkResult("gc", nil, e, stdout, stderr) } diff --git a/seaweed-block/cmd/sw-block/chunk_single_filer_test.go b/seaweed-block/cmd/sw-block/chunk_single_filer_test.go deleted file mode 100644 index 51fd090628..0000000000 --- a/seaweed-block/cmd/sw-block/chunk_single_filer_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package main - -import ( - "bytes" - "context" - "errors" - "testing" - - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" -) - -type cliFilerCheck struct { - chunkstore.Filer - checks, closes int -} - -func (f *cliFilerCheck) CheckSingleFiler(context.Context) error { - f.checks++ - return errors.New("different metadata point") -} -func TestChunkCatalogRefusesMultipleFilersBeforeMutation(t *testing.T) { - f := &cliFilerCheck{Filer: chunkstore.NewMemFiler()} - old := dialChunkFiler - t.Cleanup(func() { dialChunkFiler = old }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { - return f, func() error { f.closes++; return nil }, nil - } - var out, stderr bytes.Buffer - cat, closeFn, exit := chunkCatalog("fork", "filer", defaultChunkPathCLI, &out, &stderr) - if closeFn != nil { - _ = closeFn() - } - if cat != nil || exit < 0 || f.checks != 1 || f.closes != 1 { - t.Fatalf("unchecked CLI catalog: cat=%v exit=%d checks=%d closes=%d", cat, exit, f.checks, f.closes) - } -} - -func TestChunkGCRefusesMultipleFilersBeforeEffects(t *testing.T) { - f := &cliFilerCheck{Filer: chunkstore.NewMemFiler()} - old := dialChunkFiler - t.Cleanup(func() { dialChunkFiler = old }) - dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { - return f, func() error { f.closes++; return nil }, nil - } - code, _, _ := runChunk("gc", "--chunk-filer=filer", "--master=master", "--apply") - if code == 0 || f.checks != 1 || f.closes != 1 { - t.Fatalf("GC skipped topology admission: code=%d checks=%d closes=%d", code, f.checks, f.closes) - } -} From 947a1869706c06ba3c40f6c7e09e4b8f56d036ff Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 19:48:40 -0800 Subject: [PATCH 5/6] fix: bind maintenance to attached lineage and close review controls --- .../cmd/blockvolume/chunk_maintenance_test.go | 98 ++++++++++++++++--- .../frontend/chunkstore/gc_volume_test.go | 80 +++++++++++++++ .../durable/maintenance_lineage_test.go | 74 ++++++++++++++ .../core/frontend/durable/provider.go | 7 +- .../core/frontend/durable/provider_chunk.go | 33 +++++-- .../durable/provider_maintenance_test.go | 95 +++++++++++++++++- .../core/storage/chunk_cut_progress_test.go | 21 +++- seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/spec/MaintenanceOwner.tla | 37 ++++--- .../spec/MaintenanceOwner_early_release.cfg | 3 +- .../docs/spec/MaintenanceOwner_overlap.cfg | 3 +- .../docs/spec/MaintenanceOwner_safe.cfg | 3 +- .../spec/MaintenanceOwner_stale_rearm.cfg | 6 ++ seaweed-block/docs/spec/README.md | 24 +++-- 14 files changed, 434 insertions(+), 56 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/maintenance_lineage_test.go create mode 100644 seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg diff --git a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go index 8492464e70..e086b1846e 100644 --- a/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_maintenance_test.go @@ -4,28 +4,96 @@ 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) { - f := chunkstore.NewMemFiler() - cat, err := chunkstore.NewCatalog(f, defaultChunkPath) - if err != nil { - t.Fatal(err) - } - pass, closeFn, err := newChunkMaintenance(cat, nil, true, "unused-master:1234") - if err != nil { - t.Fatal(err) - } - defer closeFn() - if err = pass(context.Background(), "missing-volume"); err == nil { - t.Fatal("missing retention volume accepted") - } - if _, err = f.LookupEntry(context.Background(), path.Join(defaultChunkPath, "missing-volume"), "_GC_MARK"); !errors.Is(err, chunkstore.ErrNotFound) { - t.Fatalf("failed retention entered GC: %v", err) + 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) diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go index 4ebfb7b26b..f45bd190a4 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "path" + "reflect" "testing" "time" @@ -157,3 +158,82 @@ func TestVolumeGC_ForeignForkHeadIsSoleRoot(t *testing.T) { } } } + +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) + } +} diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go new file mode 100644 index 0000000000..ce1850e846 --- /dev/null +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -0,0 +1,74 @@ +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() }}} + t.Cleanup(func() { p.stopChunkLoop(h) }) + 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{}) + go func() { p.stopChunkLoop(h); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("stopped owner did not join") + } + } +} diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index f977e6b75f..1c62b94edc 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -269,9 +269,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 diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 6ea57ba92e..3fa18e19a4 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -325,7 +325,9 @@ func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer st } loopCtx, cancel := context.WithCancel(context.Background()) h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - go p.chunkBackground(loopCtx, cancel, 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 @@ -773,7 +779,7 @@ 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{}) { +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 @@ -787,7 +793,7 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca } if p.cfg.ChunkMaintenanceInterval > 0 && p.cfg.ChunkMaintenance != nil { workers.Add(1) - go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer) }() + go func() { defer workers.Done(); p.chunkMaintenanceLoop(ctx, volumeID, layer, current) }() } timer := time.NewTicker(chunkSchedulePoll) defer timer.Stop() @@ -803,7 +809,17 @@ func (p *DurableProvider) chunkBackground(ctx context.Context, cancel context.Ca workers.Wait() } -func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID string, layer storage.ChunkLayer) { +// 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 { @@ -820,9 +836,8 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str if ctx.Err() != nil || layer.Fenced() { return } - if !chunkAuthority(p.view.Projection(), volumeID) { - timer.Reset(interval) - continue + if !current() { + return } timeout := p.cfg.ChunkMaintenanceTimeout if timeout <= 0 { @@ -841,7 +856,7 @@ func (p *DurableProvider) chunkMaintenanceLoop(ctx context.Context, volumeID str case <-passCtx.Done(): return case <-tick.C: - if layer.Fenced() || !chunkAuthority(p.view.Projection(), volumeID) { + if layer.Fenced() || !current() { cancel() return } diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go index bbfe1549f4..68f60a64c6 100644 --- a/seaweed-block/core/frontend/durable/provider_maintenance_test.go +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -126,24 +126,57 @@ func TestMaintenanceAuthorityLossCancelsHeldPass(t *testing.T) { 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(); entered <- ctx.Err(); return ctx.Err() }, + 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() { _ = p.Close() }) + 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) } - case <-time.After(5 * time.Second): - t.Fatal("maintenance had no deadline") + default: + t.Fatal("no deadline observation") } } @@ -271,3 +304,57 @@ func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { 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") + } + }) + } +} diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index 274cccbef2..92240fff16 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -125,6 +125,7 @@ func TestChunkStageV3_FourTimesCapConvergesUnderSteadyWrites(t *testing.T) { // 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 @@ -139,11 +140,18 @@ func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) 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) { - _, f, l, _ := precopyLayer(t, 1, 5) + _, f, l, w := precopyLayer(t, 1, 5) l.cfg.COWSpillLimit = ctChunkBytes l.cfg.UploadConcurrency = 1 r := &deadlineProgressRemote{fakeChunkRemote: f} @@ -175,6 +183,17 @@ func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { } } // 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 previous != 4 { t.Fatalf("reusable chunks=%d", previous) } diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 306d2d7caf..7032a0c94e 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -527,9 +527,9 @@ 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` | One attached volume admits at most one maintenance pass; elapsed ticks coalesce and never enqueue catch-up work. | M8 Armed → Running | `provider_chunk.go` `chunkMaintenanceLoop` | `TestMaintenanceCoalescesWhileOnePassIsHeld`, `TestMaintenancePassHasOneDeadline` | `MaintenanceOwner` `OneOwner` | 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` | `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` | `MaintenanceOwner` `JoinedBeforeRelease` | 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 | diff --git a/seaweed-block/docs/spec/MaintenanceOwner.tla b/seaweed-block/docs/spec/MaintenanceOwner.tla index faec719597..b389264468 100644 --- a/seaweed-block/docs/spec/MaintenanceOwner.tla +++ b/seaweed-block/docs/spec/MaintenanceOwner.tla @@ -1,22 +1,37 @@ ------------------------- MODULE MaintenanceOwner ------------------------- EXTENDS Naturals, TLC -CONSTANT AllowOverlap, ReleaseBeforeJoin -VARIABLES state, due, workers, released -vars == <> +CONSTANT AllowOverlap, ReleaseBeforeJoin, AllowStaleRearm +VARIABLES state, due, workers, released, owner, current, arms, closing +vars == <> Init == /\ state = "pending" /\ due = FALSE /\ workers = 0 /\ released = FALSE -Attach == /\ state = "pending" /\ state' = "armed" /\ UNCHANGED <> -Tick == /\ state = "armed" /\ due' = TRUE /\ UNCHANGED <> + /\ owner = 1 /\ current = 1 /\ arms = 0 /\ closing = FALSE +Attach == /\ state = "pending" /\ state' = "armed" /\ arms' = arms+1 + /\ UNCHANGED <> +Tick == /\ state = "armed" /\ due' = TRUE + /\ UNCHANGED <> Start == /\ state = "armed" /\ due /\ (workers = 0 \/ AllowOverlap) - /\ workers < 2 /\ workers' = workers + 1 /\ due' = FALSE - /\ UNCHANGED <> -Finish == /\ workers > 0 /\ workers' = workers - 1 /\ UNCHANGED <> + /\ workers < 2 /\ workers' = workers+1 /\ due' = FALSE + /\ UNCHANGED <> +Finish == /\ workers > 0 /\ workers' = workers-1 + /\ UNCHANGED <> Stop == /\ state = "armed" /\ state' = "draining" /\ due' = FALSE - /\ UNCHANGED <> + /\ closing' \in BOOLEAN /\ UNCHANGED <> Join == /\ state = "draining" /\ (workers = 0 \/ ReleaseBeforeJoin) - /\ state' = "closed" /\ released' = TRUE /\ UNCHANGED <> -Next == Attach \/ Tick \/ Start \/ Finish \/ Stop \/ Join + /\ state' = IF closing THEN "closed" ELSE "idle" + /\ released' = TRUE /\ UNCHANGED <> +Rearm == /\ state = "idle" /\ arms < 3 /\ (owner = current \/ AllowStaleRearm) + /\ state' = "armed" /\ released' = FALSE /\ arms' = arms+1 + /\ UNCHANGED <> +ReplaceHandle == /\ state = "idle" /\ workers = 0 /\ current = 1 + /\ current' = 2 + /\ UNCHANGED <> +AttachCurrent == /\ state = "idle" /\ workers = 0 /\ owner # current /\ arms < 3 + /\ owner' = current /\ state' = "armed" /\ released' = FALSE + /\ arms' = arms+1 /\ UNCHANGED <> +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 ============================================================================= diff --git a/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg index eaa2d59505..a9eb05e357 100644 --- a/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg +++ b/seaweed-block/docs/spec/MaintenanceOwner_early_release.cfg @@ -1,5 +1,6 @@ SPECIFICATION Spec CONSTANTS AllowOverlap = FALSE ReleaseBeforeJoin = TRUE -INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg index 55fd95e332..6984971b3a 100644 --- a/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg +++ b/seaweed-block/docs/spec/MaintenanceOwner_overlap.cfg @@ -1,5 +1,6 @@ SPECIFICATION Spec CONSTANTS AllowOverlap = TRUE ReleaseBeforeJoin = FALSE -INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg index 08aadb34d3..deb0ac7c68 100644 --- a/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg +++ b/seaweed-block/docs/spec/MaintenanceOwner_safe.cfg @@ -1,5 +1,6 @@ SPECIFICATION Spec CONSTANTS AllowOverlap = FALSE ReleaseBeforeJoin = FALSE -INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue + AllowStaleRearm = FALSE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg b/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg new file mode 100644 index 0000000000..46925d6f86 --- /dev/null +++ b/seaweed-block/docs/spec/MaintenanceOwner_stale_rearm.cfg @@ -0,0 +1,6 @@ +SPECIFICATION Spec +CONSTANTS AllowOverlap = FALSE + ReleaseBeforeJoin = FALSE + AllowStaleRearm = TRUE +INVARIANTS OneOwner JoinedBeforeRelease NoCatchupQueue CurrentHandleAtAdmission +CHECK_DEADLOCK FALSE diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 79e130bfb9..19dc7986d7 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -337,13 +337,23 @@ frames and does not prove physical-I/O, authority rollback or timing behavior. ## Attached-volume maintenance -`MaintenanceOwner.tla` models a single attached maintenance owner, coalesced due -work and joined release. `MaintenanceOwner_safe.cfg` completed with TLC 2.19 -(tla2tools v1.7.4, SHA256 -`936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`), -15 generated / 8 distinct states, depth 5. The overlap and early-release configs -both failed their intended invariant (`OneOwner` / `JoinedBeforeRelease`). -This does not establish physical-I/O cancellation or a fleet scheduling bound. +`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 From 899ef867b0ff04bf3d7b2a396a9210bdb2f0f44c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 20:01:53 -0800 Subject: [PATCH 6/6] test: require complete final image and bounded maintenance cleanup --- .../durable/maintenance_lineage_test.go | 20 ++++++++++++++++++- .../core/storage/chunk_cut_progress_test.go | 11 +++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go index ce1850e846..d6020247f2 100644 --- a/seaweed-block/core/frontend/durable/maintenance_lineage_test.go +++ b/seaweed-block/core/frontend/durable/maintenance_lineage_test.go @@ -53,7 +53,24 @@ func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) { 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() }}} - t.Cleanup(func() { p.stopChunkLoop(h) }) + 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) @@ -64,6 +81,7 @@ func TestMaintenanceSameHandleRearmsAfterJoinedStop(t *testing.T) { t.Fatal("same handle did not arm") } done := make(chan struct{}) + stopperDone = done go func() { p.stopChunkLoop(h); close(done) }() select { case <-done: diff --git a/seaweed-block/core/storage/chunk_cut_progress_test.go b/seaweed-block/core/storage/chunk_cut_progress_test.go index 92240fff16..34b469a152 100644 --- a/seaweed-block/core/storage/chunk_cut_progress_test.go +++ b/seaweed-block/core/storage/chunk_cut_progress_test.go @@ -151,13 +151,16 @@ func (r *deadlineProgressRemote) Put(ctx context.Context, key string, b []byte) return err } func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { - _, f, l, w := precopyLayer(t, 1, 5) + 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 @@ -180,6 +183,8 @@ func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { 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. @@ -194,6 +199,10 @@ func TestChunkStageV3_MultipleDeadlinesKeepProgress(t *testing.T) { 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) }