From acc1258015fcf86ef552cc317d8e3233b5107366 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 22:56:53 -0800 Subject: [PATCH 01/25] chunkstore: snapshot delete in any order with forks (remove fork claims) A fork or restore no longer claims its parent snapshot, and neither DeleteSnapshot nor retention reads a claim: a deadline-exceeded fork or a failed restore can no longer make its parent (and so its volume) undeletable. Safety now rests on time: a fork takes its deadline start before it reads the parent, every attempt (a retry included) reads it again, and it publishes its HEAD only before start + operation deadline; GC keeps a deleted attempt rooted for its grace, and NewCollector now requires grace >= operation deadline + clock skew + CAS apply bound (new GCConfig field, default: the operation deadline). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. Removed: claimForkParent/dropForkClaim/removeForkClaim (replaced by readForkParent), the claim branch of markDeleting, liveClaims, claimedErr and snapshot_claimed, retention's ForkHeld outcome and the fork_parent keep (forkParentsNeeded). A claims xattr written by an older version is ignored. Tests: three new tests (fork retry after delete re-reads the parent; delete during a fork in flight; unknown publish keeps the keys while its intent exists), each red on the base with snapshot_claimed; the construction check with its boundary; claim-mechanics tests removed, the others rewritten to the new rule. Docs: invariants.md M6 rows, INV-SNAP-DELETE-ANY-ORDER-001 (new), INV-SNAP-EXPLICIT-DELETE-001 and INV-GC-GRACE-DEADLINE-001 restated, INV-RESTORE-PARENT-HOLD-001 archived; workspace design section 6. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk_gc.go | 2 +- .../core/frontend/chunkstore/catalog.go | 134 ++-------- .../chunkstore/catalog_settle_test.go | 19 +- seaweed-block/core/frontend/chunkstore/gc.go | 32 ++- .../frontend/chunkstore/gc_volume_test.go | 22 +- .../core/frontend/chunkstore/restore_test.go | 45 ---- .../core/frontend/chunkstore/retention.go | 241 +++--------------- .../chunkstore/retention_integration_test.go | 23 +- .../chunkstore/retention_review_test.go | 228 +---------------- .../frontend/chunkstore/retention_test.go | 60 +---- .../chunkstore/snapshot_delete_test.go | 158 ++++++++++++ .../volume_delete_integration_test.go | 2 +- .../frontend/chunkstore/volume_delete_test.go | 13 +- .../host/volume/chunk_control_class_test.go | 3 - .../docs/design/agent-workspace-design.md | 13 +- seaweed-block/docs/design/invariants.md | 15 +- 16 files changed, 302 insertions(+), 708 deletions(-) create mode 100644 seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..a1bf496f26 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -27,7 +27,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "chunk catalog namespace") fs.StringVar(&master, "master", "", "authoritative blockmaster gRPC address") fs.BoolVar(&apply, "apply", false, "settle intents, save completed marks and reclaim eligible chunks; default is read-only") - fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (must exceed the operation deadline plus mark time)") + fs.DurationVar(&grace, "grace", time.Hour, "two-mark interval and minimum upload age (at least the operation deadline + clock skew + CAS apply bound, and more than the operation deadline plus mark time)") fs.DurationVar(&ttl, "intent-ttl", time.Hour, "minimum capture-intent age before authoritative epoch expiry") fs.DurationVar(&timeout, "timeout", time.Minute, "bound for this pass, including master/filer/blob calls") if e := fs.Parse(args); e != nil { diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 2fff8ee9ef..dcd18a41c2 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -36,7 +36,6 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/geometry" - "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" @@ -1126,16 +1125,12 @@ func (c *Catalog) DeleteSnapshot(ctx context.Context, vol, name string) (string, } continue // re-read: the path now holds a tombstone or the late snapshot case ref.info.State == SnapActive: - // The one mark path shared with retention: a live fork claim - // refuses. - m, live, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) + // The one mark path shared with retention; forks do not hold it. + m, _, err := c.markDeleting(ctx, vol, name, ref.rec.Attempt) if err != nil { return "", err } - switch m { - case markClaimed: - return "", claimedErr(vol, name, live) - case markGone: + if m == markGone { continue } } @@ -1266,22 +1261,19 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For } } - // Claim the parent before using it (review of #142): one conditional - // write on the parent attempt's entry, which retention's delete mark - // is conditioned against (see retention.go). + // The deadline starts before the parent is read, and every attempt + // (a retry included) reads it again: a snapshot deleted before the read + // is refused, and one deleted after it stays rooted by GC's grace past + // readAt + deadline, the last moment this fork can publish + // (INV-SNAP-DELETE-ANY-ORDER-001). The parent is not claimed. readAt := c.now() - snap, err := c.claimForkParent(ctx, req) + snap, err := c.readForkParent(ctx, req) if err != nil { return ForkResult{}, err } - // Read after the claim: a delete of the source marks its HEAD deleting - // before it reads claims, so either it sees this claim (and gives its - // mark back) or this read sees the mark and the fork gives the claim - // back before installing anything. if gone, err := c.volumeGone(ctx, req.Source); err != nil { return ForkResult{}, err } else if gone { - c.dropForkClaim(ctx, req, snap.attempt) return ForkResult{}, refuseDeleted(req.Source, "its snapshots cannot be forked") } if snap.geo == (Geometry{}) { @@ -1382,115 +1374,33 @@ func (c *Catalog) fork(ctx context.Context, req ForkRequest, origin string) (For return ForkResult{}, err } if h.State == storage.ChunkHeadAborted || headDeletingOrDeleted(h) { - c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands - c.dropForkClaim(ctx, req, snap.attempt) // and this fork never needs the parent again + c.dropIntent(ctx, dstRoot, id) // the tombstone is permanent: this create never lands return ForkResult{}, catErr(CodeTargetExists, false, nil, "fork %s lost to a sweep: its HEAD is an aborted tombstone; fork to a new volume id", req.Target) } if outcome != createUnsettled { c.dropIntent(ctx, dstRoot, id) // confirmed, or refused for good } - c.dropForkClaim(ctx, req, snap.attempt) // the fork has its HEAD: the parent is no longer needed for it return forkResult(existing, outcome != createdNow), nil } -// claimForkParent adds fork req's claim to the parent attempt its -// snapshot name resolves to, conditioned on the entry being active with -// the claims read, and returns that snapshot. A parent deleting is -// refused (snapshot_deleting); a claim already there is reused. -func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { - root, err := c.volRoot(req.Source) +// readForkParent returns the published snapshot fork req names. A parent +// deleting is refused (snapshot_deleting), an absent or aborted one +// (snapshot_not_found). +func (c *Catalog) readForkParent(ctx context.Context, req ForkRequest) (SnapshotInfo, error) { + ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) if err != nil { return SnapshotInfo{}, err } - token := forkClaim(req.Target, req.RequestID) - dir := path.Join(root, snapsDir, req.Snapshot) - for try := 0; try < 5; try++ { - ref, ok, err := c.resolveSnap(ctx, req.Source, req.Snapshot) - if err != nil { - return SnapshotInfo{}, err - } - if !ok || ref.entry == nil || ref.info.State == SnapAborted { - return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) - } - if ref.info.State == SnapDeleting { - return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) - } - if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { - return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) - } - claims := decodeClaims(ref.entry) - for _, cl := range claims { - if cl == token { - return ref.info, nil - } - } - raw := ref.entry.Extended[extSnapClaims] - next := proto.Clone(ref.entry).(*filerpb.Entry) - setClaims(next, append(claims, token)) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: raw}) - if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a mark, another claim or a delete landed: read again - } - if err != nil { - // The claim may have landed; a retry finds and reuses it. - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, err, "fork %s: claim on %s/%s outcome unknown; retry with the same request id", req.Target, req.Source, req.Snapshot) - } - return ref.info, nil + if !ok || ref.entry == nil || ref.info.State == SnapAborted { + return SnapshotInfo{}, catErr(CodeSnapshotNotFound, false, nil, "snapshot %s/%s", req.Source, req.Snapshot) } - return SnapshotInfo{}, catErr(CodeOutcomeUnknown, true, nil, "fork %s: snapshot %s/%s kept changing; retry", req.Target, req.Source, req.Snapshot) -} - -// dropForkClaim removes fork req's claim from its parent attempt once the -// fork no longer needs it (best effort: retention treats a claim whose -// target has a HEAD as dead anyway). -func (c *Catalog) dropForkClaim(ctx context.Context, req ForkRequest, attempt string) { - _, _ = c.removeForkClaim(ctx, req, attempt) -} - -// removeForkClaim removes fork req's claim from its parent attempt and -// reports whether this call confirmed its removal (false with no error: -// the claim was not there). -func (c *Catalog) removeForkClaim(ctx context.Context, req ForkRequest, attempt string) (bool, error) { - root, err := c.volRoot(req.Source) - if err != nil || attempt == "" { - return false, err + if ref.info.State == SnapDeleting { + return SnapshotInfo{}, catErr(CodeSnapshotDeleting, false, nil, "snapshot %s/%s is being deleted", req.Source, req.Snapshot) } - token := forkClaim(req.Target, req.RequestID) - dir := path.Join(root, snapsDir, req.Snapshot) - for try := 0; try < 3; try++ { - e, err := c.f.LookupEntry(ctx, dir, attempt) - if errors.Is(err, ErrNotFound) { - return false, nil - } - if err != nil { - return false, remoteErr(err, "read %s/%s attempt %s", req.Source, req.Snapshot, attempt) - } - claims := decodeClaims(e) - kept := claims[:0:0] - for _, cl := range claims { - if cl != token { - kept = append(kept, cl) - } - } - if len(kept) == len(claims) { - return false, nil - } - c.hook(hookClaimDrop, req.Snapshot) - // Conditioned on the state read too (review of f42e723): a - // delete that marked the entry meanwhile must never be undone by - // this stale copy. A lost condition re-reads a fresh copy. - raw := e.Extended[extSnapClaims] - next := proto.Clone(e).(*filerpb.Entry) - setClaims(next, kept) - err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: e.Extended[extSnapState], extSnapClaims: raw}) - if err == nil { - return true, nil - } - if !errors.Is(err, ErrPrecondition) { - return false, remoteErr(err, "remove the claim of %s on %s/%s", req.Target, req.Source, req.Snapshot) - } + if ref.info.geo.BlockSize != 0 && ref.info.geo.NumBlocks > geometry.MaxVolumeBytes/uint64(ref.info.geo.BlockSize) { + return SnapshotInfo{}, catErr(CodeGeometryMismatch, false, nil, "fork size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) } - return false, remoteErr(nil, "claim of %s on %s/%s kept changing", req.Target, req.Source, req.Snapshot) + return ref.info, nil } // AbortFork settles a dead fork for a GC sweep (W5): it claims the diff --git a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go index 44b67dffaa..b3fe22a6f5 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go +++ b/seaweed-block/core/frontend/chunkstore/catalog_settle_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/sha256" "errors" - "path" "sort" "strings" "testing" @@ -166,22 +165,8 @@ func TestFork_IncompleteRetryBoundToOriginalImage(t *testing.T) { t.Fatalf("request id reused for another snapshot: %v, want target_exists", err) } - // The fork claims s1, so an explicit delete is refused. The image - // binding below still guards a - // fork made before claims existed: drop the claim as such a fork would - // never have written one. - if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of a claimed parent: %v, want snapshot_claimed", err) - } - ref, _, err := c.resolveSnap(ctx, "v1", "s1") - if err != nil || ref.entry == nil { - t.Fatalf("read s1: %v", err) - } - delete(ref.entry.Extended, extSnapClaims) - if err := f.UpdateEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), ref.entry, nil); err != nil { - t.Fatal(err) - } - + // Forks do not hold their parent: the delete goes through while the + // fork is incomplete, and the image binding below guards the retry. // s1 is deleted and recreated over a newer source image. if _, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil { // frees the name t.Fatal(err) diff --git a/seaweed-block/core/frontend/chunkstore/gc.go b/seaweed-block/core/frontend/chunkstore/gc.go index 678e243df2..d46175a8cf 100644 --- a/seaweed-block/core/frontend/chunkstore/gc.go +++ b/seaweed-block/core/frontend/chunkstore/gc.go @@ -41,9 +41,20 @@ type GCConfig struct { Grace, IntentTTL time.Duration // ClockSkew bounds pairwise wall-clock differences. Zero uses the default. // Binding creation timestamps additionally lose up to one second of precision. - ClockSkew time.Duration - IssuedEpoch func(context.Context, string) (uint64, error) - Now func() time.Time + ClockSkew time.Duration + // CASApplyBound is the margin for a publish applied after its fork's + // deadline check. Zero uses the catalog operation deadline. A publish + // known to have succeeded was applied before its context ended, and that + // context ends at readAt + deadline, so it is inside the deadline; an + // unknown outcome keeps the fork intent, which roots the keys until the + // target is resolved, with no time bound. This bound covers apply delay + // and clock-rate drift beyond those two. NewCollector requires + // Grace >= operation deadline + ClockSkew + CASApplyBound, so a snapshot + // deleted while a fork of it is in flight stays rooted until the fork can + // no longer publish (INV-SNAP-DELETE-ANY-ORDER-001). + CASApplyBound time.Duration + IssuedEpoch func(context.Context, string) (uint64, error) + Now func() time.Time } type GCRoot struct { @@ -105,8 +116,8 @@ type Collector struct { } func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, error) { - if cat == nil || blobs == nil || cfg.Grace <= cat.deadline() || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { - return nil, errors.New("chunkstore: GC requires catalog, blob deletion, grace > operation deadline, positive intent TTL and epoch authority") + if cat == nil || blobs == nil || cfg.IntentTTL <= 0 || cfg.IssuedEpoch == nil { + return nil, errors.New("chunkstore: GC requires catalog, blob deletion, positive intent TTL and epoch authority") } if cfg.ClockSkew == 0 { cfg.ClockSkew = DefaultGCClockSkew @@ -114,6 +125,17 @@ func NewCollector(cat *Catalog, blobs BlobDeleter, cfg GCConfig) (*Collector, er if cfg.ClockSkew < 0 || cfg.ClockSkew > time.Duration(1<<63-1)-time.Second { return nil, errors.New("chunkstore: invalid GC clock skew bound") } + if cfg.CASApplyBound == 0 { + cfg.CASApplyBound = cat.deadline() + } + const maxDur = time.Duration(1<<63 - 1) + d := cat.deadline() + if cfg.CASApplyBound < 0 || cfg.CASApplyBound > maxDur-d-cfg.ClockSkew { + return nil, errors.New("chunkstore: invalid GC CAS apply bound") + } + if need := d + cfg.ClockSkew + cfg.CASApplyBound; cfg.Grace < need { + return nil, fmt.Errorf("chunkstore: GC grace %v is below operation deadline %v + clock skew %v + CAS apply bound %v = %v", cfg.Grace, d, cfg.ClockSkew, cfg.CASApplyBound, need) + } if cfg.Now == nil { cfg.Now = time.Now } diff --git a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go index f45bd190a4..ea5cfdc98f 100644 --- a/seaweed-block/core/frontend/chunkstore/gc_volume_test.go +++ b/seaweed-block/core/frontend/chunkstore/gc_volume_test.go @@ -51,20 +51,32 @@ func TestVolumeGC_ForeignIntentRootsAndLocalCandidates(t *testing.T) { } } -func TestGC_GraceConstructorRejectsCopyDeadline(t *testing.T) { +// Grace must cover the operation deadline, the clock skew and the CAS apply +// bound (default: the deadline), so a snapshot deleted while a fork of it is +// in flight stays rooted until that fork can no longer publish. +func TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound(t *testing.T) { _, b, c, g, _ := gcFixture(t) - for _, grace := range []time.Duration{0, c.deadline() - time.Nanosecond, c.deadline()} { + need := c.deadline() + DefaultGCClockSkew + c.deadline() + for _, grace := range []time.Duration{0, c.deadline(), c.deadline() + DefaultGCClockSkew, need - time.Nanosecond} { cfg := g.cfg - cfg.Grace = grace + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = grace, 0, 0 if _, err := NewCollector(c, b, cfg); err == nil { - t.Errorf("accepted grace %s <= copy deadline", grace) + t.Errorf("accepted grace %s < deadline + skew + apply bound %s", grace, need) } } cfg := g.cfg - cfg.Grace = c.deadline() + time.Nanosecond + cfg.Grace, cfg.ClockSkew, cfg.CASApplyBound = need, 0, 0 + if _, err := NewCollector(c, b, cfg); err != nil { + t.Fatalf("grace = deadline + skew + apply bound: %v", err) + } + cfg.Grace, cfg.CASApplyBound = need, time.Second // an explicit, smaller bound if _, err := NewCollector(c, b, cfg); err != nil { t.Fatal(err) } + cfg.CASApplyBound = -1 + if _, err := NewCollector(c, b, cfg); err == nil { + t.Fatal("accepted a negative CAS apply bound") + } } func TestVolumeGC_DoesNotImportGlobalMark(t *testing.T) { diff --git a/seaweed-block/core/frontend/chunkstore/restore_test.go b/seaweed-block/core/frontend/chunkstore/restore_test.go index 25588987c4..bcda46abf0 100644 --- a/seaweed-block/core/frontend/chunkstore/restore_test.go +++ b/seaweed-block/core/frontend/chunkstore/restore_test.go @@ -390,48 +390,3 @@ func TestRestore_SnapshotOfAStalePreIndependenceImageRefused(t *testing.T) { t.Fatalf("the own image must still be accepted: %v", err) } } - -// Retention disposition with an aborted first HEAD on a restore target: the -// fork claim alone no longer holds the parent (liveClaims counts any HEAD, -// aborted included), but the fork-record scan does (forkParentsNeeded treats -// an aborted HEAD as no HEAD), so the parent snapshot is kept as fork_parent -// until the aborted target is deleted. That conservative hold is the rule. -func TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted(t *testing.T) { - f, c, _, _ := retentionFixture(t, 1) - ctx := context.Background() - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy - t.Fatal(err) - } - for _, vol := range []string{"v1", "v2"} { - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Restore(ctx, ForkRequest{Source: "v1", Snapshot: "s00", Target: "v2", RequestID: "rs"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("restore with a held HEAD create: %v", err) - } - if claimed, err := c.AbortFork(ctx, "v2"); err != nil || !claimed { - t.Fatalf("abort the unpublished restore: claimed=%v %v", claimed, err) - } - if live, err := c.liveClaims(ctx, "v1", "s00", []string{forkClaim("v2", "rs")}); err != nil || len(live) != 0 { - t.Fatalf("claim on an aborted target: live=%v %v, want not live (any HEAD ends the claim)", live, err) - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if k := kept(res.Decisions); len(k) != 1 || k["s00"] == nil || k["s00"][0] != keepForkParent || len(res.Deleted) != 0 { - t.Fatalf("aborted restore: kept %v deleted %v; want s00 kept as fork_parent", k, res.Deleted) - } - if s, err := c.allSnapshots(ctx, "v1"); err != nil || len(s) != 1 { - t.Fatalf("parent after retention: %v %v", s, err) - } - if _, err := c.DeleteVolume(ctx, "v2", nil); err != nil { - t.Fatalf("delete the aborted restore: %v", err) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || len(res.Deleted) != 1 || res.Deleted[0] != "s00" { - t.Fatalf("after the target is gone: deleted %v (%v), want s00", res.Deleted, err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a714cb82bc..2873849236 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -8,13 +8,11 @@ import ( "path" "sort" "strconv" - "strings" "time" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" - "github.com/seaweedfs/seaweed-block/core/storage" ) // Snapshot retention. @@ -34,7 +32,6 @@ import ( // + every snapshot younger than KeepYounger (a creation time in the // future, from clock skew, counts as young) // + the log-spaced keeps (below) -// + every snapshot a fork still needs // // and deletes every other snapshot. A pinned snapshot past its ExpiresAtNs // is treated as unpinned. GC reclaims the chunks. @@ -50,34 +47,18 @@ import ( // record is removed only while it still names that attempt, so a // same-name replacement made after planning is never touched. // -// Fork parents (design from the review of #142). Protection is -// one conditional write on the parent attempt's own entry, nothing else: -// -// - Fork, before it reads the parent, adds its claim (target/request) -// to the entry's claims, conditioned on {state active, claims as read}. -// A parent already deleting is refused. -// - Retain marks an attempt deleting only conditioned on {state active, -// gen, no claims}. A lost condition re-reads and decides again. -// -// The two writes hit the same entry, so one of them sees the other: either -// the claim landed first and retain keeps the snapshot (fork_held), or the -// mark landed first and the fork refuses before installing anything. -// -// A claim is removed by the fork once its HEAD is installed. Retain removes -// (conditionally) only claims that can never matter again: the target has -// a HEAD (the fork completed, or a sweep aborted it), or the target's -// VOLUME belongs to another request (this one can never publish there). -// Any other claim keeps the snapshot, however old: a fork that died before -// publishing its VOLUME holds it until the fork is retried to completion or -// settled by AbortFork. Forks published before claims existed are still -// found by the fork-record scan (forkParentsNeeded). -// -// An explicit DeleteSnapshot goes through the same check and mark -// (markDeleting): it refuses a live claim with snapshot_claimed. +// Forks and restores do not hold their parent (INV-SNAP-DELETE-ANY-ORDER-001). +// A snapshot is deleted by retention or DeleteSnapshot whatever forks read +// it: a fork reads the parent after taking its deadline start and publishes +// its HEAD only before readAt + deadline, and GC keeps a deleted attempt +// rooted for its grace, which exceeds deadline + clock skew + CAS apply +// bound (NewCollector). A fork that reads after the delete mark gets +// snapshot_deleting or snapshot_not_found, also on a retry. A claims +// xattr left by an older version is ignored. // // A pass stopped after a mark (e.g. a lost response) leaves the attempt // deleting with its name still held; the next pass (and its dry run) lists -// it and frees the name. A deleting attempt cannot gain claims. +// it and frees the name. const ( SnapshotClassSemantic = "semantic" @@ -85,18 +66,12 @@ const ( CodeInvalidClass = "invalid_class" CodeInvalidPolicy = "invalid_policy" - // CodeSnapshotClaimed: an explicit delete of a snapshot a fork still - // claims. Not retryable as such: it clears - // when the fork publishes its HEAD or is aborted. - CodeSnapshotClaimed = "snapshot_claimed" DefaultKeepNewest = 10 DefaultKeepYounger = time.Hour extRetention = "retention" extRetentionRev = "retention_rev" - - extSnapClaims = "swb.snap.claims" ) // ValidateSnapshotClass refuses a class other than "", "semantic" and @@ -217,21 +192,20 @@ type RetentionDecision struct { // The reasons a snapshot is kept. const ( - keepNewest = "newest" - keepPinned = "pinned" - keepYoung = "younger_than_policy" - keepHourly = "hourly" - keepDaily = "daily" - keepWeekly = "weekly" - keepForkParent = "fork_parent" - reasonExpired = "expired" + keepNewest = "newest" + keepPinned = "pinned" + keepYoung = "younger_than_policy" + keepHourly = "hourly" + keepDaily = "daily" + keepWeekly = "weekly" + reasonExpired = "expired" ) // planRetention decides, from one listing, which snapshots policy keeps at -// now. needed names the snapshots a fork still needs. Unpinned snapshots +// now. Unpinned snapshots // are ranked newest first; equal creation times rank by name, so the plan // is deterministic. -func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bool, now time.Time) []RetentionDecision { +func planRetention(p RetentionPolicy, snaps []SnapshotInfo, now time.Time) []RetentionDecision { ordered := append([]SnapshotInfo(nil), snaps...) sort.SliceStable(ordered, func(i, j int) bool { if ordered[i].CreatedNs != ordered[j].CreatedNs { @@ -280,9 +254,6 @@ func planRetention(p RetentionPolicy, snaps []SnapshotInfo, needed map[string]bo d.Reasons = append(d.Reasons, lk.reason) } } - if needed[s.Name] { - d.Reasons = append(d.Reasons, keepForkParent) - } d.Keep = len(d.Reasons) > 0 if !d.Keep { d.Reasons = []string{reasonExpired} @@ -314,7 +285,6 @@ type RetentionResult struct { Decisions []RetentionDecision `json:"decisions"` Deleted []string `json:"deleted"` // confirmed deleted (empty on a dry run) Replaced []string `json:"replaced"` // planned, but the name now holds another attempt: left alone - ForkHeld []string `json:"forkHeld"` // planned, but a fork took a hold meanwhile: kept Failed *RetentionFailure `json:"failed,omitempty"` // NotAttempted lists the expired snapshots not reached because the // pass stopped at Failed. @@ -350,13 +320,9 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio snaps = append(snaps, s) } } - needed, err := c.forkParentsNeeded(ctx, vol) - if err != nil { - return RetentionResult{}, err - } res := RetentionResult{VolumeID: vol, Policy: p, PolicySet: set, DryRun: dryRun, - Deleted: []string{}, Replaced: []string{}, ForkHeld: []string{}, NotAttempted: []string{}} - res.Decisions = planRetention(p, snaps, needed, c.now()) + Deleted: []string{}, Replaced: []string{}, NotAttempted: []string{}} + res.Decisions = planRetention(p, snaps, c.now()) var expired []RetentionDecision for _, d := range res.Decisions { if d.Keep { @@ -390,8 +356,6 @@ func (c *Catalog) Retain(ctx context.Context, vol string, dryRun bool) (Retentio res.Deleted = append(res.Deleted, d.Name) case retainReplaced: res.Replaced = append(res.Replaced, d.Name) - case retainForkHeld: - res.ForkHeld = append(res.ForkHeld, d.Name) } } return res, nil @@ -409,7 +373,6 @@ type retainOutcome int const ( retainDeleted retainOutcome = iota // marked deleting (or already gone) and the name freed retainReplaced // the planned attempt is gone; another attempt holds the name - retainForkHeld // a live fork claim is on the attempt: kept, nothing written ) // deleteRetainedAttempt deletes the planned attempt of vol/name and only @@ -420,13 +383,9 @@ func (c *Catalog) deleteRetainedAttempt(ctx context.Context, vol, name, attempt if err != nil { return 0, false, err } - m, _, uncertain, err := c.markDeleting(ctx, vol, name, attempt) - if err != nil { + if _, uncertain, err := c.markDeleting(ctx, vol, name, attempt); err != nil { return 0, uncertain, err } - if m == markClaimed { - return retainForkHeld, false, nil - } return c.freeName(ctx, root, name, attempt) } @@ -435,90 +394,56 @@ type markResult int const ( markDone markResult = iota // this call marked the attempt deleting markGone // the attempt's entry is gone - markSettled // already deleting or aborted (no fork can claim it) - markClaimed // a live fork claim is on it: nothing written + markSettled // already deleting or aborted ) -// markDeleting marks attempt of vol/name deleting under the fork-claim -// rule, the one path for retention and explicit delete: the mark is -// conditioned on {state active, gen, no claims}; dead claims are cleared -// conditionally first; a lost condition re-reads and decides again. live -// lists the live claims when the result is markClaimed. uncertain -// reports, with an error, a mutation whose outcome is unknown. -func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, []string, bool, error) { +// markDeleting marks attempt of vol/name deleting, the one path for +// retention and explicit delete: the mark is conditioned on {state active, +// gen}; a lost condition re-reads and decides again. No fork claim is read +// (INV-SNAP-DELETE-ANY-ORDER-001). uncertain reports, with an error, a +// mutation whose outcome is unknown. +func (c *Catalog) markDeleting(ctx context.Context, vol, name, attempt string) (markResult, bool, error) { root, err := c.volRoot(vol) if err != nil { - return 0, nil, false, err + return 0, false, err } dir := path.Join(root, snapsDir, name) for try := 0; try < 5; try++ { e, err := c.f.LookupEntry(ctx, dir, attempt) if errors.Is(err, ErrNotFound) { - return markGone, nil, false, nil + return markGone, false, nil } if err != nil { - return 0, nil, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) + return 0, false, remoteErr(err, "read snapshot %s/%s attempt %s", vol, name, attempt) } if string(e.Extended[extSnapState]) != SnapActive { - return markSettled, nil, false, nil - } - raw := string(e.Extended[extSnapClaims]) - claims := decodeClaims(e) - live, err := c.liveClaims(ctx, vol, name, claims) - if err != nil { - return 0, nil, false, err - } - if len(live) > 0 { - return markClaimed, live, false, nil + return markSettled, false, nil } c.hook(hookChecked, name) next := proto.Clone(e).(*filerpb.Entry) - if len(claims) > 0 { - // Every claim is dead: clear them, then decide again. - delete(next.Extended, extSnapClaims) - err := c.f.UpdateEntry(ctx, dir, next, map[string][]byte{extSnapState: []byte(SnapActive), extSnapClaims: []byte(raw)}) - if err != nil && !errors.Is(err, ErrPrecondition) && !errors.Is(err, ErrNotFound) { - return 0, nil, true, remoteErr(err, "clear the dead fork claims of %s/%s attempt %s", vol, name, attempt) - } - continue - } next.Extended[extSnapState] = []byte(SnapDeleting) next.Extended[extSnapDeletedNs] = []byte(strconv.FormatInt(c.now().UnixNano(), 10)) err = c.f.UpdateEntry(ctx, dir, next, map[string][]byte{ - extSnapState: []byte(SnapActive), - extSnapGen: e.Extended[extSnapGen], - extSnapClaims: nil, // no claims: a fork that claimed meanwhile wins + extSnapState: []byte(SnapActive), + extSnapGen: e.Extended[extSnapGen], }) if errors.Is(err, ErrPrecondition) || errors.Is(err, ErrNotFound) { - continue // a claim, a delete or a replacement landed: decide again + continue // a delete or a replacement landed: decide again } if err != nil { - return 0, nil, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) + return 0, true, remoteErr(err, "mark snapshot %s/%s attempt %s deleting", vol, name, attempt) } c.hook(hookMarked, name) - return markDone, nil, false, nil + return markDone, false, nil } - return 0, nil, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) -} - -// claimedErr is snapshot_claimed naming the claiming fork volumes. -func claimedErr(vol, name string, live []string) error { - targets := make([]string, 0, len(live)) - for _, cl := range live { - t, _, _ := strings.Cut(cl, "/") - targets = append(targets, t) - } - return catErr(CodeSnapshotClaimed, false, nil, "snapshot %s/%s is the parent of incomplete fork %s; it can be deleted once that fork completes or is aborted", vol, name, strings.Join(targets, ", ")) + return 0, false, remoteErr(nil, "snapshot %s/%s attempt %s kept changing", vol, name, attempt) } // Test seams: hook stages in a Retain pass. const ( hookPlanned = "planned" // after planning, before any deletion - hookChecked = "checked" // an attempt's claims were read and none is live, before its mark + hookChecked = "checked" // an attempt was read active, before its mark hookMarked = "marked" // an attempt is marked deleting, before its name is freed - // hookClaimDrop: a completed fork read its parent entry to drop its - // claim, before the conditional write. - hookClaimDrop = "claim-drop" ) func (c *Catalog) hook(stage, name string) { @@ -539,61 +464,6 @@ func (c *Catalog) freeName(ctx context.Context, root, name, attempt string) (ret return 0, true, remoteErr(err, "remove the name record %s", name) } -// forkClaim is the claim a fork puts on its parent attempt. -func forkClaim(target, requestID string) string { return target + "/" + requestID } - -func decodeClaims(e *filerpb.Entry) []string { - raw := e.Extended[extSnapClaims] - if len(raw) == 0 { - return nil - } - var out []string - if json.Unmarshal(raw, &out) != nil { - return []string{string(raw)} // unreadable: kept as one live claim (safe) - } - return out -} - -func setClaims(e *filerpb.Entry, claims []string) { - if len(claims) == 0 { - delete(e.Extended, extSnapClaims) - return - } - sort.Strings(claims) - body, _ := json.Marshal(claims) - e.Extended[extSnapClaims] = body -} - -// liveClaims returns the claims on vol/name that a fork may still need: a -// claim is dead only when its target has a HEAD, or its target's VOLUME -// was made by another request (or from another parent). -func (c *Catalog) liveClaims(ctx context.Context, vol, name string, claims []string) ([]string, error) { - var live []string - for _, cl := range claims { - target, req, ok := strings.Cut(cl, "/") - if !ok || CheckVolumeID(target) != nil { - live = append(live, cl) // not ours to judge: keep the snapshot - continue - } - _, has, err := c.ReadHead(ctx, target) - if err != nil { - return nil, err - } - if has { - continue - } - v, ok, err := c.ReadVolume(ctx, target) - if err != nil { - return nil, err - } - if ok && (v.Fork == nil || v.Fork.RequestID != req || v.Fork.Source != vol || v.Fork.Snapshot != name) { - continue - } - live = append(live, cl) - } - return live, nil -} - // allSnapshots lists every published, not-deleting snapshot of vol, with // the attempt each name resolved to. func (c *Catalog) allSnapshots(ctx context.Context, vol string) ([]SnapshotInfo, error) { @@ -618,36 +488,3 @@ func (c *Catalog) listSnapshots(ctx context.Context, vol string, deleting bool) after = next } } - -// forkParentsNeeded names the snapshots of vol a fork still needs by its -// published fork record: a volume whose fork record names vol and the -// snapshot, and which has no real published HEAD yet (absent or aborted). -// It covers forks published before fork holds existed; a newer fork is -// also covered, atomically, by its hold (deleteRetainedAttempt). -func (c *Catalog) forkParentsNeeded(ctx context.Context, vol string) (map[string]bool, error) { - vols, err := c.ListVolumes(ctx) - if err != nil { - return nil, err - } - needed := map[string]bool{} - for _, other := range vols { - if other == vol { - continue - } - v, ok, err := c.ReadVolume(ctx, other) - if err != nil { - return nil, err - } - if !ok || v.Fork == nil || v.Fork.Source != vol { - continue - } - h, has, err := c.ReadHead(ctx, other) - if err != nil { - return nil, err - } - if !has || h.State == storage.ChunkHeadAborted { - needed[v.Fork.Snapshot] = true - } - } - return needed, nil -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go index 1570b55000..d04475e01c 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_integration_test.go @@ -143,7 +143,7 @@ func TestIntegration_RetainAndUsage(t *testing.T) { // deadline exceeded) keeps its parent, and completes on retry; (3) a fork // that claims between retention's claim check and its mark makes the // filer refuse the mark (conditioned on no claims), so the parent is kept. -func TestIntegration_RetainHeldSchedules(t *testing.T) { +func TestIntegration_RetainIgnoresIncompleteForks(t *testing.T) { c := startWeed(t) ctx := context.Background() const base = "/swblock/chunks" @@ -222,27 +222,18 @@ func TestIntegration_RetainHeldSchedules(t *testing.T) { t.Fatal(err) } cat.retainHook = nil - if len(res.Deleted) != 0 || fmt.Sprint(res.Replaced) != "[s00]" || fmt.Sprint(res.ForkHeld) != "[s02 s01]" { - t.Fatalf("retain: deleted=%v replaced=%v forkHeld=%v; want none / s00 / s02 s01", res.Deleted, res.Replaced, res.ForkHeld) + if fmt.Sprint(res.Deleted) != "[s02 s01]" || fmt.Sprint(res.Replaced) != "[s00]" { + t.Fatalf("retain: deleted=%v replaced=%v; want s02 s01 / s00 (forks do not hold their parent)", res.Deleted, res.Replaced) } b, err := cat.readSnap(ctx, "v1", "s00") if err != nil || b.attempt != pinnedAttempt || b.State != SnapActive || b.Class != SnapshotClassPinned { t.Fatalf("pinned replacement: %+v %v (attempt %s, want %s)", b, err, b.attempt, pinnedAttempt) } - // An explicit delete of a claimed parent is refused. - if _, err := cat.DeleteSnapshot(ctx, "v1", "s01"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete of the claimed s01: %v; want snapshot_claimed", err) - } + // A retry of either stopped fork reads its parent again and is refused. for _, fk := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - if s, err := cat.readSnap(ctx, "v1", fk.snap); err != nil || s.State != SnapActive { - t.Fatalf("fork parent %s: %+v %v; want active", fk.snap, s, err) + _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("fork %s retry after its parent was deleted: %v; want snapshot_not_found or snapshot_deleting", fk.target, err) } - if _, err := cat.Fork(ctx, ForkRequest{Source: "v1", Snapshot: fk.snap, Target: fk.target, RequestID: "f"}); err != nil { - t.Fatalf("fork %s retry: %v", fk.target, err) - } - } - res, err = cat.Retain(ctx, "v1", false) - if err != nil || fmt.Sprint(res.Deleted) != "[s02 s01]" { - t.Fatalf("after the forks completed: deleted=%v %v; want s02 s01 (s00 is pinned)", res.Deleted, err) } } diff --git a/seaweed-block/core/frontend/chunkstore/retention_review_test.go b/seaweed-block/core/frontend/chunkstore/retention_review_test.go index ab074525b3..0ebd5b8081 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_review_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_review_test.go @@ -3,7 +3,6 @@ package chunkstore import ( "context" "errors" - "path" "strings" "testing" "time" @@ -26,7 +25,7 @@ func TestPlanRetention_RollingWindows(t *testing.T) { for _, a := range ages { snaps = append(snaps, snapAt(nm(a), a, SnapshotClassSemantic, time.Time{}, nil)) } - return kept(planRetention(p, snaps, nil, now)) + return kept(planRetention(p, snaps, now)) } now := at(10*time.Hour + 30*time.Minute) if k := plan(RetentionPolicy{KeepHourly: 1}, now, at(10*time.Hour+20*time.Minute), at(9*time.Hour+50*time.Minute)); len(k) != 1 || k[nm(at(10*time.Hour+20*time.Minute))] == nil { @@ -104,51 +103,6 @@ func forkFixture(t *testing.T) (*fakeFiler, *Catalog) { return f, c } -// A fork that starts after the retention scan (its VOLUME published, its -// HEAD not yet) has claimed the parent: retention keeps it, and the fork -// completes on retry. -func TestCatalog_RetainKeepsAParentForkedAfterTheScan(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - c.retainHook = func(stage, _ string) { - if stage != hookPlanned { - return - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { - t.Fatalf("deleted=%v forkHeld=%v; want s01 kept for the fork", res.Deleted, res.ForkHeld) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent after retain: %+v %v; want active", s, err) - } - c.retainHook = nil - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - // Completed: the hold is gone and the parent is no longer needed. - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after the fork completed: deleted=%v %v; want s01", res.Deleted, err) - } -} - -func claimsOf(t *testing.T, c *Catalog, name string) []string { - t.Helper() - ref, ok, err := c.resolveSnap(context.Background(), "v1", name) - if err != nil || !ok || ref.entry == nil { - t.Fatalf("read %s: ok=%t %v", name, ok, err) - } - return decodeClaims(ref.entry) -} - // A fork arriving after the mark finds the parent deleting and refuses // before installing anything (and leaves no claim). func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { @@ -176,105 +130,6 @@ func TestCatalog_ForkAfterTheMarkRefuses(t *testing.T) { } } -// Schedule 1: retention read no claims, then a fork claims before the -// mark. The mark's condition (no claims) fails; retention reads again, -// sees the live claim and keeps the parent. -func TestCatalog_ClaimBetweenCheckAndMarkWins(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - c.retainHook = func(stage, name string) { - if stage != hookChecked || name != "s01" { - return - } - c.retainHook = nil - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - } - res, err := c.Retain(ctx, "v1", false) - if err != nil { - t.Fatal(err) - } - if strings.Join(res.ForkHeld, ",") != "s01" || strings.Join(res.Deleted, ",") != "s02,s00" { - t.Fatalf("deleted=%v forkHeld=%v; want s01 kept", res.Deleted, res.ForkHeld) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent: %+v %v; want active", s, err) - } - if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/f" { - t.Fatalf("claims %v; want v2/f", got) - } -} - -// Schedule 2: a fork that claimed and died before publishing its VOLUME -// keeps the parent however much later retention runs (no lifetimes); the -// fork retried to completion releases it. -func TestCatalog_DeadForkClaimKeepsTheParent(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - f.failCreate = func(p string) error { - if p == catBase+"/v2/"+volumeName { - return errors.New("filer unavailable") - } - return nil - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err == nil { - t.Fatal("fork with a failing VOLUME create succeeded") - } - f.failCreate = nil - if _, ok, _ := c.ReadVolume(ctx, "v2"); ok { - t.Fatal("VOLUME published") - } - saved := c.now - c.SetClock(func() time.Time { return saved().Add(30 * 24 * time.Hour) }) - res, err := c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.ForkHeld, ",") != "s01" { - t.Fatalf("30 days later: forkHeld=%v %v; want s01 still kept", res.ForkHeld, err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - if got := claimsOf(t, c, "s01"); len(got) != 0 { - t.Fatalf("claims after the fork completed: %v; want none", got) - } - res, err = c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after completion: deleted=%v %v; want s01", res.Deleted, err) - } -} - -// Schedule 3: a second request for the same target is refused without -// touching the first request's claim (claims are per target AND request, -// and a fork drops only its own, only once its HEAD exists). -func TestCatalog_RefusedSameTargetForkLeavesTheOtherClaim(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork a: %v", err) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "b"}); CodeOf(err) != CodeTargetExists { - t.Fatalf("fork b (same target, other request): %v; want target_exists", err) - } - if _, err := c.Retain(ctx, "v1", false); err != nil { - t.Fatal(err) - } - if s, err := c.readSnap(ctx, "v1", "s01"); err != nil || s.State != SnapActive { - t.Fatalf("parent after retain: %+v %v; want kept for request a", s, err) - } - if got := claimsOf(t, c, "s01"); strings.Join(got, ",") != "v2/a" { - t.Fatalf("claims %v; want only a's, intact", got) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "a"}); err != nil { - t.Fatalf("fork a retry: %v", err) - } - res, err := c.Retain(ctx, "v1", false) - if err != nil || strings.Join(res.Deleted, ",") != "s01" { - t.Fatalf("after a completed: deleted=%v %v; want s01 (b's claim dead)", res.Deleted, err) - } -} - // A failure part way reports the confirmed deletions, the failing // snapshot (uncertain: the mark's outcome is unknown) and what was not // attempted; a lost response leaves the snapshot deleting and the next @@ -355,84 +210,3 @@ func TestCatalog_UsageCountsForkHolders(t *testing.T) { t.Fatalf("s1 after v1's HEAD moved, v2 forked from it: %+v; want 0 exclusive (v2 holds both chunks)", u.Snapshots) } } - -// An explicit delete of a snapshot an -// incomplete fork claims is refused (snapshot_claimed, not retryable, -// naming the fork); once the fork completes or is aborted the delete goes -// through. Retention and delete share the check (markDeleting). -func TestCatalog_DeleteRefusesAClaimedParent(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork v2: %v", err) - } - holdFirst(f, catBase+"/v3/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s02", Target: "v3", RequestID: "g"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork v3: %v", err) - } - for _, tc := range []struct{ snap, target string }{{"s01", "v2"}, {"s02", "v3"}} { - _, err := c.DeleteSnapshot(ctx, "v1", tc.snap) - var ce *CatalogError - if !errors.As(err, &ce) || ce.Code != CodeSnapshotClaimed || ce.Retryable || !strings.Contains(ce.Detail(), tc.target) { - t.Fatalf("delete %s claimed by %s: %v; want snapshot_claimed, not retryable, naming %s", tc.snap, tc.target, err, tc.target) - } - if s, err := c.readSnap(ctx, "v1", tc.snap); err != nil || s.State != SnapActive { - t.Fatalf("%s after the refused delete: %+v %v; want active", tc.snap, s, err) - } - } - // Completed fork: its claim no longer blocks. - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork v2 retry: %v", err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil || got != SnapDeleting { - t.Fatalf("delete after the fork completed: %q %v", got, err) - } - // Aborted fork (a sweep's tombstone): neither does its claim. - if claimed, err := c.AbortFork(ctx, "v3"); err != nil || !claimed { - t.Fatalf("abort v3: claimed=%t %v", claimed, err) - } - if got, err := c.DeleteSnapshot(ctx, "v1", "s02"); err != nil || got != SnapDeleting { - t.Fatalf("delete after the fork was aborted: %q %v", got, err) - } -} - -// Review of f42e723: a completed fork's claim cleanup that read the parent -// entry, then paused while an explicit delete marked it, must not write -// its stale copy back (resurrecting an unnamed snapshot as a GC root). -func TestCatalog_ClaimCleanupNeverUndoesADelete(t *testing.T) { - f, c := forkFixture(t) - ctx := context.Background() - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork: %v", err) - } - parent, err := c.readSnap(ctx, "v1", "s01") - if err != nil { - t.Fatal(err) - } - ran := false - c.retainHook = func(stage, name string) { - if stage != hookClaimDrop || name != "s01" || ran { - return - } - ran = true // the fork's HEAD exists now: its claim is dead - if _, err := c.DeleteSnapshot(ctx, "v1", "s01"); err != nil { - t.Fatalf("delete during the claim cleanup: %v", err) - } - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - c.retainHook = nil - e, err := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s01"), parent.attempt) - if err != nil { - t.Fatal(err) - } - if !ran || string(e.Extended[extSnapState]) != SnapDeleting || len(e.Extended[extSnapDeletedNs]) == 0 { - t.Fatalf("ran=%t state=%q deleted_ns=%q; want the delete mark kept", ran, e.Extended[extSnapState], e.Extended[extSnapDeletedNs]) - } - if _, ok, err := c.resolveSnap(ctx, "v1", "s01"); ok || err != nil { - t.Fatalf("s01's name is back (%v)", err) - } -} diff --git a/seaweed-block/core/frontend/chunkstore/retention_test.go b/seaweed-block/core/frontend/chunkstore/retention_test.go index 10109d3916..f329ed96be 100644 --- a/seaweed-block/core/frontend/chunkstore/retention_test.go +++ b/seaweed-block/core/frontend/chunkstore/retention_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" "github.com/seaweedfs/seaweed-block/core/storage" ) @@ -45,7 +44,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { for i := 0; i < 15; i++ { snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), retBase.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - k := kept(planRetention(noYoung(), snaps, nil, now)) + k := kept(planRetention(noYoung(), snaps, now)) if len(k) != 10 { t.Fatalf("kept %d, want 10: %v", len(k), k) } @@ -55,7 +54,7 @@ func TestPlanRetention_NewestNWithNameTieBreak(t *testing.T) { } } tie := []SnapshotInfo{snapAt("b", retBase, "", time.Time{}, nil), snapAt("a", retBase, "", time.Time{}, nil)} - if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, nil, now)); len(k) != 1 || k["a"] == nil { + if k := kept(planRetention(RetentionPolicy{KeepNewest: 1}, tie, now)); len(k) != 1 || k["a"] == nil { t.Fatalf("tie: kept %v, want only a (name order)", k) } } @@ -71,7 +70,7 @@ func TestPlanRetention_PinnedSemanticAndLabels(t *testing.T) { snapAt("semantic-old", retBase, SnapshotClassSemantic, time.Time{}, nil), snapAt("labeled-old", retBase, "", time.Time{}, map[string]string{"agent.step": "npm-ci"}), } - k := kept(planRetention(RetentionPolicy{}, snaps, nil, now)) + k := kept(planRetention(RetentionPolicy{}, snaps, now)) if len(k) != 2 || k["pinned-old"] == nil || k["pinned-by-expiry"] == nil { t.Fatalf("kept %v; want exactly pinned-old and pinned-by-expiry", k) } @@ -87,7 +86,7 @@ func TestPlanRetention_YoungAndClockSkew(t *testing.T) { snapAt("future", now.Add(10*time.Minute), SnapshotClassSemantic, time.Time{}, nil), snapAt("old", now.Add(-2*time.Hour), SnapshotClassSemantic, time.Time{}, nil), } - k := kept(planRetention(p, snaps, nil, now)) + k := kept(planRetention(p, snaps, now)) if len(k) != 2 || k["young"] == nil || k["future"] == nil { t.Fatalf("kept %v; want young and future", k) } @@ -100,7 +99,7 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { for i := 0; i < 12; i++ { // every 30 min over the last 6 hours snaps = append(snaps, snapAt(fmt.Sprintf("s%02d", i), now.Add(-time.Duration(i)*30*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, nil, now)) + k := kept(planRetention(RetentionPolicy{KeepHourly: 3}, snaps, now)) if len(k) != 3 { t.Fatalf("kept %d, want 3 (one per hour for the last 3 hours): %v", len(k), k) } @@ -111,16 +110,6 @@ func TestPlanRetention_HourlyBuckets(t *testing.T) { } } -// A snapshot a fork still needs is kept whatever the policy says. -func TestPlanRetention_ForkParentKept(t *testing.T) { - now := retBase.Add(48 * time.Hour) - snaps := []SnapshotInfo{snapAt("parent", retBase, SnapshotClassSemantic, time.Time{}, nil)} - k := kept(planRetention(RetentionPolicy{}, snaps, map[string]bool{"parent": true}, now)) - if len(k) != 1 || k["parent"][0] != keepForkParent { - t.Fatalf("kept %v; want parent (fork_parent)", k) - } -} - // An agent that checkpoints every step stays bounded: one semantic // snapshot a minute for a day keeps at most N + T/step + hourly buckets. func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { @@ -132,14 +121,14 @@ func TestPlanRetention_AgentCheckpointingEveryStepStaysBounded(t *testing.T) { } now := start.Add(24 * time.Hour) bound := p.KeepNewest + int(DefaultKeepYounger/time.Minute) + p.KeepHourly - if k := kept(planRetention(p, snaps, nil, now)); len(k) > bound { + if k := kept(planRetention(p, snaps, now)); len(k) > bound { t.Fatalf("kept %d of %d step checkpoints; want at most %d", len(k), len(snaps), bound) } // The bound holds however long the agent runs. for i := 24 * 60; i < 7*24*60; i++ { snaps = append(snaps, snapAt(fmt.Sprintf("step-%05d", i), start.Add(time.Duration(i)*time.Minute), SnapshotClassSemantic, time.Time{}, nil)) } - if k := kept(planRetention(p, snaps, nil, start.Add(7*24*time.Hour))); len(k) > bound { + if k := kept(planRetention(p, snaps, start.Add(7*24*time.Hour))); len(k) > bound { t.Fatalf("after a week: kept %d; want at most %d", len(k), bound) } } @@ -283,41 +272,6 @@ func TestCatalog_SnapshotClass(t *testing.T) { } } -// A fork whose HEAD is not yet written still needs its parent snapshot: -// retain keeps it; once the fork's HEAD is published it no longer does. -func TestCatalog_RetainKeepsParentOfAnIncompleteFork(t *testing.T) { - f, c, _, clock := retentionFixture(t, 3) - ctx := context.Background() - if err := c.SetRetentionPolicy(ctx, "v1", RetentionPolicy{}); err != nil { // keep nothing by policy - t.Fatal(err) - } - // The fake filer lists only directory entries it holds; a real filer - // has them for every volume directory. - for _, vol := range []string{"v1", "v2"} { - if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: vol, IsDirectory: true}, true); err != nil { - t.Fatal(err) - } - } - holdFirst(f, catBase+"/v2/HEAD") - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { - t.Fatalf("fork with a held HEAD create: %v", err) - } - res, err := c.Retain(ctx, "v1", true) - if err != nil { - t.Fatal(err) - } - if k := kept(res.Decisions); len(k) != 1 || k["s01"] == nil || k["s01"][0] != keepForkParent { - t.Fatalf("incomplete fork: kept %v; want only s01 (fork_parent)", k) - } - if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s01", Target: "v2", RequestID: "f"}); err != nil { - t.Fatalf("fork retry: %v", err) - } - _ = clock - if res, err := c.Retain(ctx, "v1", true); err != nil || res.Kept != 0 { - t.Fatalf("published fork: kept %d (%v); want 0", res.Kept, err) - } -} - // publishTagged installs a HEAD for vol with chunks under keys tagged tag. func publishTagged(t *testing.T, f *fakeFiler, b *fakeBlobs, vol, tag string, chunks map[uint64][]byte) storage.ChunkHead { t.Helper() diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go new file mode 100644 index 0000000000..84405652db --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -0,0 +1,158 @@ +package chunkstore + +import ( + "bytes" + "context" + "path" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. + +// A fork stopped past its deadline does not keep its parent: the snapshot is +// deleted, and a retry of the same request reads the parent again and is +// refused; it never publishes from its first read. +func TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent(t *testing.T) { + f, _, c, h := catalogFixture(t) + ctx := context.Background() + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + req := ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"} + clock := time.Now() + c.SetClock(func() time.Time { clock = clock.Add(time.Second); return clock }) // every read advances + c.OpDeadline = time.Nanosecond + if _, err := c.Fork(ctx, req); CodeOf(err) != CodeDeadlineExceeded { + t.Fatalf("fork past its deadline: %v, want deadline_exceeded", err) + } + c.OpDeadline = 0 + if _, ok, err := c.ReadVolume(ctx, "v2"); !ok || err != nil { + t.Fatalf("the stopped fork's VOLUME: ok=%v %v", ok, err) + } + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent of an incomplete fork: %q %v, want deleting", got, err) + } + _, err := c.Fork(ctx, req) + if code := CodeOf(err); code != CodeSnapshotNotFound && code != CodeSnapshotDeleting { + t.Fatalf("retry after the parent was deleted: %v, want snapshot_not_found or snapshot_deleting", err) + } + if _, err := f.LookupEntry(ctx, catBase+"/v2", headName); err == nil { + t.Fatal("the retry published a HEAD from its first read of a deleted parent") + } +} + +// A delete that lands between a fork's read of its parent and its HEAD +// publish succeeds; the fork still publishes inside its deadline, and the +// target keeps every chunk after the source snapshot and volume are gone and +// GC has run past its grace. +func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x41), 2: chunkBytes(0x42)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + deleted := false + f.stallCreate = func(p string) bool { // runs before the fake takes its lock + if p == catBase+"/v2/"+headName && !deleted { + deleted = true + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Errorf("delete while the fork is in flight: %q %v", got, err) + } + } + return false + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); err != nil { + t.Fatalf("fork whose parent was deleted after its read: %v", err) + } + f.stallCreate = nil + if !deleted { + t.Fatal("the delete never ran inside the fork") + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + for i := 0; i < 3; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) + } + r2, _ := NewChunkRemote(f, b, path.Join(catBase, "v2")) + h2, err := r2.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + for idx, ref := range h2.Chunks { + if got, err := r2.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("fork chunk %d lost: %v", idx, err) + } + } +} + +// An unknown publish outcome keeps the fork's intent, and that intent roots +// the parent's keys with no time bound: the snapshot deleted, the source +// volume deleted, GC run well past its grace, the keys survive while the +// intent exists. +func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testing.T) { + f, b, c, g, now := gcFixture(t) + ctx := context.Background() + want := map[uint64][]byte{0: chunkBytes(0x51), 1: chunkBytes(0x52)} + h := publishSource(t, f, b.fakeBlobs, "v1", want) + if _, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "r"}, h); err != nil { + t.Fatal(err) + } + if err := f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "v2", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + f.failCreate = func(p string) error { + if p == catBase+"/v2/"+headName { + return errTransport + } + return nil + } + if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "v2", RequestID: "f"}); CodeOf(err) != CodeOutcomeUnknown { + t.Fatalf("fork with an unknown HEAD create: %v", err) + } + f.failCreate = nil + if got, err := c.DeleteSnapshot(ctx, "v1", "s1"); err != nil || got != SnapDeleting { + t.Fatalf("delete the parent: %q %v", got, err) + } + detachHead(t, f, b.fakeBlobs, "v1") + if _, err := c.DeleteVolume(ctx, "v1", nil); err != nil { + t.Fatalf("delete the source volume: %v", err) + } + intents := func() int { + list, err := f.ListEntries(ctx, path.Join(catBase, "v2", intentsDir), "", "", 0) + if err != nil { + t.Fatal(err) + } + return len(list) + } + if intents() == 0 { + t.Fatal("the unknown publish left no intent") + } + for i := 0; i < 4; i++ { + if _, err := g.Run(ctx); err != nil { + t.Fatalf("gc: %v", err) + } + *now = now.Add(2 * time.Hour) // far past the grace + } + if intents() == 0 { + t.Fatal("GC settled the fork intent without the target being resolved") + } + r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + for idx, ref := range h.Chunks { + if got, err := r1.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { + t.Fatalf("parent chunk %d reclaimed while the fork intent exists: %v", idx, err) + } + } +} diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go index b1f4501a4d..28cc7b0e09 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_integration_test.go @@ -120,7 +120,7 @@ func TestIntegration_DeleteVolumeThenGC(t *testing.T) { // GC: two marks past grace reclaim exactly A (only S1 and w2 reached // it) and D (only w2); B and C (w1's HEAD and S2) stay. - grace := 2 * DefaultOpDeadline + grace := 3 * DefaultOpDeadline // >= deadline + skew + CAS apply bound at := time.Now().Add(3 * grace) g, err := NewCollector(cat, cl, GCConfig{Grace: grace, IntentTTL: time.Hour, Now: func() time.Time { return at }, IssuedEpoch: func(context.Context, string) (uint64, error) { return 1, nil }}) diff --git a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go index 0bb854fa48..c554bb76f0 100644 --- a/seaweed-block/core/frontend/chunkstore/volume_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/volume_delete_test.go @@ -331,7 +331,7 @@ func TestCatalog_InFlightSnapshotRefusesTheDelete(t *testing.T) { } } -// A fork that claims during the delete mark sees the deleting source and +// A fork that reads during the delete mark sees the deleting source and // refuses before installing anything; the delete refuses too (the forked // snapshot exists) and reverts. func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { @@ -355,9 +355,6 @@ func TestCatalog_ForkDuringTheDeleteMarkRefuses(t *testing.T) { if _, ok, _ := c.ReadVolume(ctx, "w2"); ok { t.Fatal("the refused fork published its VOLUME") } - if got := claimsOf(t, c, "s1"); len(got) != 0 { - t.Fatalf("the refused fork left claims %v", got) - } } // P2 (incarnation): D1 checks under deleting generation G and pauses @@ -504,14 +501,14 @@ func TestCatalog_DeleteVolumeTombstonesAndRefusesReuse(t *testing.T) { if _, err := c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s2", Target: "w3", RequestID: "f3"}); CodeOf(err) != CodeOutcomeUnknown { t.Fatalf("fork w3: %v", err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); CodeOf(err) != CodeSnapshotClaimed { - t.Fatalf("delete s2 under the incomplete fork: %v; want snapshot_claimed", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapDeleting { + t.Fatalf("delete s2 under the incomplete fork: %q %v; forks do not hold their parent", got, err) } if res, err := c.DeleteVolume(ctx, "w3", nil); err != nil || !res.Completed { t.Fatalf("delete w3: %+v %v", res, err) } - if _, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil { - t.Fatalf("delete s2 after w3 was deleted (its claim is dead): %v", err) + if got, err := c.DeleteSnapshot(ctx, "v1", "s2"); err != nil || got != SnapAbsent { + t.Fatalf("delete s2 again: %q %v; want absent", got, err) } } diff --git a/seaweed-block/core/host/volume/chunk_control_class_test.go b/seaweed-block/core/host/volume/chunk_control_class_test.go index 918ead3a02..89d333a9bc 100644 --- a/seaweed-block/core/host/volume/chunk_control_class_test.go +++ b/seaweed-block/core/host/volume/chunk_control_class_test.go @@ -29,9 +29,6 @@ func TestChunkControl_InvalidClassRefusedBeforeCut(t *testing.T) { t.Fatalf("%s maps to %d, want 400", code, s) } } - if s := catalogStatus(chunkstore.CodeSnapshotClaimed); s != http.StatusConflict { - t.Fatalf("snapshot_claimed maps to %d, want 409", s) - } info, err := ctl.Snapshot(ctx, "v1", ChunkSnapshotRequest{Name: "s1", RequestID: "r1", Class: chunkstore.SnapshotClassPinned}) if err != nil || info.Class != chunkstore.SnapshotClassPinned || fp.cuts != 1 { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..790fd99811 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -186,9 +186,10 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete - **Snapshot** (`Catalog.CreateSnapshot`): claim the name with an exclusive name record `{request, attempt}` (a retry gets its own attempt back); check the volume is not being deleted; write an intent with a deadline; re-check the deadline; exclusively create `snaps//` holding a copy of the HEAD root. An unknown outcome keeps the intent; the caller retries with the same request id. -- **Fork** (`Catalog.Fork`): claim the parent snapshot, check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. -- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; the claim is the fork's (live until the target has a HEAD), and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. An aborted first HEAD keeps the parent snapshot as `fork_parent` until the target is deleted. Model: `docs/spec/RestoreIndependence.tla`. -- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; a snapshot with a live fork claim is always kept; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Fork** (`Catalog.Fork`): take the deadline start and read the parent snapshot (every attempt reads it again; a parent deleting or gone refuses; the parent is not claimed), check the source is not being deleted, write the target `VOLUME` (origin fork), then a HEAD at gen 1, epoch 0, no holder, with the parent's `RemoteLSN` and references. No segment or chunk is copied: the fork's references are owner-qualified, so it reads the parent's objects, and its root alone keeps them live after the parent snapshot is deleted. +- **Restore** (`Catalog.Restore`, independent restore): the fork steps with `VOLUME` origin `restore`; until its first HEAD the parent stays rooted by GC's grace after any delete, and from then on the target's owner-qualified refs keep the source's chunks live, so deleting the source snapshot or volume mid-restore is normal. The background walker (`HydrateAll`) makes every chunk local through the shared fill flights, under one host fill permit per flight. Bounded batch cuts then upload the chunks under the target's own keys; when the resolved HEAD holds no ref to another volume, the write-once `RESTORE-INDEPENDENT` entry is created (`MarkIndependent`). Snapshots of the target are refused until then, and a snapshot image that still names another volume's chunks is refused even after it. Model: `docs/spec/RestoreIndependence.tla`. +- **Retention** (`retention.go`): classes `semantic` and `pinned`; newest N, recent window and log-spaced keeps; no snapshot is kept because of a fork or restore; deletion uses the same conditional mark as `DeleteSnapshot`. +- **Snapshot delete in any order with forks** (no claims): a fork publishes only before its read time + operation deadline, and GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector` refuses otherwise); an unknown publish keeps the fork intent, which roots the keys until the target is resolved. Model: `ForkDelete` (`G >= D + E + P`). - **GC** (`gc.go` `Collector.run`, operator-driven through `sw-block ops chunk gc`, preview by default; see also `core/frontend/chunkstore/GC.md`): - roots: every HEAD, every named snapshot (including one whose delete is still in progress), every snapshot attempt that is not aborted, live intents, and segment objects; an unreadable segment aborts the mark. A deleted snapshot's attempt stays a root for one grace period after its delete time, then stops counting (`Collector.snapshotAttemptHeads` in `gc_copy.go`); - a capture intent expires only if it is older than the TTL, blockmaster has issued a higher epoch, and the remote HEAD has moved to a higher epoch; copy intents are settled only by a permanent tombstone at their publication target; @@ -228,7 +229,7 @@ stateDiagram-v2 [*] --> NameHeld: exclusive name record {request, attempt} NameHeld --> Published: exclusive create snaps/name/attempt NameHeld --> Aborted: DeleteSnapshot or GC tombstones the attempt path - Published --> Deleting: DeleteSnapshot or retention (no live fork claim) + Published --> Deleting: DeleteSnapshot or retention (forks do not hold it) Deleting --> NameFreed: name record removed Aborted --> NameFreed: name record removed NameFreed --> [*] @@ -242,7 +243,7 @@ Restore (target volume): stateDiagram-v2 [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped - Claimed --> Aborted: GC tombstones the HEAD (parent kept as fork_parent) + Claimed --> Aborted: GC tombstones the HEAD Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] @@ -376,7 +377,7 @@ Not done yet: | Chunks and segments are write-once; keys are never rebound | `chunk_remote.go` `putObject`; `gc.go` tombstones | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | yes | | Intents are durable before the first upload and removed only after the CAS outcome is known | `captureLocked` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS`, `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | yes | | GC never deletes a chunk reachable from a HEAD, snapshot, attempt or intent, and deletes only after two graced marks | `gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | yes | -| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, never while a fork claim is live | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | yes | +| A published snapshot is removed only by `DeleteSnapshot` or retention for the planned attempt, in any order with forks (no claims) | `catalog.go` `DeleteSnapshot`; `retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestSnapshotDelete_DeleteDuringAForkInFlight` (`core/frontend/chunkstore/snapshot_delete_test.go`) | yes | | Volume delete commits only with no snapshot name records; past the commit point it is irreversible | `volume_delete.go` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne`, `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | Volume ids are never reused | `core/host/master/services.go`; `catalog.go` `EnsureVolume` | `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | yes | | A host serves and cuts only under a valid lease; a fenced guard never reopens | `workspace_lease.go` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`) | yes | diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..6c61a9147a 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -290,9 +290,9 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th |---|---|---|---|---| | — | name held | exclusive name record `{request, attempt}`; a retry with the same request id gets its own attempt back | `core/frontend/chunkstore/catalog.go` `CreateSnapshot`, `claimName` | `INV-SNAP-EXPLICIT-DELETE-001` | | name held | published | the volume is not being deleted; an intent with a deadline is written and the deadline is re-checked; exclusive create of the attempt path | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | deleting | `DeleteSnapshot` or retention for this attempt, never while a fork claim is live | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001` | -| published | fork | claim the parent snapshot, check the source is not being deleted, write the target `VOLUME`, then its HEAD; no chunk is copied | `core/frontend/chunkstore/catalog.go` `Fork`, `claimForkParent` | `INV-GC-REACHABLE-001` | -| published | restore | the fork steps with `VOLUME` origin `restore`: the claim is live until the target has a HEAD (the fork's semantics); after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-RESTORE-PARENT-HOLD-001` | +| published | deleting | `DeleteSnapshot` or retention for this attempt, whatever forks or restores read it (no claim is read); the mark records its delete time and GC keeps the attempt rooted for its grace | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `INV-SNAP-EXPLICIT-DELETE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | fork | take the deadline start, read the parent snapshot (every attempt reads it again; deleting or absent refuses), check the source is not being deleted, write the target `VOLUME`, then its HEAD only before start + deadline; no chunk is copied and the parent is not claimed | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent` | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | +| published | restore | the fork steps with `VOLUME` origin `restore`: until the first HEAD the parent stays rooted by GC's grace after any delete (the fork deadline bound), after that the target's owner-qualified refs keep the source's chunks live through GC rooting by owner, with the source snapshot and the source volume both gone; a replay onto a volume of the other origin is refused | `core/frontend/chunkstore/catalog.go` `Restore`, `fork`, `checkForkRecord`; `core/frontend/chunkstore/gc.go` `Collector.run` (qualified refs rooted by owner) | `INV-GC-REACHABLE-001`, `INV-SNAP-DELETE-ANY-ORDER-001` | | restore | independent | the write-once `RESTORE-INDEPENDENT` entry is created only on a live HEAD whose resolved image (segments and every chunk ref inside) holds no ref owned by another volume | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`, `ForeignRefs` | `INV-RESTORE-INDEPENDENT-001` | | restore (not independent) | name held | refused: `CreateSnapshot` on a restore volume needs the marker, and the supplied image itself must hold no foreign ref; a refused request leaves no name or attempt | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `INV-RESTORE-SNAPSHOT-001` | @@ -382,7 +382,7 @@ with a separate scope/config-bound mark. Incomplete marks carry no coverage. ## Part B. Invariant ledger -135 rows: 116 ACTIVE, 17 STUB, 2 ARCHIVED; 15 kept from the internal ledger, 120 new. +136 rows: 116 ACTIVE, 17 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 121 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. @@ -568,14 +568,15 @@ Notes: | `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-DELETE-PROGRESS-001` | A definite HTTP400 DELETE refusal cannot starve later eligible bindings or erase younger candidates' completed-mark coverage. The rejected fid stays in its immutable tombstone, is retried later and is never counted reclaimed. FailedDeletes reports the object; ExecuteGC saves the complete mark before returning partial failure. Other/unknown errors and cancellation remain pass failures. | M6 bound/tombstoned → physical reclamation | `core/frontend/chunkstore/gc.go` `run`; `gc_execution.go` `executeGC`; `swfs.go` `DeleteBlob` | `TestGCPermanentDeleteDoesNotStarveLaterBindings`, `TestSWFS_DeleteBlobStatusesAndExactPath` | `GCDeleteProgress` `NoFalseSuccess`, `FailureVisible`, `LaterProgress` | ACTIVE | | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | 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` | `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-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | 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_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) whatever forks or restores read it, in any order: no fork claim refuses or delays it. A fork reads its parent after taking its deadline start, every attempt (a retry included) reads it again, and it publishes only before start + deadline; GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound; an unknown publish keeps the fork intent, which roots the keys until the target is resolved. | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | 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 | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | | `INV-RESTORE-INDEPENDENT-001` | `RESTORE-INDEPENDENT` is written once, only for a restore volume with a live HEAD whose resolved image holds no ref owned by another volume; a restore without a live HEAD (absent or aborted) never attaches and is never marked. | M6 snapshot: restore → independent | `core/frontend/chunkstore/restore.go` `MarkIndependent`, `foreignRefsOf`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestRestore_MarkIndependentOnlyWithoutQualifiedRefs`, `TestRestore_WithoutLiveHeadNeverAttaches`, `TestRestore_SourceGoneIsNormal` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent`, `NoForeignList` | ACTIVE | | `INV-RESTORE-SNAPSHOT-001` | A snapshot of a restore volume is refused until it is independent, and the snapshot image itself must hold no ref owned by another volume (a cut saved before the marker is refused after it); a refused request leaves no name or attempt. | M6 snapshot: restore (not independent) → name held (refused) | `core/frontend/chunkstore/catalog.go` `CreateSnapshot` | `TestRestore_SnapshotsRefusedUntilIndependent`, `TestRestore_SnapshotOfAStalePreIndependenceImageRefused` (`core/frontend/chunkstore/restore_test.go`) | `RestoreIndependence` `Independent` (`red_snap_during_restore`) | ACTIVE | -| `INV-RESTORE-PARENT-HOLD-001` | A restore target with an aborted first HEAD no longer has a live fork claim (any HEAD ends the claim), but retention still keeps the parent snapshot as `fork_parent` (the fork-record scan treats an aborted HEAD as no HEAD) until the target volume is deleted. | M6 snapshot: published (parent of an aborted restore) | `core/frontend/chunkstore/retention.go` `liveClaims`, `forkParentsNeeded` | `TestRestore_AbortedFirstHeadKeepsTheParentUntilTheTargetIsDeleted` (`core/frontend/chunkstore/restore_test.go`) | — (Go only: the model's `ClaimUntilHead` does not cover retention of an aborted target) | ACTIVE | +| `INV-RESTORE-PARENT-HOLD-001` | Retired: retention no longer keeps a snapshot because of a fork or restore (`INV-SNAP-DELETE-ANY-ORDER-001`). | — | — | — | — | ARCHIVED | | `INV-RESTORE-HYDRATE-001` | The background hydrate walker fills only through the shared fill flights (one fetch per chunk, never over a local write), yields while a guest waits, and holds one host fill permit (no cut payload, the caller's class) per flight until that flight's I/O is over, also when it returns early on cancel or revocation. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `startWalkerFill`, `admitFill` | `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld` (`core/storage/chunk_hydrate_all_test.go`) | — | ACTIVE | | `INV-CAT-INTENT-DROP-BOUNDED-001` | Dropping an operation's intent outlives the caller's cancellation (cleanup after a refused or cancelled request) but is bounded by `dropIntentTimeout`; a failed or timed-out delete leaves the intent, which only over-protects. | M6 intent: Live → Removed | `core/frontend/chunkstore/catalog.go` `dropIntent` | `TestCatalog_DropIntentIsBoundedAfterTheCallerIsCancelled` (`core/frontend/chunkstore/restore_test.go`) | — | ACTIVE | From 6687234a0d6b512017a2abac1e51ab02f2adf63d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:09:00 -0800 Subject: [PATCH 02/25] blockvolume: --chunk-dirty-threshold is deprecated and ignored (cuts stage by the copy-on-write budget); warn at start, removal after 2027-01-31 Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 12 +++---- .../cmd/blockvolume/chunk_remote_test.go | 35 +++++++++++++++---- seaweed-block/cmd/blockvolume/main.go | 14 +++++--- .../core/frontend/durable/provider.go | 7 ---- .../core/frontend/durable/provider_chunk.go | 1 - .../durable/provider_chunk_sched_test.go | 15 ++++---- .../provider_initial_memory_linux_test.go | 6 ---- .../durable/provider_maintenance_test.go | 2 +- seaweed-block/deploy/config/blockvolume.env | 3 -- .../systemd/sw-blockvolume-ublk.service | 1 - .../deploy/systemd/sw-blockvolume.service | 1 - .../docs/design/agent-workspace-design.md | 4 +-- seaweed-block/docs/standalone-deployment.md | 3 +- 13 files changed, 56 insertions(+), 48 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 7bc5d5eb20..1bc51d1c8d 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -29,9 +29,12 @@ const ( defaultChunkMaintenanceTimeout = time.Minute defaultChunkGCGrace = time.Hour defaultChunkIntentTTL = time.Hour - defaultChunkDirtyThreshold = 512 // chunks, 2 GiB at 4 MiB chunks ) +// chunkDirtyThresholdRemoval is when --chunk-dirty-threshold, accepted and +// ignored since cuts stage by the COW budget (M5 Stage), is removed. +const chunkDirtyThresholdRemoval = "2027-01-31" + type chunkFlags struct { detachPrecopy bool hostLimit hostlimit.Config @@ -42,7 +45,7 @@ type chunkFlags struct { captureInterval time.Duration maintenanceInterval time.Duration automaticGC bool - dirtyThreshold int + dirtyThreshold int // deprecated, ignored (chunkDirtyThresholdRemoval) uploadConcurrency int hydrationWorkers int hydrationQueueDepth int @@ -61,7 +64,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.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || c.dirtyThreshold != defaultChunkDirtyThreshold || + c.captureInterval != defaultChunkCaptureInterval || c.maintenanceInterval != defaultChunkMaintenanceInterval || c.automaticGC || 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") } @@ -100,9 +103,6 @@ func validateChunkFlags(f flags) error { if c.hydrationQueueDepth < 1 || c.hydrationQueueDepth > 65536 { return errors.New("--chunk-hydration-queue-depth must be between 1 and 65536") } - if c.dirtyThreshold < 0 { - return fmt.Errorf("--chunk-dirty-threshold=%d must not be negative", c.dirtyThreshold) - } return nil } diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index c885307e7c..51dd5615ae 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -31,13 +31,13 @@ func TestWALStoreChunkFlags(t *testing.T) { if err != nil { t.Fatal(err) } - 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) + if d.chunk.captureInterval != 15*time.Minute || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC || len(d.warnings) != 0 { + t.Fatalf("scheduler defaults interval %s warnings %v, want capture 15m, maintenance 1h, GC off and no warning", d.chunk.captureInterval, d.warnings) } 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")) - if err != nil || off.chunk.captureInterval != 0 || off.chunk.dirtyThreshold != 0 { - t.Fatalf("disabling both triggers: %+v %v", off.chunk, err) + "--chunk-capture-interval=0")) + if err != nil || off.chunk.captureInterval != 0 { + t.Fatalf("disabling the timer: %+v %v", off.chunk, err) } if _, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore")); err != nil { t.Fatalf("walstore with the chunk defaults untouched: %v", err) @@ -58,8 +58,6 @@ func TestWALStoreChunkFlags(t *testing.T) { "--chunk-filer=x:1", "--chunk-control-endpoint"), "zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"), "too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"), - "negative threshold": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), - "threshold on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), "interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"), } for name, args := range refused { @@ -123,3 +121,26 @@ func TestChunkHolderIsServerAndReplica(t *testing.T) { t.Fatalf("chunk holder %q, want m02/r1", got) } } + +// --chunk-dirty-threshold is deprecated (O-OPS-1): a cut stages by the +// copy-on-write budget (M5 Stage), so the flag never had an effect. It is +// still accepted, with any value and any durable implementation, and warns +// with its removal date; nothing reads its value. +func TestChunkDirtyThresholdIsDeprecatedAndIgnored(t *testing.T) { + base := func(extra ...string) []string { + return append(phase150RequiredBlockvolumeArgs(), extra...) + } + for _, args := range [][]string{ + base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=512"), + base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), + base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), + } { + f, err := parseFlags(args) + if err != nil { + t.Fatalf("%v: refused: %v", args, err) + } + if len(f.warnings) != 1 || !strings.Contains(f.warnings[0], "deprecated") || !strings.Contains(f.warnings[0], chunkDirtyThresholdRemoval) { + t.Fatalf("%v: warnings %v; want one deprecation warning naming %s", args, f.warnings, chunkDirtyThresholdRemoval) + } + } +} diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 394ef1d974..2fcf691f2c 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -42,6 +42,7 @@ import ( ) type flags struct { + warnings []string // printed at start (deprecated flags) cpuProfileDir string memoryLimitMiB int64 masterAddr string @@ -209,7 +210,7 @@ func parseFlags(args []string) (flags, error) { 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)") - fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", defaultChunkDirtyThreshold, "walstore-chunk: number of candidate chunks above which a cut pre-copies (stages) chunks before its barrier, in rounds of this size; copy-before-write copies the rest outside the barrier; never triggers a cut; 0 = no pre-copy") + fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", 0, "deprecated and ignored: a cut stages by the copy-on-write budget, not a chunk count; removed after "+chunkDirtyThresholdRemoval) fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") @@ -251,9 +252,12 @@ func parseFlags(args []string) (flags, error) { return flags{}, err } memoryFlagSet := false - fs.Visit(func(f *flag.Flag) { - if f.Name == "memory-limit-mib" { + fs.Visit(func(fl *flag.Flag) { + switch fl.Name { + case "memory-limit-mib": memoryFlagSet = true + case "chunk-dirty-threshold": + f.warnings = append(f.warnings, "--chunk-dirty-threshold is deprecated and has no effect (a cut stages by the copy-on-write budget); it is removed after "+chunkDirtyThresholdRemoval) } }) if !memoryFlagSet && os.Getenv("GOMEMLIMIT") != "" { @@ -584,6 +588,9 @@ func durableCreateGeometry(f flags) (uint32, int, error) { } func run(f flags) int { + for _, w := range f.warnings { + fmt.Fprintln(os.Stderr, "blockvolume: warning:", w) + } // Diagnostics first: parseFlags validated the directory, and nothing // has been activated yet, so a failure here leaves nothing to clean up. stopProfile, err := startCPUProfileSignal(f.cpuProfileDir) @@ -667,7 +674,6 @@ func run(f flags) int { cfg.ChunkMaintenanceTimeout = defaultChunkMaintenanceTimeout cfg.ChunkMaintenance = chunk.maintenance cfg.ChunkDetachPrecopy = f.chunk.detachPrecopy - cfg.ChunkDirtyThreshold = f.chunk.dirtyThreshold cfg.ChunkUploadConcurrency = f.chunk.uploadConcurrency cfg.ChunkHydrationWorkers = f.chunk.hydrationWorkers cfg.ChunkHydrationQueueDepth = f.chunk.hydrationQueueDepth diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 55eb72554b..4c3b3607eb 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -199,13 +199,6 @@ type ProviderConfig struct { // call back into the provider. OnChunkDetach func(volumeID string) uint64 OnChunkDetachResumed func(volumeID string, attempt uint64) - // ChunkDirtyThreshold is the number of candidate chunks above which - // a cut pre-copies (stages) chunks before its barrier, in rounds of - // this size; copy-before-write copies the rest outside the barrier. - // It never triggers a cut: the remote holds snapshots, and cuts are - // published only by CaptureVolume, MakeVolumeRemoteDurable - // (snapshot, detach) and the timer. Zero: no pre-copy. - ChunkDirtyThreshold int // ChunkUploadConcurrency bounds remote uploads; zero defaults to 8. ChunkUploadConcurrency int // ChunkPayloadMemoryBudget bounds one volume's cut payloads; zero uses the storage default. diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 2bc76b8324..2c194a39e8 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -385,7 +385,6 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h ReadMissTimeout: p.cfg.ChunkReadMissTimeout, HydrationWorkers: p.cfg.ChunkHydrationWorkers, HydrationQueueDepth: p.cfg.ChunkHydrationQueueDepth, - BarrierBound: p.cfg.ChunkDirtyThreshold, UploadConcurrency: p.cfg.ChunkUploadConcurrency, PayloadMemoryBudget: p.cfg.ChunkPayloadMemoryBudget, Budget: p.cfg.ChunkBudget, diff --git a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go index 795a399f9b..bbea2993a2 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_sched_test.go @@ -14,13 +14,12 @@ import ( "github.com/seaweedfs/seaweed-block/core/storage" ) -func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration, threshold int) *durable.DurableProvider { +func schedProvider(t *testing.T, remote storage.ChunkRemote, interval time.Duration) *durable.DurableProvider { t.Helper() p, err := durable.NewDurableProvider(durable.ProviderConfig{ Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, ChunkCaptureInterval: interval, - ChunkDirtyThreshold: threshold, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, }, v1View()) if err != nil { @@ -40,12 +39,12 @@ func headGen(t *testing.T, remote storage.ChunkRemote) storage.ChunkHead { } // The remote holds snapshots: with the timer off, no number of dirty -// chunks publishes a cut on its own (the threshold only bounds a cut). -func TestWALStoreChunk_DirtyThresholdNeverTriggersCut(t *testing.T) { +// chunks publishes a cut on its own. +func TestWALStoreChunk_DirtyChunksNeverTriggerCut(t *testing.T) { remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, 0, 2) + p := schedProvider(t, remote, 0) s := openRecovered(t, p) - for c := uint32(0); c < 4; c++ { // four dirty chunks, twice the threshold + for c := uint32(0); c < 4; c++ { // four dirty chunks if _, err := s.Write(c*pcChunkBlocks+1, block(byte(c+1))); err != nil { t.Fatal(err) } @@ -71,7 +70,7 @@ func TestWALStoreChunk_DirtyThresholdNeverTriggersCut(t *testing.T) { func TestWALStoreChunk_ExplicitCutRestartsTheTimer(t *testing.T) { const interval = 3 * time.Second remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, interval, 0) + p := schedProvider(t, remote, interval) s := openRecovered(t, p) begin := time.Now() @@ -204,7 +203,7 @@ func TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt(t *testing.T) { var releaseOnce sync.Once release := func() { releaseOnce.Do(func() { close(remote.release) }) } t.Cleanup(release) - p := schedProvider(t, remote, interval, 0) + p := schedProvider(t, remote, interval) events := make(chan loopEvent, 64) durable.SetTestChunkLoopTrace(p, func(event string, lastCutNs int64, skipped bool) { select { diff --git a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go index a4c3945460..5fd481e6d3 100644 --- a/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go +++ b/seaweed-block/core/frontend/durable/provider_initial_memory_linux_test.go @@ -47,9 +47,6 @@ func TestWALStoreChunk_LedgerWriteAnonymousMemory(t *testing.T) { defer cancel() r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} - if os.Getenv("SWBLOCK_MEMORY_STAGE") != "" { - cfg.ChunkDirtyThreshold = 64 - } p, err := durable.NewDurableProvider(cfg, v1View()) if err != nil { t.Fatal(err) @@ -243,9 +240,6 @@ func TestWALStoreChunk_InitialWriteAnonymousMemory(t *testing.T) { defer cancel() r := &memoryDiskRemote{MemChunkRemote: storage.NewMemChunkRemote(), dir: t.TempDir(), hashes: make(map[string][32]byte)} cfg := durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 1 << 18, ChunkBlocks: 1024, ChunkCaptureInterval: 0, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return r, nil }} - if os.Getenv("SWBLOCK_MEMORY_STAGE") != "" { - cfg.ChunkDirtyThreshold = 64 - } if raw := os.Getenv("SWBLOCK_MEMORY_CHUNKS"); raw != "" { chunks, e := strconv.Atoi(raw) if e != nil || chunks <= 0 { diff --git a/seaweed-block/core/frontend/durable/provider_maintenance_test.go b/seaweed-block/core/frontend/durable/provider_maintenance_test.go index 68f60a64c6..1f38b998b2 100644 --- a/seaweed-block/core/frontend/durable/provider_maintenance_test.go +++ b/seaweed-block/core/frontend/durable/provider_maintenance_test.go @@ -256,7 +256,7 @@ func TestMaintenanceCoalescesWhileOnePassIsHeld(t *testing.T) { func TestMaintenancePeriodicNoopDoesNotChurnHead(t *testing.T) { remote := storage.NewMemChunkRemote() - p := schedProvider(t, remote, time.Millisecond, 0) + p := schedProvider(t, remote, time.Millisecond) s := openRecovered(t, p) lsn, err := s.Write(1, block(0x91)) if err != nil { diff --git a/seaweed-block/deploy/config/blockvolume.env b/seaweed-block/deploy/config/blockvolume.env index cce3021c5c..a40f5f7c7f 100644 --- a/seaweed-block/deploy/config/blockvolume.env +++ b/seaweed-block/deploy/config/blockvolume.env @@ -113,9 +113,6 @@ SWB_CHUNK_REPLICATION= SWB_CHUNK_CAPTURE_INTERVAL=0 # --chunk-upload-concurrency (default 8; 1..64). Parallel dirty-chunk uploads. SWB_CHUNK_UPLOAD_CONCURRENCY=8 -# --chunk-dirty-threshold (default 512 chunks = 2 GiB; 0 = unbounded). Bound -# on one cut's barrier copy; never triggers a cut. -SWB_CHUNK_DIRTY_THRESHOLD=512 # --chunk-control-endpoint (default false). Expose /chunk/* (cut, snapshot, # snapshots, snapshot/delete, detach) on the status listener; needs # SWB_STATUS_ADDR. diff --git a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service index 37fdd5fb1a..c15dcbb0a2 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume-ublk.service @@ -60,7 +60,6 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ - --chunk-dirty-threshold=${SWB_CHUNK_DIRTY_THRESHOLD} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ $SWB_VOLUME_EXTRA_ARGS diff --git a/seaweed-block/deploy/systemd/sw-blockvolume.service b/seaweed-block/deploy/systemd/sw-blockvolume.service index a17b9d7980..28675f37ce 100644 --- a/seaweed-block/deploy/systemd/sw-blockvolume.service +++ b/seaweed-block/deploy/systemd/sw-blockvolume.service @@ -59,7 +59,6 @@ ExecStart=/usr/local/bin/blockvolume \ --chunk-replication=${SWB_CHUNK_REPLICATION} \ --chunk-capture-interval=${SWB_CHUNK_CAPTURE_INTERVAL} \ --chunk-upload-concurrency=${SWB_CHUNK_UPLOAD_CONCURRENCY} \ - --chunk-dirty-threshold=${SWB_CHUNK_DIRTY_THRESHOLD} \ --chunk-control-endpoint=${SWB_CHUNK_CONTROL_ENDPOINT} \ --workspace-lease=${SWB_WORKSPACE_LEASE} \ $SWB_VOLUME_EXTRA_ARGS diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..6aabd7faef 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -72,7 +72,7 @@ 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, 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. +- **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. Dirty chunks never trigger 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. @@ -122,7 +122,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `chunkLayerImpl.captureLocked` (`core/storage/chunk_layer.go`; contract in the `chunk_seam.go` header). A checkpoint is not a prefix image (the extent can already hold blocks newer than the checkpoint), so a cut is a quiesced point, not a checkpoint boundary. 1. **Admit:** refuse when closed, fenced, detached, during a base install, or when `CaptureAllowed` fails (healthy primary, unchanged lineage, valid lease). -2. **Pre-copy:** while more than `BarrierBound` chunks would be copied under the barrier (`--chunk-dirty-threshold`, default 512), stage up to that many per round outside the barrier, for at most `chunkStageRounds` (3) rounds (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. +2. **Pre-copy:** while the chunks that would be copied under the barrier exceed half the copy-on-write side budget, stage the hottest of them per round outside the barrier, repeating only while the remainder shrinks (`stage`). The deprecated `--chunk-dirty-threshold` has no effect here. A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. 3. **Quiesce:** take the capture barrier (walstore `captureMu`) exclusively, then `Sync`. H is the synced LSN; no data newer than H exists in the WAL or the extent. 4. **Open and copy:** install the fixed candidate window under the barrier, then release it. Bounded workers copy through the validated reader outside the barrier. A first writer saves a pending candidate before mutation; a writer waits only for its own copying/saving chunk. A staged copy is reused only if its version and HEAD still match. Pause is Sync plus candidate/window installation, independent of copy bytes. 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index c2c8f5abb4..ef83e8b124 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -124,11 +124,12 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_CHUNK_COLLECTION`, `SWB_CHUNK_REPLICATION` | `--chunk-collection`, `--chunk-replication` | empty (filer default) | Placement of chunk needles | | `SWB_CHUNK_CAPTURE_INTERVAL` | `--chunk-capture-interval` | `0` (no timer) | Automatic cut interval, e.g. `15m` | | `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) | -| `SWB_CHUNK_DIRTY_THRESHOLD` | `--chunk-dirty-threshold` | `512` | Bound on one cut's barrier copy, in chunks | | `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener | | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | | `SWB_VOLUME_EXTRA_ARGS` | any | empty | Other flags (Kubernetes gate and source-gated flags) | +`--chunk-dirty-threshold` (and `SWB_CHUNK_DIRTY_THRESHOLD`) is deprecated and ignored: a cut stages by its copy-on-write budget, not a chunk count. It is still accepted with a startup warning, and it is removed after 2027-01-31. + The `--chunk-*` and `--workspace-lease` flags are refused unless `--durable-impl=walstore-chunk`; leave them at their defaults otherwise. From f676da0424398b74710970f17a64d84ecc8bc8c2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:09:29 -0800 Subject: [PATCH 03/25] docs: condense INV-SNAP-DELETE-ANY-ORDER-001 (statement <= 300 chars, detail in the notes) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 6c61a9147a..e826296eca 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -570,7 +570,7 @@ Notes: | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | 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_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) whatever forks or restores read it, in any order: no fork claim refuses or delays it. A fork reads its parent after taking its deadline start, every attempt (a retry included) reads it again, and it publishes only before start + deadline; GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound; an unknown publish keeps the fork intent, which roots the keys until the target is resolved. | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | 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 | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | @@ -582,6 +582,7 @@ Notes: Notes: +- `INV-SNAP-DELETE-ANY-ORDER-001`: a fork takes its deadline start before it reads the parent, and every attempt (a retry included) reads it again, so a parent deleted before the read refuses. GC keeps a deleted attempt rooted for a grace of at least deadline + clock skew + CAS apply bound (`NewCollector`). An unknown publish keeps the fork intent, which roots the keys until the target is resolved. ### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing From 0ef32a75c7d28a5104a319a4f24d9f097c8aa0a0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:15:00 -0800 Subject: [PATCH 04/25] sw-block: ops chunk commands that write chunk metadata run the single-filer start check (O-ENG-4) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 41 +++++++++++-- seaweed-block/cmd/sw-block/chunk_gc.go | 5 ++ seaweed-block/cmd/sw-block/chunk_retain.go | 4 +- .../cmd/sw-block/chunk_start_check_test.go | 60 +++++++++++++++++++ .../cmd/sw-block/chunk_volume_delete.go | 2 +- 5 files changed, 104 insertions(+), 8 deletions(-) create mode 100644 seaweed-block/cmd/sw-block/chunk_start_check_test.go diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 80cc5f67ad..46411e71e4 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -42,6 +42,29 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { return c, c.Close, nil } +// checkSingleFiler is the start check of a command that writes chunk +// metadata (O-ENG-4): block metadata goes through exactly one filer, the +// same rule blockvolume enforces at start. Tests replace it. +var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { + if s, ok := f.(*chunkstore.SWFS); ok { + return s.CheckSingleFiler(ctx) + } + return nil +} + +// refuseUnlessSingleFiler runs the start check; exit >= 0 means refused. +func refuseUnlessSingleFiler(name string, f chunkstore.Filer, stdout, stderr io.Writer) int { + err := checkSingleFiler(context.Background(), f) + switch { + case err == nil: + return -1 + case errors.Is(err, chunkstore.ErrNotSingleFiler): + return chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) + default: + return chunkFail(name, stdout, stderr, chunkExitFailed, codeUnavailableCLI, "single-filer start check: "+err.Error(), true) + } +} + 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) @@ -259,7 +282,9 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { // chunkCatalog opens the catalog under --chunk-path on --chunk-filer. // It returns exit -1 on success, else the exit code after reporting. -func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { +// chunkCatalog dials the filer and opens the catalog; a command that writes +// (writes) first passes the single-filer start check. +func chunkCatalog(name, filer, base string, writes bool, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } @@ -267,6 +292,12 @@ func chunkCatalog(name, filer, base string, stdout, stderr io.Writer) (*chunksto if err != nil { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } + if writes { + if exit := refuseUnlessSingleFiler(name, f, stdout, stderr); exit >= 0 { + _ = closeFn() + return nil, nil, exit + } + } cat, err := chunkstore.NewCatalog(f, base) if err != nil { _ = closeFn() @@ -364,7 +395,7 @@ func chunkSnapshots(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("snapshots", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, stdout, stderr) if exit >= 0 { return exit } @@ -392,7 +423,7 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || name == "" { return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false) } - cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, stdout, stderr) if exit >= 0 { return exit } @@ -428,7 +459,7 @@ func chunkFork(args []string, stdout, stderr io.Writer) int { requestID = newRequestID() fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) } - cat, closeFn, exit := chunkCatalog("fork", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("fork", filer, base, true, stdout, stderr) if exit >= 0 { return exit } @@ -456,7 +487,7 @@ func chunkShow(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("show", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("show", filer, base, false, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index a5a8cdfc61..b802d26e68 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -41,6 +41,11 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { return chunkResult("gc", nil, e, stdout, stderr) } defer closeFn() + if apply { + if exit := refuseUnlessSingleFiler("gc", f, stdout, stderr); exit >= 0 { + return exit + } + } blobs, ok := f.(chunkstore.BlobDeleter) if !ok { return chunkFail("gc", stdout, stderr, chunkExitFailed, codeInternalCLI, "chunk store cannot delete immutable blobs", false) diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index 7b9702672c..34246710c3 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -31,7 +31,7 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("usage", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("usage", filer, base, false, stdout, stderr) if exit >= 0 { return exit } @@ -74,7 +74,7 @@ func chunkRetain(args []string, stdout, stderr io.Writer) int { if setPolicy && dryRun { return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) } - cat, closeFn, exit := chunkCatalog("retain", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go new file mode 100644 index 0000000000..605bde12a9 --- /dev/null +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -0,0 +1,60 @@ +package main + +import ( + "bytes" + "context" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" +) + +// O-ENG-4: every ops chunk command that writes chunk metadata runs the +// single-filer start check before it reads or writes anything, and refuses +// when the filer is not the only one of its group; read-only commands (and +// read-only modes) do not run it. +func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checks := 0 + checkSingleFiler = func(context.Context, chunkstore.Filer) error { + checks++ + return chunkstore.ErrNotSingleFiler + } + filer := []string{"--chunk-filer", "filer:18888"} + writing := map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), + "fork": append([]string{"ops", "chunk", "fork", "--source", "v1", "--snapshot", "s1", "--target", "v2", "--request-id", "r"}, filer...), + "retain": append([]string{"ops", "chunk", "retain", "--volume", "v1"}, filer...), + "volume-delete": append([]string{"ops", "chunk", "volume-delete", "--volume", "v1", "--master", "m:1", "--request-id", "r"}, filer...), + "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + } + for name, args := range writing { + before := checks + var out, errb bytes.Buffer + code := run(args, &out, &errb) + if checks != before+1 { + t.Errorf("%s: start check ran %d times; want once", name, checks-before) + } + if code == 0 || !strings.Contains(out.String()+errb.String(), "exactly one filer") { + t.Errorf("%s: exit %d, out %q err %q; want the single-filer refusal", name, code, out.String(), errb.String()) + } + } + readOnly := map[string][]string{ + "snapshots": append([]string{"ops", "chunk", "snapshots", "--volume", "v1"}, filer...), + "show": append([]string{"ops", "chunk", "show", "--volume", "v1"}, filer...), + "usage": append([]string{"ops", "chunk", "usage", "--volume", "v1"}, filer...), + "retain --dry-run": append([]string{"ops", "chunk", "retain", "--volume", "v1", "--dry-run"}, filer...), + "gc (read-only)": append([]string{"ops", "chunk", "gc", "--master", "m:1"}, filer...), + } + for name, args := range readOnly { + before := checks + var out, errb bytes.Buffer + run(args, &out, &errb) + if checks != before { + t.Errorf("%s: a read-only command ran the start check", name) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 52e05da0cc..9054369431 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -46,7 +46,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) } - cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, stdout, stderr) + cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, stdout, stderr) if exit >= 0 { return exit } From e3a06ab435f0100b6a92eb0454c1c8ce3dc7945e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:18:09 -0800 Subject: [PATCH 05/25] invariants: INV-WS-SINGLE-FILER-001 names the ops chunk enforcement and its test Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index ba83dc3ba6..1f40a16a20 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -501,7 +501,7 @@ Notes: | `INV-WS-CAS-UNKNOWN-001` | An unknown HEAD CAS outcome is settled by re-reading HEAD, never by a blind retry; until it is settled the proposal stays pending and its intents stay. | M5 CAS → Pending | `core/storage/chunk_layer.go` `captureLocked`, `resolvePending`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestChunkRemote_UncertainCASIsNotPrecondition` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_UnknownNotAppliedNeverClaimsSuccess` (`core/storage/chunk_layer_contract_test.go`); `TestClaimChunkHeadSettlesUnknownWithoutReplay` (`core/storage/chunk_restore_test.go`); `TestChunkIntent_UncertainCASKeepsIntentUntilSettled` (`core/storage/chunk_layer_intent_test.go`) | — | ACTIVE | | `INV-WS-CLAIM-BEFORE-SERVE-001` | A new holder claims HEAD at its master-issued epoch before I/O opens; a HEAD with a higher epoch, or another holder at the same epoch, fences the claim. | M4 Claiming → Holder \| Fenced | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestClaimChunkHeadRefusesStaleAuthorityAndAdmissionDrift` (`core/storage/chunk_restore_test.go`); `TestRestoreSeedPrecedesTakeoverCAS` (`core/frontend/durable/provider_seed_order_test.go`); `TestWorkspaceMoveRestoresLazilyAndFencesOldHost` (`core/host/master/workspace_restore_test.go`) | `WorkspaceTakeover` `SeedMatchesTakeover` | ACTIVE | | `INV-WS-STALE-LOCAL-ROOT-001` | An existing local root whose HEAD another holder has published is not served or cut; the attach fails closed with `ErrChunkStaleLocalRoot`. | M4 Claiming → Refused | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused`, `TestWALStoreChunk_MoveBackRefusedOnDeferredAttach` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`) | — | ACTIVE | +| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`) | — | ACTIVE | | `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE | | `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | | `INV-WS-STOP-PENDING-001` | Stop-pending changes only when the lease guard renews, never what it admits or acknowledges: from the start of a chunk detach until the guard fences, its sleep after a completed renewal is at most 250 ms; it returns to the normal renewal delay only when that same (latest) detach attempt provably did not happen and serving resumed. It bounds scheduling, not the time from a revocation to its acknowledgement. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/frontend/durable/provider_chunk.go` `DetachVolume`, `resumeAfterDetach`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay` | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE | @@ -512,6 +512,7 @@ Notes: Notes: +- `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply) before it reads or writes; read-only commands and modes do not run it. - `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary. - `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits). - `INV-WS-FORCED-MOVE-001`: TLA+: `W4_drift` found the gap before #158; the skew margin itself is not in the model. Extended for a new holder that dies between its grant and its HEAD claim: the move issue starts its lease, admission uses that grant's lease, HEAD is read after admission, an older-epoch HEAD is accepted (its generation and remote LSN may have moved by an earlier holder's late claim), and a returning holder is refused by two fences, its lease-gated attach and the higher HEAD epoch. `WorkspaceTakeover` models one move from A to B and does not cover a second move away from an unclaimed grant; that model check is open and not claimed here. From 8fb359c7a39b753f9009988f5de1d29be69c880b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:21:08 -0800 Subject: [PATCH 06/25] WIP status schema (O-OPS-2) --- .../core/host/volume/status_schema_test.go | 267 ++++++++++++ seaweed-block/docs/status-schema.md | 402 ++++++++++++++++++ 2 files changed, 669 insertions(+) create mode 100644 seaweed-block/core/host/volume/status_schema_test.go create mode 100644 seaweed-block/docs/status-schema.md diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go new file mode 100644 index 0000000000..89447cb761 --- /dev/null +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -0,0 +1,267 @@ +package volume + +import ( + "fmt" + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "reflect" + "sort" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/engine" + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/replication" +) + +// statusRoutes are the status routes and the type each one encodes. The +// anonymous bodies of /status/peers and /status/durable are restated here +// field for field; TestStatusBodiesMatchTheRoutes checks they still match. +var statusRoutes = []struct { + route, note string + typ reflect.Type +}{ + {"/status", "the volume's authority and health projection", reflect.TypeOf(StatusProjection{})}, + {"/status/peers", "replication peers of the served volume", reflect.TypeOf(peersStatusBody{})}, + {"/status/durable", "durable store state of the served volume", reflect.TypeOf(durableStatusBody{})}, + {"/status/recovery", "the engine's replica projection (only with recovery enabled)", reflect.TypeOf(engine.ReplicaProjection{})}, + {"/status/chunk", "chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint)", reflect.TypeOf(chunkstore.VolumeUsage{})}, + {"/status/nvme", "NVMe/TCP frontend counters", reflect.TypeOf(NVMeStatus{})}, + {"/status/ublk", "ublk frontend counters", reflect.TypeOf(UblkStatus{})}, + {"/status/frontend-capabilities", "the frontends this host can serve", reflect.TypeOf(FrontendCapabilitiesStatus{})}, +} + +type peersStatusBody struct { + VolumeID string + ReplicaID string + PeerCount int + Peers []replication.ReplicaPeerStatus +} + +type durableStatusBody struct { + VolumeID string + ReplicaID string + VolumeCount int + Volumes []durable.VolumeStatus +} + +const ( + statusSchemaDoc = "../../../docs/status-schema.md" + statusSchemaBegin = "" + statusSchemaEnd = "" + modulePath = "github.com/seaweedfs/seaweed-block/" +) + +// fieldDocs maps "pkgpath.Type.Field" to the field's doc or line comment. +type fieldDocs map[string]string + +func (d fieldDocs) load(t *testing.T, pkgPath string) { + t.Helper() + if !strings.HasPrefix(pkgPath, modulePath) { + return + } + if _, done := d["pkg:"+pkgPath]; done { + return + } + d["pkg:"+pkgPath] = "" + dir := filepath.Join("..", "..", "..", strings.TrimPrefix(pkgPath, modulePath)) + fset := token.NewFileSet() + pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, parser.ParseComments) + if err != nil { + t.Fatalf("parse %s: %v", dir, err) + } + for _, p := range pkgs { + for _, f := range p.Files { + ast.Inspect(f, func(n ast.Node) bool { + ts, ok := n.(*ast.TypeSpec) + if !ok { + return true + } + st, ok := ts.Type.(*ast.StructType) + if !ok { + return true + } + for _, fl := range st.Fields.List { + text := "" + if fl.Doc != nil { + text = fl.Doc.Text() + } else if fl.Comment != nil { + text = fl.Comment.Text() + } + text = strings.Join(strings.Fields(text), " ") + for _, name := range fl.Names { + d[pkgPath+"."+ts.Name.Name+"."+name.Name] = text + } + } + return true + }) + } + } +} + +// schemaRows walks t's JSON fields; prefix is the dotted JSON path so far. +func schemaRows(t *testing.T, docs fieldDocs, typ reflect.Type, prefix string, seen map[reflect.Type]bool, rows *[]string) { + for typ.Kind() == reflect.Pointer { + typ = typ.Elem() + } + if typ.Kind() != reflect.Struct || seen[typ] { + return + } + seen[typ] = true + defer delete(seen, typ) + docs.load(t, typ.PkgPath()) + for i := 0; i < typ.NumField(); i++ { + f := typ.Field(i) + if !f.IsExported() { + continue + } + tag := f.Tag.Get("json") + if tag == "-" { + continue + } + name, opts, _ := strings.Cut(tag, ",") + if f.Anonymous && name == "" { + schemaRows(t, docs, f.Type, prefix, seen, rows) + continue + } + if name == "" { + name = f.Name + } + path := name + if prefix != "" { + path = prefix + "." + name + } + ft, suffix := f.Type, "" + for { + switch ft.Kind() { + case reflect.Pointer: + ft = ft.Elem() + continue + case reflect.Slice, reflect.Array: + if ft.Elem().Kind() != reflect.Uint8 { + ft, suffix = ft.Elem(), suffix+"[]" + continue + } + case reflect.Map: + ft, suffix = ft.Elem(), suffix+"{}" + continue + } + break + } + typeName := ft.Kind().String() + if ft.Kind() == reflect.Struct { + typeName = "object" + if ft.PkgPath() == "time" && ft.Name() == "Time" { + typeName = "time (RFC 3339)" + } + } else if ft.Name() != "" && ft.PkgPath() != "" { + typeName = ft.Name() + " (" + ft.Kind().String() + ")" + } + if f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.Uint8 { + typeName = "bytes (base64)" + } + desc := docs[typ.PkgPath()+"."+typ.Name()+"."+f.Name] + if desc == "" { + desc = "—" + } + if strings.Contains(opts, "omitempty") { + desc += " (omitted when empty)" + } + desc = strings.ReplaceAll(desc, "|", "\\|") + *rows = append(*rows, fmt.Sprintf("| `%s%s` | %s | %s |", path, suffix, typeName, desc)) + if ft.Kind() == reflect.Struct && !(ft.PkgPath() == "time" && ft.Name() == "Time") { + schemaRows(t, docs, ft, path+suffix, seen, rows) + } + } +} + +func generateStatusSchema(t *testing.T) string { + t.Helper() + docs := fieldDocs{} + var b strings.Builder + b.WriteString(statusSchemaBegin + "\n") + for _, r := range statusRoutes { + var rows []string + schemaRows(t, docs, r.typ, "", map[reflect.Type]bool{}, &rows) + fmt.Fprintf(&b, "\n### `GET %s`\n\n%s. Go type `%s`.\n\n| Field | Type | Meaning |\n|---|---|---|\n", r.route, upperFirst(r.note), r.typ.String()) + b.WriteString(strings.Join(rows, "\n") + "\n") + } + b.WriteString("\n" + statusSchemaEnd) + return b.String() +} + +func upperFirst(s string) string { + if s == "" { + return s + } + return strings.ToUpper(s[:1]) + s[1:] +} + +// The status schema document lists every field the status routes return, +// generated from the Go types and their field comments. A field added, +// removed or renamed without regenerating the document fails here. +func TestStatusSchemaDoc(t *testing.T) { + want := generateStatusSchema(t) + raw, err := os.ReadFile(statusSchemaDoc) + if err != nil { + t.Fatal(err) + } + doc := strings.ReplaceAll(string(raw), "\r\n", "\n") + i, j := strings.Index(doc, statusSchemaBegin), strings.Index(doc, statusSchemaEnd) + if i < 0 || j < i { + t.Fatalf("%s has no generated block", statusSchemaDoc) + } + got := doc[i : j+len(statusSchemaEnd)] + if got == want { + return + } + if os.Getenv("STATUS_SCHEMA_UPDATE") == "1" { + if err := os.WriteFile(statusSchemaDoc, []byte(doc[:i]+want+doc[j+len(statusSchemaEnd):]), 0o644); err != nil { + t.Fatal(err) + } + return + } + gl, wl := strings.Split(got, "\n"), strings.Split(want, "\n") + for k := 0; k < len(gl) || k < len(wl); k++ { + var g, w string + if k < len(gl) { + g = gl[k] + } + if k < len(wl) { + w = wl[k] + } + if g != w { + t.Fatalf("%s is out of date at line %d of the generated block:\n doc: %s\n code: %s\nregenerate with STATUS_SCHEMA_UPDATE=1", statusSchemaDoc, k+1, g, w) + } + } +} + +// The restated bodies of /status/peers and /status/durable keep the +// handlers' field names and types. +func TestStatusBodiesMatchTheRoutes(t *testing.T) { + fields := func(v any) []string { + var out []string + ty := reflect.TypeOf(v) + for i := 0; i < ty.NumField(); i++ { + out = append(out, ty.Field(i).Name+":"+ty.Field(i).Type.String()) + } + sort.Strings(out) + return out + } + src, err := os.ReadFile("status_server.go") + if err != nil { + t.Fatal(err) + } + s := string(src) + for _, f := range append(fields(peersStatusBody{}), fields(durableStatusBody{})...) { + name, typ, _ := strings.Cut(f, ":") + typ = strings.TrimPrefix(typ, "volume.") + if !strings.Contains(s, "\t\t"+name+" ") || !strings.Contains(s, typ) { + t.Errorf("status_server.go no longer declares body field %s %s", name, typ) + } + } +} diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md new file mode 100644 index 0000000000..beda34f23e --- /dev/null +++ b/seaweed-block/docs/status-schema.md @@ -0,0 +1,402 @@ +# Status schema + +The blockvolume status listener (`--status-addr`) serves JSON on the routes below. Each table lists every field a route returns: its JSON path (`[]` marks a list, `{}` a map), its type, and its meaning as the field's Go comment states it. A field marked `—` has no comment in the code yet. + +The tables are generated from the Go types, so they list exactly the fields that exist. `go test ./core/host/volume -run TestStatusSchemaDoc` fails when the code and this page disagree; `STATUS_SCHEMA_UPDATE=1` rewrites the generated block. + +All routes take `?volume=` and answer 404 for a volume this host does not serve. + + + +### `GET /status` + +The volume's authority and health projection. Go type `volume.StatusProjection`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | — | +| `ReplicaID` | string | — | +| `Epoch` | uint64 | — | +| `EndpointVersion` | uint64 | — | +| `Healthy` | bool | — | +| `Memory` | object | — | +| `Memory.HeapAllocBytes` | uint64 | — | +| `Memory.HeapInuseBytes` | uint64 | — | +| `Memory.HeapSysBytes` | uint64 | — | +| `Memory.HeapReleasedBytes` | uint64 | — | +| `Memory.SoftLimitBytes` | int64 | — | +| `Memory.RSSBytes` | uint64 | — | +| `Memory.AnonymousRSSBytes` | uint64 | — | +| `FrontendPrimaryReady` | bool | — | +| `AuthorityRole` | string | — | +| `ReplicationRole` | string | — | +| `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | +| `UnhealthyReason` | string | UnhealthyReason is the slot's explicit unhealthy report (#128 rule 6), the value its heartbeat carries; empty when healthy. (omitted when empty) | +| `CatchUp` | object | CatchUp shows a supporting replica's catch-up progress while it is not yet replica_ready; it is visible without being an alert. (omitted when empty) | +| `CatchUp.ElapsedMs` | int64 | ElapsedMs is the time since this replica was admitted as a supporting replica at its current epoch. | +| `CatchUp.LagLSN` | uint64 | LagLSN is the engine's H-R (primary head minus this replica's durable frontier) as last observed; 0 when unknown or caught up. | +| `Warnings[]` | string | Warnings are the durable store's typed recovery warnings (e.g. wal_hole_suspected, issue #51). Visible, not an alert: they do not change Healthy or the frontend's readiness. (omitted when empty) | + +### `GET /status/peers` + +Replication peers of the served volume. Go type `volume.peersStatusBody`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | — | +| `ReplicaID` | string | — | +| `PeerCount` | int | — | +| `Peers[]` | object | — | +| `Peers[].ReplicaID` | string | — | +| `Peers[].State` | string | — | +| `Peers[].Epoch` | uint64 | — | +| `Peers[].EndpointVersion` | uint64 | — | +| `Peers[].DataAddr` | string | — | +| `Peers[].CtrlAddr` | string | — | +| `Peers[].SessionID` | uint64 | — | +| `Peers[].ProbeInFlight` | bool | — | +| `Peers[].Closed` | bool | — | + +### `GET /status/durable` + +Durable store state of the served volume. Go type `volume.durableStatusBody`. + +| Field | Type | Meaning | +|---|---|---| +| `VolumeID` | string | — | +| `ReplicaID` | string | — | +| `VolumeCount` | int | — | +| `Volumes[]` | object | — | +| `Volumes[].VolumeID` | string | — | +| `Volumes[].Path` | string | — | +| `Volumes[].Impl` | string | — | +| `Volumes[].ReplicaID` | string | — | +| `Volumes[].Epoch` | uint64 | — | +| `Volumes[].EndpointVersion` | uint64 | — | +| `Volumes[].Latched` | bool | — | +| `Volumes[].Operational` | bool | — | +| `Volumes[].FrontierKnown` | bool | — | +| `Volumes[].DurableLSN` | uint64 | — | +| `Volumes[].RetainedLSN` | uint64 | — | +| `Volumes[].HeadLSN` | uint64 | — | +| `Volumes[].Evidence` | string | — | +| `Volumes[].Closed` | bool | — | +| `Volumes[].WriteProfile` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Writes` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Flushes` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUAWrites` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Failed` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL` | object | — (omitted when empty) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Count` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.SumNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P50UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P99UpperNanos` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.TargetWriteOps` | uint64 | — | +| `Volumes[].WriteProfile.TargetWriteBytes` | uint64 | — | +| `Volumes[].WriteProfile.TargetWriteRequestMaxBytes` | uint64 | — | +| `Volumes[].WriteProfile.TargetWriteDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.BackendWriteRequestOps` | uint64 | — | +| `Volumes[].WriteProfile.BackendWriteRequestBytes` | uint64 | — | +| `Volumes[].WriteProfile.BackendWriteRequestMaxBytes` | uint64 | — | +| `Volumes[].WriteProfile.BackendWriteOps` | uint64 | — | +| `Volumes[].WriteProfile.BackendWriteBytes` | uint64 | — | +| `Volumes[].WriteProfile.BackendWriteDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.BackendStorageWriteCalls` | uint64 | — | +| `Volumes[].WriteProfile.BackendStorageWriteBlocks` | uint64 | — | +| `Volumes[].WriteProfile.BackendStorageBatchCalls` | uint64 | — | +| `Volumes[].WriteProfile.BackendStorageBatchBlocks` | uint64 | — | +| `Volumes[].WriteProfile.BackendFullBlockBatchCalls` | uint64 | — | +| `Volumes[].WriteProfile.BackendFullBlockBatchBlocks` | uint64 | — | +| `Volumes[].WriteProfile.BackendFullBlockBatchMax` | uint64 | — | +| `Volumes[].WriteProfile.WALCopyOps` | uint64 | — | +| `Volumes[].WriteProfile.WALCopyBytes` | uint64 | — | +| `Volumes[].WriteProfile.WALCopyDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.WALEncodeOps` | uint64 | — | +| `Volumes[].WriteProfile.WALEncodeBytes` | uint64 | — | +| `Volumes[].WriteProfile.WALEncodeDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.WALChecksumOps` | uint64 | — | +| `Volumes[].WriteProfile.WALChecksumBytes` | uint64 | — | +| `Volumes[].WriteProfile.WALChecksumDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendOps` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendBytes` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendLockWaitOps` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendLockWaitNanos` | uint64 | — | +| `Volumes[].WriteProfile.WriteCommitLockWaitOps` | uint64 | — | +| `Volumes[].WriteProfile.WriteCommitLockWaitNanos` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendWriteAtCalls` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendWriteAtBytes` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendWriteAtMaxBytes` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendWrapCount` | uint64 | — | +| `Volumes[].WriteProfile.WALAppendPaddingBytes` | uint64 | — | +| `Volumes[].WriteProfile.DirtyMapUpdateOps` | uint64 | — | +| `Volumes[].WriteProfile.DirtyMapUpdateDurationNanos` | uint64 | — | +| `Volumes[].WriteProfile.BackendSyncOps` | uint64 | — | +| `Volumes[].WriteProfile.BackendSyncDurationNanos` | uint64 | — | +| `Volumes[].DataSync` | object | — (omitted when empty) | +| `Volumes[].DataSync.Mode` | string | — | +| `Volumes[].DataSync.Reason` | string | — | +| `Volumes[].CheckpointPersistence` | object | — (omitted when empty) | +| `Volumes[].CheckpointPersistence.Successes` | uint64 | — | +| `Volumes[].CheckpointPersistence.Refusals` | uint64 | — | +| `Volumes[].CheckpointPersistence.Failures` | uint64 | — | +| `Volumes[].CheckpointPersistence.CheckpointLSN` | uint64 | — | +| `Volumes[].CheckpointPersistence.Advances` | uint64 | — | +| `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | — | +| `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | +| `Volumes[].Chunk.Attached` | bool | — | +| `Volumes[].Chunk.AwaitingAuthority` | bool | — | +| `Volumes[].Chunk.Fenced` | bool | — | +| `Volumes[].Chunk.RemoteLSN` | uint64 | — | +| `Volumes[].Chunk.Stats` | object | — | +| `Volumes[].Chunk.Stats.Hydration` | object | — | +| `Volumes[].Chunk.Stats.Hydration.WorkerLimit` | int | — | +| `Volumes[].Chunk.Stats.Hydration.QueueDepth` | int | — | +| `Volumes[].Chunk.Stats.Hydration.Active` | int | — | +| `Volumes[].Chunk.Stats.Hydration.Queued` | int | — | +| `Volumes[].Chunk.Stats.Hydration.WaitCalls` | uint64 | — | +| `Volumes[].Chunk.Stats.Hydration.Joined` | uint64 | — | +| `Volumes[].Chunk.Stats.Hydration.WaitRefusals` | uint64 | — | +| `Volumes[].Chunk.Stats.Hydration.Fetches` | uint64 | — | +| `Volumes[].Chunk.Stats.Hydration.Completed` | uint64 | — | +| `Volumes[].Chunk.Stats.Hydration.FetchErrors` | uint64 | — | +| `Volumes[].Chunk.Stats.CutsOK` | uint64 | — | +| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | — | +| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | — | +| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | — | +| `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, budget_revoked, upload | +| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | — | +| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | — | +| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | — | +| `Volumes[].Chunk.Stats.DirtyChunks` | int | — | +| `Volumes[].Chunk.Stats.Reconciling` | bool | — | +| `Volumes[].Chunk.Stats.ReconcileDone` | int | — | +| `Volumes[].Chunk.Stats.ReconcileTotal` | int | — | +| `Volumes[].Chunk.Stats.LastCut` | object | — | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases` | object | — | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.lifecycleWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.ManifestNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CommitStateNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.IntentCleanupNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.NonPayloadCopyNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.PayloadNs` | int64 | disjoint streaming/copy/upload wall intervals | +| `Volumes[].Chunk.Stats.LastCut.COWWALReadAttempts` | uint64 | Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWLocalReadNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.COWSavedChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.COWSaveNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.COWWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.BarrierPauseNs` | int64 | BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.LockWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.DrainNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CASWriteNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.HeadReadbackNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.SyncNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CopyNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CandidateChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.UploadedChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.UploadedBytes` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.ZeroedChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.UnchangedChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.UploadNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CASNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.MapPersistNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.CASResult` | string | — | +| `Volumes[].Chunk.Stats.LastCut.TotalNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.StageRounds` | int | Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | +| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | — | +| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | — | +| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | — | +| `Volumes[].Chunk.Stats.LastCutH` | uint64 | — | +| `Volumes[].Chunk.Stats.LastCutNs` | int64 | — | +| `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | +| `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | +| `Volumes[].Chunk.HostBudget` | interface | — (omitted when empty) | +| `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | +| `Volumes[].HolesSuspected` | uint64 | — (omitted when empty) | + +### `GET /status/recovery` + +The engine's replica projection (only with recovery enabled). Go type `engine.ReplicaProjection`. + +| Field | Type | Meaning | +|---|---|---| +| `Mode` | Mode (string) | — | +| `RecoveryDecision` | RecoveryDecision (string) | — | +| `SessionKind` | SessionKind (string) | — | +| `SessionPhase` | SessionPhase (string) | — | +| `Epoch` | uint64 | — | +| `EndpointVersion` | uint64 | — | +| `R` | uint64 | — | +| `S` | uint64 | — | +| `H` | uint64 | — | +| `Reason` | string | — | + +### `GET /status/chunk` + +Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint). Go type `chunkstore.VolumeUsage`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | — | +| `chunkBytes` | uint64 | one full chunk | +| `liveChunks` | int | — | +| `liveBytes` | uint64 | — | +| `snapshots[]` | object | — | +| `snapshots[].name` | string | — | +| `snapshots[].createdNs` | int64 | — | +| `snapshots[].class` | string | — | +| `snapshots[].pinned` | bool | — | +| `snapshots[].chunks` | int | — | +| `snapshots[].exclusiveBytes` | uint64 | — | +| `manifestBindings` | int | — | +| `manifestBytes` | uint64 | — | +| `storedBindings` | int | — | +| `storedBytes` | uint64 | — | +| `storedUpperBound` | bool | — | +| `policy` | object | — | +| `policy.keepNewest` | int | — | +| `policy.keepYoungerNs` | int64 | — | +| `policy.keepHourly` | int | — | +| `policy.keepDaily` | int | — | +| `policy.keepWeekly` | int | — | +| `policySet` | bool | — | + +### `GET /status/nvme` + +NVMe/TCP frontend counters. Go type `volume.NVMeStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | — | +| `stats` | object | — | +| `stats.sessions_accepted` | uint64 | — | +| `stats.admin_connects` | uint64 | — | +| `stats.io_connects` | uint64 | — | +| `stats.read_commands` | uint64 | — | +| `stats.write_commands` | uint64 | — | +| `stats.flush_commands` | uint64 | — | +| `stats.inline_write_commands` | uint64 | — | +| `stats.inline_write_bytes` | uint64 | — | +| `stats.r2t_write_commands` | uint64 | — | +| `stats.r2t_write_bytes` | uint64 | — | +| `stats.h2c_data_pdus` | uint64 | — | +| `stats.h2c_data_bytes` | uint64 | — | +| `stats.c2h_data_pdus` | uint64 | — | +| `stats.c2h_data_bytes` | uint64 | — | +| `stats.write_capsule_receive_parse_ops` | uint64 | — | +| `stats.write_capsule_receive_parse_ns` | uint64 | — | +| `stats.r2t_data_collection_ops` | uint64 | — | +| `stats.r2t_data_collection_ns` | uint64 | — | +| `stats.write_dispatch_wait_ops` | uint64 | — | +| `stats.write_dispatch_wait_ns` | uint64 | — | +| `stats.write_handler_ops` | uint64 | — | +| `stats.write_handler_ns` | uint64 | — | +| `stats.write_completion_queue_wait_ops` | uint64 | — | +| `stats.write_completion_queue_wait_ns` | uint64 | — | +| `stats.write_completion_send_ops` | uint64 | — | +| `stats.write_completion_send_ns` | uint64 | — | + +### `GET /status/ublk` + +Ublk frontend counters. Go type `volume.UblkStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | — | +| `stats` | object | — | +| `stats.read_requests` | uint64 | — | +| `stats.write_requests` | uint64 | — | +| `stats.flush_requests` | uint64 | — | +| `stats.fua_writes` | uint64 | — | +| `stats.other_requests` | uint64 | — | +| `stats.errors` | uint64 | — | + +### `GET /status/frontend-capabilities` + +The frontends this host can serve. Go type `volume.FrontendCapabilitiesStatus`. + +| Field | Type | Meaning | +|---|---|---| +| `volumeID` | string | — | +| `hostCapabilityIsProductClaim` | bool | — | +| `frontendTransports[]` | object | — | +| `frontendTransports[].protocol` | string | — | +| `frontendTransports[].transport` | string | — | +| `frontendTransports[].supported` | bool | — | +| `frontendTransports[].listenerImplemented` | bool | — | +| `frontendTransports[].listenerStarted` | bool | — | +| `frontendTransports[].startAllowed` | bool | — | +| `frontendTransports[].startReason` | string | — (omitted when empty) | +| `frontendTransports[].reason` | string | — | +| `frontendTransports[].preflight[]` | object | — (omitted when empty) | +| `frontendTransports[].preflight[].name` | string | — | +| `frontendTransports[].preflight[].available` | bool | — | +| `frontendTransports[].preflight[].reason` | string | — | +| `frontendTransports[].preflight[].detail` | string | — (omitted when empty) | + + From 46a7f6ad77f1bc29b9eb5b1b21d23e53f9c2a60a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:21:28 -0800 Subject: [PATCH 07/25] storage, volume: BarrierBound and barrierOverBound documented as legacy-fixture only; production stages by the copy-on-write budget Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/chunk_control.go | 2 +- seaweed-block/core/storage/chunk_seam.go | 19 ++++++++++--------- seaweed-block/docs/standalone-deployment.md | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c1e4029609..bc05328565 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -93,7 +93,7 @@ type ChunkCutStatsBody struct { StagedChunks int `json:"stagedChunks"` StagedChunksUsed int `json:"stagedChunksUsed"` BarrierCopyChunks int `json:"barrierCopyChunks"` - BarrierOverBound bool `json:"barrierOverBound"` + BarrierOverBound bool `json:"barrierOverBound"` // always false in production (legacy fixture bound only); deprecated with --chunk-dirty-threshold } func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index d2721cfaaa..387fad3237 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -359,10 +359,10 @@ type chunkLayerConfig struct { // impl3 uses its owned LSN map and never calls this optional legacy object. Bitmap chunkBitmapStore - // BarrierBound bounds how many chunks a cut copies under its barrier: - // beyond it, chunks are pre-copied outside the barrier in staging - // rounds (at most chunkStageRounds; then the barrier takes the rest). - // Zero: unbounded, no staging. + // BarrierBound is for legacy test fixtures only: it sets + // BarrierOverBound when a cut copies more chunks than this under its + // barrier. Production staging is by the copy-on-write side budget (M5 + // Stage), and production leaves this zero. BarrierBound int // UploadConcurrency bounds capture/pre-copy Put calls (0 defaults to 8). @@ -443,11 +443,12 @@ type chunkCutStats struct { MapPersistNs int64 CASResult string TotalNs int64 - // Pre-copy (BarrierBound > 0): StageRounds staging rounds staged - // StagedChunks chunks outside the barrier; StagedChunksUsed of the - // uploads in HEAD came from staging. BarrierCopyChunks were copied - // under the barrier; BarrierOverBound: more than the bound (the - // staging rounds did not converge). + // Pre-copy (staging by the copy-on-write side budget, M5 Stage): + // StageRounds staging rounds staged StagedChunks chunks outside the + // barrier; StagedChunksUsed of the uploads in HEAD came from staging. + // BarrierCopyChunks were copied under the barrier. BarrierOverBound: + // more than the legacy fixture BarrierBound; always false in + // production, where that bound is zero. StageRounds int StagedChunks int StagedChunksUsed int diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index ef83e8b124..75fea226a2 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -128,7 +128,7 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | | `SWB_VOLUME_EXTRA_ARGS` | any | empty | Other flags (Kubernetes gate and source-gated flags) | -`--chunk-dirty-threshold` (and `SWB_CHUNK_DIRTY_THRESHOLD`) is deprecated and ignored: a cut stages by its copy-on-write budget, not a chunk count. It is still accepted with a startup warning, and it is removed after 2027-01-31. +`--chunk-dirty-threshold` (and `SWB_CHUNK_DIRTY_THRESHOLD`) is deprecated and ignored: a cut stages by its copy-on-write budget, not a chunk count. It is still accepted with a startup warning, and it is removed after 2027-01-31. With it, the `barrierOverBound` field of a cut's result is always `false` in production; it goes with the flag. The `--chunk-*` and `--workspace-lease` flags are refused unless `--durable-impl=walstore-chunk`; leave them at their defaults otherwise. From c669f13950182995fb7577b88ea806b334277965 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:24:27 -0800 Subject: [PATCH 08/25] status schema: host and frontend status field comments Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/types.go | 29 ++-- .../core/host/volume/memory_status.go | 14 +- .../core/host/volume/status_schema_test.go | 38 +++-- .../core/host/volume/status_server.go | 52 +++--- seaweed-block/docs/status-schema.md | 150 +++++++++--------- 5 files changed, 153 insertions(+), 130 deletions(-) diff --git a/seaweed-block/core/frontend/types.go b/seaweed-block/core/frontend/types.go index b61c2b42a1..920666050a 100644 --- a/seaweed-block/core/frontend/types.go +++ b/seaweed-block/core/frontend/types.go @@ -31,11 +31,11 @@ type Identity struct { // Mode into a single value that ProjectionView.Projection() // returns. type Projection struct { - VolumeID string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Healthy bool + VolumeID string // the volume this host serves + ReplicaID string // this host's replica of it + Epoch uint64 // the authority epoch of the current assignment + EndpointVersion uint64 // the assignment's endpoint version within the epoch + Healthy bool // the replica may serve I/O at this epoch } // ProjectionView is the read-only seam between adapter/engine @@ -50,15 +50,16 @@ type ProjectionView interface { // Backend is a per-lineage handle for one open frontend session. // // Lifecycle ownership (BUG-005 2026-04-22): -// Backend.Close() is OWNED BY THE PROVIDER. Session-layer -// consumers (iSCSI session, NVMe controller, etc.) MUST NOT -// call Close on a Backend obtained from Provider.Open — -// treat the returned Backend as a BORROWED reference for the -// duration of the session. DurableProvider caches one Backend -// per volumeID; a session-level Close would mark the cached -// Backend closed and break every subsequent session. Session -// teardown should release conn + session-local state only. -// Provider.Close tears down all Backends in correct order. +// +// Backend.Close() is OWNED BY THE PROVIDER. Session-layer +// consumers (iSCSI session, NVMe controller, etc.) MUST NOT +// call Close on a Backend obtained from Provider.Open — +// treat the returned Backend as a BORROWED reference for the +// duration of the session. DurableProvider caches one Backend +// per volumeID; a session-level Close would mark the cached +// Backend closed and break every subsequent session. Session +// teardown should release conn + session-local state only. +// Provider.Close tears down all Backends in correct order. // // T3a extends the interface with two methods (all existing // implementations gain trivial impls in the same commit): diff --git a/seaweed-block/core/host/volume/memory_status.go b/seaweed-block/core/host/volume/memory_status.go index 3a15daa127..b1ee1950bc 100644 --- a/seaweed-block/core/host/volume/memory_status.go +++ b/seaweed-block/core/host/volume/memory_status.go @@ -11,13 +11,13 @@ import ( // ProcessMemoryStatus separates live heap from resident pages awaiting return // to the OS. RSS fields are zero on systems without /proc/self/status. type ProcessMemoryStatus struct { - HeapAllocBytes uint64 - HeapInuseBytes uint64 - HeapSysBytes uint64 - HeapReleasedBytes uint64 - SoftLimitBytes int64 - RSSBytes uint64 - AnonymousRSSBytes uint64 + HeapAllocBytes uint64 // Go heap bytes in live objects (runtime.MemStats.HeapAlloc) + HeapInuseBytes uint64 // Go heap bytes in in-use spans (HeapInuse) + HeapSysBytes uint64 // Go heap bytes obtained from the OS (HeapSys) + HeapReleasedBytes uint64 // Go heap bytes returned to the OS (HeapReleased) + SoftLimitBytes int64 // the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) + RSSBytes uint64 // resident set size from /proc/self/status (VmRSS); 0 off Linux + AnonymousRSSBytes uint64 // anonymous resident memory (RssAnon); 0 off Linux } func processMemoryStatus() ProcessMemoryStatus { diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go index 89447cb761..2222189579 100644 --- a/seaweed-block/core/host/volume/status_schema_test.go +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -36,17 +36,17 @@ var statusRoutes = []struct { } type peersStatusBody struct { - VolumeID string - ReplicaID string - PeerCount int - Peers []replication.ReplicaPeerStatus + VolumeID string // the served volume + ReplicaID string // this host's replica + PeerCount int // number of entries in Peers + Peers []replication.ReplicaPeerStatus // this primary's replication peers } type durableStatusBody struct { - VolumeID string - ReplicaID string - VolumeCount int - Volumes []durable.VolumeStatus + VolumeID string // the served volume + ReplicaID string // this host's replica + VolumeCount int // number of entries in Volumes + Volumes []durable.VolumeStatus // the durable store state of the served volume } const ( @@ -70,7 +70,9 @@ func (d fieldDocs) load(t *testing.T, pkgPath string) { d["pkg:"+pkgPath] = "" dir := filepath.Join("..", "..", "..", strings.TrimPrefix(pkgPath, modulePath)) fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { return !strings.HasSuffix(fi.Name(), "_test.go") }, parser.ParseComments) + pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { + return !strings.HasSuffix(fi.Name(), "_test.go") || fi.Name() == "status_schema_test.go" // the restated bodies + }, parser.ParseComments) if err != nil { t.Fatalf("parse %s: %v", dir, err) } @@ -85,13 +87,27 @@ func (d fieldDocs) load(t *testing.T, pkgPath string) { if !ok { return true } + // A doc comment above a run of fields with no blank line + // between them describes the whole run (a group comment). + group, groupFirst, prevEnd := "", "", -1 for _, fl := range st.Fields.List { text := "" - if fl.Doc != nil { + line := fset.Position(fl.Pos()).Line + switch { + case fl.Doc != nil: text = fl.Doc.Text() - } else if fl.Comment != nil { + group, groupFirst = strings.Join(strings.Fields(text), " "), "" + if len(fl.Names) > 0 { + groupFirst = fl.Names[0].Name + } + case fl.Comment != nil: text = fl.Comment.Text() + case group != "" && line == prevEnd+1: + text = "(group of `" + groupFirst + "`) " + group + default: + group = "" } + prevEnd = fset.Position(fl.End()).Line text = strings.Join(strings.Fields(text), " ") for _, name := range fl.Names { d[pkgPath+"."+ts.Name.Name+"."+name.Name] = text diff --git a/seaweed-block/core/host/volume/status_server.go b/seaweed-block/core/host/volume/status_server.go index e8fa35391e..eda1faaa63 100644 --- a/seaweed-block/core/host/volume/status_server.go +++ b/seaweed-block/core/host/volume/status_server.go @@ -131,39 +131,39 @@ type RuntimeRebuildResult struct { } type FrontendTransportCapability struct { - Protocol string `json:"protocol"` - Transport string `json:"transport"` - Supported bool `json:"supported"` - ListenerImplemented bool `json:"listenerImplemented"` - ListenerStarted bool `json:"listenerStarted"` - StartAllowed bool `json:"startAllowed"` - StartReason string `json:"startReason,omitempty"` - Reason string `json:"reason"` - Preflight []FrontendTransportPreflightFact `json:"preflight,omitempty"` + Protocol string `json:"protocol"` // the block protocol (iscsi, nvme, ublk) + Transport string `json:"transport"` // its transport (tcp, rdma, local) + Supported bool `json:"supported"` // this build and host can serve it + ListenerImplemented bool `json:"listenerImplemented"` // a listener exists for it in this binary + ListenerStarted bool `json:"listenerStarted"` // the listener is running now + StartAllowed bool `json:"startAllowed"` // the preflight checks allow starting it + StartReason string `json:"startReason,omitempty"` // why it may or may not start + Reason string `json:"reason"` // why it is or is not supported + Preflight []FrontendTransportPreflightFact `json:"preflight,omitempty"` // the host facts checked for it } type FrontendTransportPreflightFact struct { - Name string `json:"name"` - Available bool `json:"available"` - Reason string `json:"reason"` - Detail string `json:"detail,omitempty"` + Name string `json:"name"` // the host fact checked (a module, device or privilege) + Available bool `json:"available"` // the fact holds on this host + Reason string `json:"reason"` // why it holds or not + Detail string `json:"detail,omitempty"` // extra detail, such as the path probed } type FrontendCapabilitiesStatus struct { - VolumeID string `json:"volumeID"` - HostCapabilityIsProductClaim bool `json:"hostCapabilityIsProductClaim"` - FrontendTransports []FrontendTransportCapability `json:"frontendTransports"` + VolumeID string `json:"volumeID"` // the served volume + HostCapabilityIsProductClaim bool `json:"hostCapabilityIsProductClaim"` // always false: host facts, not a supported-product claim + FrontendTransports []FrontendTransportCapability `json:"frontendTransports"` // one entry per protocol and transport } type NVMeStatus struct { - VolumeID string `json:"volumeID"` - Stats nvme.Stats `json:"stats"` + VolumeID string `json:"volumeID"` // the served volume + Stats nvme.Stats `json:"stats"` // the NVMe/TCP target's counters since start } // UblkStatus is the /status/ublk body: the ublk device's request counters. type UblkStatus struct { - VolumeID string `json:"volumeID"` - Stats ublk.Stats `json:"stats"` + VolumeID string `json:"volumeID"` // the served volume + Stats ublk.Stats `json:"stats"` // the ublk device's request counters since start } const ( @@ -184,10 +184,16 @@ const ( // replica readiness from authority movement. type StatusProjection struct { frontend.Projection - Memory ProcessMemoryStatus + // Memory is the process's memory use at the time of the request. + Memory ProcessMemoryStatus + // FrontendPrimaryReady: this replica is the healthy, non-superseded + // primary and may serve guest I/O. FrontendPrimaryReady bool - AuthorityRole string - ReplicationRole string + // AuthorityRole is primary, superseded or unknown. + AuthorityRole string + // ReplicationRole is none (a primary), recovering, not_ready, + // replica_ready or unknown. + ReplicationRole string // RoleAdmissionFailure (G1) explains a not-Healthy projection caused // by a failed role call on the replica listener; empty otherwise. RoleAdmissionFailure string `json:",omitempty"` diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index beda34f23e..08cc367950 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -14,22 +14,22 @@ The volume's authority and health projection. Go type `volume.StatusProjection`. | Field | Type | Meaning | |---|---|---| -| `VolumeID` | string | — | -| `ReplicaID` | string | — | -| `Epoch` | uint64 | — | -| `EndpointVersion` | uint64 | — | -| `Healthy` | bool | — | -| `Memory` | object | — | -| `Memory.HeapAllocBytes` | uint64 | — | -| `Memory.HeapInuseBytes` | uint64 | — | -| `Memory.HeapSysBytes` | uint64 | — | -| `Memory.HeapReleasedBytes` | uint64 | — | -| `Memory.SoftLimitBytes` | int64 | — | -| `Memory.RSSBytes` | uint64 | — | -| `Memory.AnonymousRSSBytes` | uint64 | — | -| `FrontendPrimaryReady` | bool | — | -| `AuthorityRole` | string | — | -| `ReplicationRole` | string | — | +| `VolumeID` | string | the volume this host serves | +| `ReplicaID` | string | this host's replica of it | +| `Epoch` | uint64 | the authority epoch of the current assignment | +| `EndpointVersion` | uint64 | the assignment's endpoint version within the epoch | +| `Healthy` | bool | the replica may serve I/O at this epoch | +| `Memory` | object | Memory is the process's memory use at the time of the request. | +| `Memory.HeapAllocBytes` | uint64 | Go heap bytes in live objects (runtime.MemStats.HeapAlloc) | +| `Memory.HeapInuseBytes` | uint64 | Go heap bytes in in-use spans (HeapInuse) | +| `Memory.HeapSysBytes` | uint64 | Go heap bytes obtained from the OS (HeapSys) | +| `Memory.HeapReleasedBytes` | uint64 | Go heap bytes returned to the OS (HeapReleased) | +| `Memory.SoftLimitBytes` | int64 | the Go soft memory limit in force (--memory-limit-mib or GOMEMLIMIT) | +| `Memory.RSSBytes` | uint64 | resident set size from /proc/self/status (VmRSS); 0 off Linux | +| `Memory.AnonymousRSSBytes` | uint64 | anonymous resident memory (RssAnon); 0 off Linux | +| `FrontendPrimaryReady` | bool | FrontendPrimaryReady: this replica is the healthy, non-superseded primary and may serve guest I/O. | +| `AuthorityRole` | string | AuthorityRole is primary, superseded or unknown. | +| `ReplicationRole` | string | ReplicationRole is none (a primary), recovering, not_ready, replica_ready or unknown. | | `RoleAdmissionFailure` | string | RoleAdmissionFailure (G1) explains a not-Healthy projection caused by a failed role call on the replica listener; empty otherwise. (omitted when empty) | | `UnhealthyReason` | string | UnhealthyReason is the slot's explicit unhealthy report (#128 rule 6), the value its heartbeat carries; empty when healthy. (omitted when empty) | | `CatchUp` | object | CatchUp shows a supporting replica's catch-up progress while it is not yet replica_ready; it is visible without being an alert. (omitted when empty) | @@ -43,10 +43,10 @@ Replication peers of the served volume. Go type `volume.peersStatusBody`. | Field | Type | Meaning | |---|---|---| -| `VolumeID` | string | — | -| `ReplicaID` | string | — | -| `PeerCount` | int | — | -| `Peers[]` | object | — | +| `VolumeID` | string | the served volume | +| `ReplicaID` | string | this host's replica | +| `PeerCount` | int | number of entries in Peers | +| `Peers[]` | object | this primary's replication peers | | `Peers[].ReplicaID` | string | — | | `Peers[].State` | string | — | | `Peers[].Epoch` | uint64 | — | @@ -63,10 +63,10 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | Field | Type | Meaning | |---|---|---| -| `VolumeID` | string | — | -| `ReplicaID` | string | — | -| `VolumeCount` | int | — | -| `Volumes[]` | object | — | +| `VolumeID` | string | the served volume | +| `ReplicaID` | string | this host's replica | +| `VolumeCount` | int | number of entries in Volumes | +| `Volumes[]` | object | the durable store state of the served volume | | `Volumes[].VolumeID` | string | — | | `Volumes[].Path` | string | — | | `Volumes[].Impl` | string | — | @@ -237,47 +237,47 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | — | | `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | — | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | -| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.ManifestNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.CommitStateNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.IntentCleanupNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.NonPayloadCopyNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.ManifestNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.CommitStateNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.IntentCleanupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | +| `Volumes[].Chunk.Stats.LastCut.NonPayloadCopyNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PayloadNs` | int64 | disjoint streaming/copy/upload wall intervals | | `Volumes[].Chunk.Stats.LastCut.COWWALReadAttempts` | uint64 | Local validated WAL attempts and local copy duration, including savers. | -| `Volumes[].Chunk.Stats.LastCut.COWLocalReadNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.COWSavedChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.COWSaveNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.COWWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.COWLocalReadNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWSavedChunks` | int | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWSaveNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | +| `Volumes[].Chunk.Stats.LastCut.COWWaitNs` | int64 | (group of `COWWALReadAttempts`) Local validated WAL attempts and local copy duration, including savers. | | `Volumes[].Chunk.Stats.LastCut.BarrierPauseNs` | int64 | BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | -| `Volumes[].Chunk.Stats.LastCut.LockWaitNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.DrainNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.CASWriteNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.HeadReadbackNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.SyncNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.CopyNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.CandidateChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.UploadedChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.UploadedBytes` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.ZeroedChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.UnchangedChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.UploadNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.CASNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.MapPersistNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.CASResult` | string | — | -| `Volumes[].Chunk.Stats.LastCut.TotalNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCut.LockWaitNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.DrainNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASWriteNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.HeadReadbackNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.SyncNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CopyNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CandidateChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadedBytes` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.ZeroedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UnchangedChunks` | int | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.UploadNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.MapPersistNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.CASResult` | string | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | +| `Volumes[].Chunk.Stats.LastCut.TotalNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | | `Volumes[].Chunk.Stats.LastCut.StageRounds` | int | Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | -| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | — | -| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | — | -| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | — | +| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | +| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | +| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | +| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | | `Volumes[].Chunk.Stats.LastCutH` | uint64 | — | | `Volumes[].Chunk.Stats.LastCutNs` | int64 | — | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | | `Volumes[].Chunk.HostBudget` | interface | — (omitted when empty) | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | -| `Volumes[].HolesSuspected` | uint64 | — (omitted when empty) | +| `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | ### `GET /status/recovery` @@ -332,8 +332,8 @@ NVMe/TCP frontend counters. Go type `volume.NVMeStatus`. | Field | Type | Meaning | |---|---|---| -| `volumeID` | string | — | -| `stats` | object | — | +| `volumeID` | string | the served volume | +| `stats` | object | the NVMe/TCP target's counters since start | | `stats.sessions_accepted` | uint64 | — | | `stats.admin_connects` | uint64 | — | | `stats.io_connects` | uint64 | — | @@ -367,8 +367,8 @@ Ublk frontend counters. Go type `volume.UblkStatus`. | Field | Type | Meaning | |---|---|---| -| `volumeID` | string | — | -| `stats` | object | — | +| `volumeID` | string | the served volume | +| `stats` | object | the ublk device's request counters since start | | `stats.read_requests` | uint64 | — | | `stats.write_requests` | uint64 | — | | `stats.flush_requests` | uint64 | — | @@ -382,21 +382,21 @@ The frontends this host can serve. Go type `volume.FrontendCapabilitiesStatus`. | Field | Type | Meaning | |---|---|---| -| `volumeID` | string | — | -| `hostCapabilityIsProductClaim` | bool | — | -| `frontendTransports[]` | object | — | -| `frontendTransports[].protocol` | string | — | -| `frontendTransports[].transport` | string | — | -| `frontendTransports[].supported` | bool | — | -| `frontendTransports[].listenerImplemented` | bool | — | -| `frontendTransports[].listenerStarted` | bool | — | -| `frontendTransports[].startAllowed` | bool | — | -| `frontendTransports[].startReason` | string | — (omitted when empty) | -| `frontendTransports[].reason` | string | — | -| `frontendTransports[].preflight[]` | object | — (omitted when empty) | -| `frontendTransports[].preflight[].name` | string | — | -| `frontendTransports[].preflight[].available` | bool | — | -| `frontendTransports[].preflight[].reason` | string | — | -| `frontendTransports[].preflight[].detail` | string | — (omitted when empty) | +| `volumeID` | string | the served volume | +| `hostCapabilityIsProductClaim` | bool | always false: host facts, not a supported-product claim | +| `frontendTransports[]` | object | one entry per protocol and transport | +| `frontendTransports[].protocol` | string | the block protocol (iscsi, nvme, ublk) | +| `frontendTransports[].transport` | string | its transport (tcp, rdma, local) | +| `frontendTransports[].supported` | bool | this build and host can serve it | +| `frontendTransports[].listenerImplemented` | bool | a listener exists for it in this binary | +| `frontendTransports[].listenerStarted` | bool | the listener is running now | +| `frontendTransports[].startAllowed` | bool | the preflight checks allow starting it | +| `frontendTransports[].startReason` | string | why it may or may not start (omitted when empty) | +| `frontendTransports[].reason` | string | why it is or is not supported | +| `frontendTransports[].preflight[]` | object | the host facts checked for it (omitted when empty) | +| `frontendTransports[].preflight[].name` | string | the host fact checked (a module, device or privilege) | +| `frontendTransports[].preflight[].available` | bool | the fact holds on this host | +| `frontendTransports[].preflight[].reason` | string | why it holds or not | +| `frontendTransports[].preflight[].detail` | string | extra detail, such as the path probed (omitted when empty) | From 6fe5a9b17dc22f6ea20f06cd2ccca7f2ee3683f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:25:11 -0800 Subject: [PATCH 09/25] status schema: replication peer, engine projection and chunk usage field comments Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/engine/projection.go | 20 ++--- .../core/frontend/chunkstore/retention.go | 10 +-- .../core/frontend/chunkstore/usage.go | 36 ++++---- seaweed-block/core/replication/peer.go | 18 ++-- seaweed-block/docs/status-schema.md | 82 +++++++++---------- 5 files changed, 83 insertions(+), 83 deletions(-) diff --git a/seaweed-block/core/engine/projection.go b/seaweed-block/core/engine/projection.go index b2df857375..01e1f41418 100644 --- a/seaweed-block/core/engine/projection.go +++ b/seaweed-block/core/engine/projection.go @@ -13,16 +13,16 @@ const ( // ReplicaProjection is the operator-facing view derived from state. // Intentionally descriptive. Must NEVER be reused as control truth. type ReplicaProjection struct { - Mode Mode - RecoveryDecision RecoveryDecision - SessionKind SessionKind - SessionPhase SessionPhase - Epoch uint64 - EndpointVersion uint64 - R uint64 - S uint64 - H uint64 - Reason string + Mode Mode // the engine mode (idle, recovering, healthy, degraded) + RecoveryDecision RecoveryDecision // the recovery class the R/S/H boundaries call for + SessionKind SessionKind // the kind of the current recovery session, if any + SessionPhase SessionPhase // its phase + Epoch uint64 // the authority epoch + EndpointVersion uint64 // the endpoint version within the epoch + R uint64 // the replica's durable boundary (LSN) + S uint64 // the primary's recoverable start boundary (WAL tail LSN) + H uint64 // the primary's target boundary (head LSN) + Reason string // why the engine is in this mode or decision } // DeriveProjection computes the projection from current state. diff --git a/seaweed-block/core/frontend/chunkstore/retention.go b/seaweed-block/core/frontend/chunkstore/retention.go index a714cb82bc..acc738b23e 100644 --- a/seaweed-block/core/frontend/chunkstore/retention.go +++ b/seaweed-block/core/frontend/chunkstore/retention.go @@ -116,11 +116,11 @@ func (s SnapshotInfo) Pinned() bool { // RetentionPolicy is a volume's snapshot retention policy. type RetentionPolicy struct { - KeepNewest int `json:"keepNewest"` - KeepYoungerNs int64 `json:"keepYoungerNs"` - KeepHourly int `json:"keepHourly"` - KeepDaily int `json:"keepDaily"` - KeepWeekly int `json:"keepWeekly"` + KeepNewest int `json:"keepNewest"` // keep the newest N unpinned snapshots + KeepYoungerNs int64 `json:"keepYoungerNs"` // keep every snapshot younger than this (ns) + KeepHourly int `json:"keepHourly"` // keep the newest snapshot of each of the last N hours + KeepDaily int `json:"keepDaily"` // keep the newest snapshot of each of the last N days + KeepWeekly int `json:"keepWeekly"` // keep the newest snapshot of each of the last N weeks } // DefaultRetentionPolicy is the policy of a volume that never set one. diff --git a/seaweed-block/core/frontend/chunkstore/usage.go b/seaweed-block/core/frontend/chunkstore/usage.go index d8ec500960..472c1ed877 100644 --- a/seaweed-block/core/frontend/chunkstore/usage.go +++ b/seaweed-block/core/frontend/chunkstore/usage.go @@ -38,28 +38,28 @@ import ( // SnapshotUsage is one snapshot's share of a volume's space. type SnapshotUsage struct { - Name string `json:"name"` - CreatedNs int64 `json:"createdNs"` - Class string `json:"class"` - Pinned bool `json:"pinned"` - Chunks int `json:"chunks"` - ExclusiveBytes uint64 `json:"exclusiveBytes"` + Name string `json:"name"` // the snapshot name + CreatedNs int64 `json:"createdNs"` // when it was created (Unix ns) + Class string `json:"class"` // its retention class + Pinned bool `json:"pinned"` // retention never deletes it + Chunks int `json:"chunks"` // chunks its manifest references + ExclusiveBytes uint64 `json:"exclusiveBytes"` // bytes no other holder references: what deleting it makes eligible for GC } // VolumeUsage is a volume's space accounting. type VolumeUsage struct { - VolumeID string `json:"volumeID"` - ChunkBytes uint64 `json:"chunkBytes"` // one full chunk - LiveChunks int `json:"liveChunks"` - LiveBytes uint64 `json:"liveBytes"` - Snapshots []SnapshotUsage `json:"snapshots"` - ManifestBindings int `json:"manifestBindings"` - ManifestBytes uint64 `json:"manifestBytes"` - StoredBindings int `json:"storedBindings"` - StoredBytes uint64 `json:"storedBytes"` - StoredUpperBound bool `json:"storedUpperBound"` - Policy RetentionPolicy `json:"policy"` - PolicySet bool `json:"policySet"` + VolumeID string `json:"volumeID"` // the volume + ChunkBytes uint64 `json:"chunkBytes"` // one full chunk + LiveChunks int `json:"liveChunks"` // chunks HEAD references + LiveBytes uint64 `json:"liveBytes"` // their bytes (the last chunk clipped) + Snapshots []SnapshotUsage `json:"snapshots"` // one entry per live snapshot + ManifestBindings int `json:"manifestBindings"` // stored chunk-key bindings some manifest references + ManifestBytes uint64 `json:"manifestBytes"` // their exact bytes + StoredBindings int `json:"storedBindings"` // all chunk-key bindings in the filer, referenced or not + StoredBytes uint64 `json:"storedBytes"` // their bytes; unreferenced ones counted at full chunk size + StoredUpperBound bool `json:"storedUpperBound"` // StoredBytes is an upper bound (some bindings are unreferenced) + Policy RetentionPolicy `json:"policy"` // the snapshot retention policy in force + PolicySet bool `json:"policySet"` // the volume set its own policy (else the default applies) } // chunkSize is the byte size of chunk index idx under g. diff --git a/seaweed-block/core/replication/peer.go b/seaweed-block/core/replication/peer.go index 6280721502..42dfadcedc 100644 --- a/seaweed-block/core/replication/peer.go +++ b/seaweed-block/core/replication/peer.go @@ -178,15 +178,15 @@ type ReplicaPeer struct { // append-only: status endpoints and TestOps gates use it to assert // peer recovery state without scraping logs. type ReplicaPeerStatus struct { - ReplicaID string - State string - Epoch uint64 - EndpointVersion uint64 - DataAddr string - CtrlAddr string - SessionID uint64 - ProbeInFlight bool - Closed bool + ReplicaID string // the peer replica + State string // the peer state (the replica peer table, M3) + Epoch uint64 // the epoch the peer was assigned at + EndpointVersion uint64 // the peer's endpoint version within the epoch + DataAddr string // the peer's data-path address + CtrlAddr string // the peer's control-path address + SessionID uint64 // the current recovery or shipping session; 0 when none + ProbeInFlight bool // a reachability probe of the peer is running + Closed bool // the peer handle was closed (it no longer ships) } // NewReplicaPeer constructs a per-replica runtime handle and registers diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 08cc367950..9d2b108420 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -47,15 +47,15 @@ Replication peers of the served volume. Go type `volume.peersStatusBody`. | `ReplicaID` | string | this host's replica | | `PeerCount` | int | number of entries in Peers | | `Peers[]` | object | this primary's replication peers | -| `Peers[].ReplicaID` | string | — | -| `Peers[].State` | string | — | -| `Peers[].Epoch` | uint64 | — | -| `Peers[].EndpointVersion` | uint64 | — | -| `Peers[].DataAddr` | string | — | -| `Peers[].CtrlAddr` | string | — | -| `Peers[].SessionID` | uint64 | — | -| `Peers[].ProbeInFlight` | bool | — | -| `Peers[].Closed` | bool | — | +| `Peers[].ReplicaID` | string | the peer replica | +| `Peers[].State` | string | the peer state (the replica peer table, M3) | +| `Peers[].Epoch` | uint64 | the epoch the peer was assigned at | +| `Peers[].EndpointVersion` | uint64 | the peer's endpoint version within the epoch | +| `Peers[].DataAddr` | string | the peer's data-path address | +| `Peers[].CtrlAddr` | string | the peer's control-path address | +| `Peers[].SessionID` | uint64 | the current recovery or shipping session; 0 when none | +| `Peers[].ProbeInFlight` | bool | a reachability probe of the peer is running | +| `Peers[].Closed` | bool | the peer handle was closed (it no longer ships) | ### `GET /status/durable` @@ -285,16 +285,16 @@ The engine's replica projection (only with recovery enabled). Go type `engine.Re | Field | Type | Meaning | |---|---|---| -| `Mode` | Mode (string) | — | -| `RecoveryDecision` | RecoveryDecision (string) | — | -| `SessionKind` | SessionKind (string) | — | -| `SessionPhase` | SessionPhase (string) | — | -| `Epoch` | uint64 | — | -| `EndpointVersion` | uint64 | — | -| `R` | uint64 | — | -| `S` | uint64 | — | -| `H` | uint64 | — | -| `Reason` | string | — | +| `Mode` | Mode (string) | the engine mode (idle, recovering, healthy, degraded) | +| `RecoveryDecision` | RecoveryDecision (string) | the recovery class the R/S/H boundaries call for | +| `SessionKind` | SessionKind (string) | the kind of the current recovery session, if any | +| `SessionPhase` | SessionPhase (string) | its phase | +| `Epoch` | uint64 | the authority epoch | +| `EndpointVersion` | uint64 | the endpoint version within the epoch | +| `R` | uint64 | the replica's durable boundary (LSN) | +| `S` | uint64 | the primary's recoverable start boundary (WAL tail LSN) | +| `H` | uint64 | the primary's target boundary (head LSN) | +| `Reason` | string | why the engine is in this mode or decision | ### `GET /status/chunk` @@ -302,29 +302,29 @@ Chunk store usage of a walstore-chunk volume (only with --chunk-control-endpoint | Field | Type | Meaning | |---|---|---| -| `volumeID` | string | — | +| `volumeID` | string | the volume | | `chunkBytes` | uint64 | one full chunk | -| `liveChunks` | int | — | -| `liveBytes` | uint64 | — | -| `snapshots[]` | object | — | -| `snapshots[].name` | string | — | -| `snapshots[].createdNs` | int64 | — | -| `snapshots[].class` | string | — | -| `snapshots[].pinned` | bool | — | -| `snapshots[].chunks` | int | — | -| `snapshots[].exclusiveBytes` | uint64 | — | -| `manifestBindings` | int | — | -| `manifestBytes` | uint64 | — | -| `storedBindings` | int | — | -| `storedBytes` | uint64 | — | -| `storedUpperBound` | bool | — | -| `policy` | object | — | -| `policy.keepNewest` | int | — | -| `policy.keepYoungerNs` | int64 | — | -| `policy.keepHourly` | int | — | -| `policy.keepDaily` | int | — | -| `policy.keepWeekly` | int | — | -| `policySet` | bool | — | +| `liveChunks` | int | chunks HEAD references | +| `liveBytes` | uint64 | their bytes (the last chunk clipped) | +| `snapshots[]` | object | one entry per live snapshot | +| `snapshots[].name` | string | the snapshot name | +| `snapshots[].createdNs` | int64 | when it was created (Unix ns) | +| `snapshots[].class` | string | its retention class | +| `snapshots[].pinned` | bool | retention never deletes it | +| `snapshots[].chunks` | int | chunks its manifest references | +| `snapshots[].exclusiveBytes` | uint64 | bytes no other holder references: what deleting it makes eligible for GC | +| `manifestBindings` | int | stored chunk-key bindings some manifest references | +| `manifestBytes` | uint64 | their exact bytes | +| `storedBindings` | int | all chunk-key bindings in the filer, referenced or not | +| `storedBytes` | uint64 | their bytes; unreferenced ones counted at full chunk size | +| `storedUpperBound` | bool | StoredBytes is an upper bound (some bindings are unreferenced) | +| `policy` | object | the snapshot retention policy in force | +| `policy.keepNewest` | int | keep the newest N unpinned snapshots | +| `policy.keepYoungerNs` | int64 | keep every snapshot younger than this (ns) | +| `policy.keepHourly` | int | keep the newest snapshot of each of the last N hours | +| `policy.keepDaily` | int | keep the newest snapshot of each of the last N days | +| `policy.keepWeekly` | int | keep the newest snapshot of each of the last N weeks | +| `policySet` | bool | the volume set its own policy (else the default applies) | ### `GET /status/nvme` From 671a5eebc8361b0fd0bdef738a9d096e51460713 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:25:55 -0800 Subject: [PATCH 10/25] status schema: NVMe/TCP and ublk counter comments Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/frontend/nvme/stats.go | 54 +++++++++-------- seaweed-block/core/frontend/ublk/dispatch.go | 12 ++-- seaweed-block/docs/status-schema.md | 64 ++++++++++---------- 3 files changed, 66 insertions(+), 64 deletions(-) diff --git a/seaweed-block/core/frontend/nvme/stats.go b/seaweed-block/core/frontend/nvme/stats.go index e167cccb4c..055c45278b 100644 --- a/seaweed-block/core/frontend/nvme/stats.go +++ b/seaweed-block/core/frontend/nvme/stats.go @@ -15,36 +15,38 @@ import ( // includes socket wait and decode. R2T collection includes target send, // initiator response, and H2CData receive. type Stats struct { - SessionsAccepted uint64 `json:"sessions_accepted"` - AdminConnects uint64 `json:"admin_connects"` - IOConnects uint64 `json:"io_connects"` + SessionsAccepted uint64 `json:"sessions_accepted"` // TCP sessions accepted + AdminConnects uint64 `json:"admin_connects"` // admin-queue Connect commands + IOConnects uint64 `json:"io_connects"` // I/O-queue Connect commands - ReadCommands uint64 `json:"read_commands"` - WriteCommands uint64 `json:"write_commands"` - FlushCommands uint64 `json:"flush_commands"` + ReadCommands uint64 `json:"read_commands"` // Read commands received + WriteCommands uint64 `json:"write_commands"` // Write commands received + FlushCommands uint64 `json:"flush_commands"` // Flush commands received - InlineWriteCommands uint64 `json:"inline_write_commands"` - InlineWriteBytes uint64 `json:"inline_write_bytes"` - R2TWriteCommands uint64 `json:"r2t_write_commands"` - R2TWriteBytes uint64 `json:"r2t_write_bytes"` + InlineWriteCommands uint64 `json:"inline_write_commands"` // writes whose data came inline in the command capsule + InlineWriteBytes uint64 `json:"inline_write_bytes"` // their data bytes + R2TWriteCommands uint64 `json:"r2t_write_commands"` // writes whose data the target requested with R2T + R2TWriteBytes uint64 `json:"r2t_write_bytes"` // their data bytes - H2CDataPDUs uint64 `json:"h2c_data_pdus"` - H2CDataBytes uint64 `json:"h2c_data_bytes"` - C2HDataPDUs uint64 `json:"c2h_data_pdus"` - C2HDataBytes uint64 `json:"c2h_data_bytes"` + H2CDataPDUs uint64 `json:"h2c_data_pdus"` // host-to-controller data PDUs received + H2CDataBytes uint64 `json:"h2c_data_bytes"` // their bytes + C2HDataPDUs uint64 `json:"c2h_data_pdus"` // controller-to-host data PDUs sent (read data) + C2HDataBytes uint64 `json:"c2h_data_bytes"` // their bytes - WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"` - WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"` - R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"` - R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"` - WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"` - WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"` - WriteHandlerOps uint64 `json:"write_handler_ops"` - WriteHandlerNanos uint64 `json:"write_handler_ns"` - WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"` - WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"` - WriteCompletionSendOps uint64 `json:"write_completion_send_ops"` - WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"` + // Write phase attribution: for each phase, the operations timed and + // their total nanoseconds (overlapping phases can overlap in time). + WriteCapsuleReceiveParseOps uint64 `json:"write_capsule_receive_parse_ops"` // write capsules received and decoded (includes socket wait) + WriteCapsuleReceiveParseNanos uint64 `json:"write_capsule_receive_parse_ns"` // total nanoseconds of those operations + R2TDataCollectionOps uint64 `json:"r2t_data_collection_ops"` // R2T data collections (R2T send to the last H2CData) + R2TDataCollectionNanos uint64 `json:"r2t_data_collection_ns"` // total nanoseconds of those operations + WriteDispatchWaitOps uint64 `json:"write_dispatch_wait_ops"` // waits for a write handler to take the command + WriteDispatchWaitNanos uint64 `json:"write_dispatch_wait_ns"` // total nanoseconds of those operations + WriteHandlerOps uint64 `json:"write_handler_ops"` // write handler runs (the backend write) + WriteHandlerNanos uint64 `json:"write_handler_ns"` // total nanoseconds of those operations + WriteCompletionQueueWaitOps uint64 `json:"write_completion_queue_wait_ops"` // waits of a completion for the send queue + WriteCompletionQueueWaitNanos uint64 `json:"write_completion_queue_wait_ns"` // total nanoseconds of those operations + WriteCompletionSendOps uint64 `json:"write_completion_send_ops"` // completion sends to the host + WriteCompletionSendNanos uint64 `json:"write_completion_send_ns"` // total nanoseconds of those operations } type targetStats struct { diff --git a/seaweed-block/core/frontend/ublk/dispatch.go b/seaweed-block/core/frontend/ublk/dispatch.go index e2c9c7a8ed..429127b5bb 100644 --- a/seaweed-block/core/frontend/ublk/dispatch.go +++ b/seaweed-block/core/frontend/ublk/dispatch.go @@ -50,12 +50,12 @@ type handler struct { // counted when it is received, before the backend call; Errors counts the // requests that completed with a negative result. type Stats struct { - ReadRequests uint64 `json:"read_requests"` - WriteRequests uint64 `json:"write_requests"` - FlushRequests uint64 `json:"flush_requests"` - FUAWrites uint64 `json:"fua_writes"` - OtherRequests uint64 `json:"other_requests"` - Errors uint64 `json:"errors"` + ReadRequests uint64 `json:"read_requests"` // read requests received + WriteRequests uint64 `json:"write_requests"` // write requests received + FlushRequests uint64 `json:"flush_requests"` // flush requests received + FUAWrites uint64 `json:"fua_writes"` // writes with forced unit access + OtherRequests uint64 `json:"other_requests"` // requests of any other operation + Errors uint64 `json:"errors"` // requests completed with a negative result } type counters struct { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 9d2b108420..9df8f54859 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -334,32 +334,32 @@ NVMe/TCP frontend counters. Go type `volume.NVMeStatus`. |---|---|---| | `volumeID` | string | the served volume | | `stats` | object | the NVMe/TCP target's counters since start | -| `stats.sessions_accepted` | uint64 | — | -| `stats.admin_connects` | uint64 | — | -| `stats.io_connects` | uint64 | — | -| `stats.read_commands` | uint64 | — | -| `stats.write_commands` | uint64 | — | -| `stats.flush_commands` | uint64 | — | -| `stats.inline_write_commands` | uint64 | — | -| `stats.inline_write_bytes` | uint64 | — | -| `stats.r2t_write_commands` | uint64 | — | -| `stats.r2t_write_bytes` | uint64 | — | -| `stats.h2c_data_pdus` | uint64 | — | -| `stats.h2c_data_bytes` | uint64 | — | -| `stats.c2h_data_pdus` | uint64 | — | -| `stats.c2h_data_bytes` | uint64 | — | -| `stats.write_capsule_receive_parse_ops` | uint64 | — | -| `stats.write_capsule_receive_parse_ns` | uint64 | — | -| `stats.r2t_data_collection_ops` | uint64 | — | -| `stats.r2t_data_collection_ns` | uint64 | — | -| `stats.write_dispatch_wait_ops` | uint64 | — | -| `stats.write_dispatch_wait_ns` | uint64 | — | -| `stats.write_handler_ops` | uint64 | — | -| `stats.write_handler_ns` | uint64 | — | -| `stats.write_completion_queue_wait_ops` | uint64 | — | -| `stats.write_completion_queue_wait_ns` | uint64 | — | -| `stats.write_completion_send_ops` | uint64 | — | -| `stats.write_completion_send_ns` | uint64 | — | +| `stats.sessions_accepted` | uint64 | TCP sessions accepted | +| `stats.admin_connects` | uint64 | admin-queue Connect commands | +| `stats.io_connects` | uint64 | I/O-queue Connect commands | +| `stats.read_commands` | uint64 | Read commands received | +| `stats.write_commands` | uint64 | Write commands received | +| `stats.flush_commands` | uint64 | Flush commands received | +| `stats.inline_write_commands` | uint64 | writes whose data came inline in the command capsule | +| `stats.inline_write_bytes` | uint64 | their data bytes | +| `stats.r2t_write_commands` | uint64 | writes whose data the target requested with R2T | +| `stats.r2t_write_bytes` | uint64 | their data bytes | +| `stats.h2c_data_pdus` | uint64 | host-to-controller data PDUs received | +| `stats.h2c_data_bytes` | uint64 | their bytes | +| `stats.c2h_data_pdus` | uint64 | controller-to-host data PDUs sent (read data) | +| `stats.c2h_data_bytes` | uint64 | their bytes | +| `stats.write_capsule_receive_parse_ops` | uint64 | Write phase attribution: for each phase, the operations timed and their total nanoseconds (overlapping phases can overlap in time). | +| `stats.write_capsule_receive_parse_ns` | uint64 | total nanoseconds of those operations | +| `stats.r2t_data_collection_ops` | uint64 | R2T data collections (R2T send to the last H2CData) | +| `stats.r2t_data_collection_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_dispatch_wait_ops` | uint64 | waits for a write handler to take the command | +| `stats.write_dispatch_wait_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_handler_ops` | uint64 | write handler runs (the backend write) | +| `stats.write_handler_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_completion_queue_wait_ops` | uint64 | waits of a completion for the send queue | +| `stats.write_completion_queue_wait_ns` | uint64 | total nanoseconds of those operations | +| `stats.write_completion_send_ops` | uint64 | completion sends to the host | +| `stats.write_completion_send_ns` | uint64 | total nanoseconds of those operations | ### `GET /status/ublk` @@ -369,12 +369,12 @@ Ublk frontend counters. Go type `volume.UblkStatus`. |---|---|---| | `volumeID` | string | the served volume | | `stats` | object | the ublk device's request counters since start | -| `stats.read_requests` | uint64 | — | -| `stats.write_requests` | uint64 | — | -| `stats.flush_requests` | uint64 | — | -| `stats.fua_writes` | uint64 | — | -| `stats.other_requests` | uint64 | — | -| `stats.errors` | uint64 | — | +| `stats.read_requests` | uint64 | read requests received | +| `stats.write_requests` | uint64 | write requests received | +| `stats.flush_requests` | uint64 | flush requests received | +| `stats.fua_writes` | uint64 | writes with forced unit access | +| `stats.other_requests` | uint64 | requests of any other operation | +| `stats.errors` | uint64 | requests completed with a negative result | ### `GET /status/frontend-capabilities` From c5478a990f5ef13a77ca51be0ab04d2f21333430 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:27:09 -0800 Subject: [PATCH 11/25] sw-block: the single-filer start check runs within the command's --timeout Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 22 ++++++++----- seaweed-block/cmd/sw-block/chunk_gc.go | 2 +- seaweed-block/cmd/sw-block/chunk_retain.go | 4 +-- .../cmd/sw-block/chunk_start_check_test.go | 33 +++++++++++++++++++ .../cmd/sw-block/chunk_volume_delete.go | 2 +- 5 files changed, 50 insertions(+), 13 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 46411e71e4..983a7ca611 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -52,9 +52,13 @@ var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { return nil } -// refuseUnlessSingleFiler runs the start check; exit >= 0 means refused. -func refuseUnlessSingleFiler(name string, f chunkstore.Filer, stdout, stderr io.Writer) int { - err := checkSingleFiler(context.Background(), f) +// refuseUnlessSingleFiler runs the start check within the command's own +// timeout (a stalled filer or master cannot hold the command longer); exit +// >= 0 means refused. +func refuseUnlessSingleFiler(name string, f chunkstore.Filer, timeout time.Duration, stdout, stderr io.Writer) int { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + err := checkSingleFiler(ctx, f) switch { case err == nil: return -1 @@ -284,7 +288,7 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int { // It returns exit -1 on success, else the exit code after reporting. // chunkCatalog dials the filer and opens the catalog; a command that writes // (writes) first passes the single-filer start check. -func chunkCatalog(name, filer, base string, writes bool, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { +func chunkCatalog(name, filer, base string, writes bool, timeout time.Duration, stdout, stderr io.Writer) (*chunkstore.Catalog, func() error, int) { if filer == "" { return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--chunk-filer is required", false) } @@ -293,7 +297,7 @@ func chunkCatalog(name, filer, base string, writes bool, stdout, stderr io.Write return nil, nil, chunkFail(name, stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false) } if writes { - if exit := refuseUnlessSingleFiler(name, f, stdout, stderr); exit >= 0 { + if exit := refuseUnlessSingleFiler(name, f, timeout, stdout, stderr); exit >= 0 { _ = closeFn() return nil, nil, exit } @@ -395,7 +399,7 @@ func chunkSnapshots(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("snapshots", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshots", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -423,7 +427,7 @@ func chunkSnapshotDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || name == "" { return chunkFail("snapshot-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --name are required", false) } - cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, stdout, stderr) + cat, closeFn, exit := chunkCatalog("snapshot-delete", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -459,7 +463,7 @@ func chunkFork(args []string, stdout, stderr io.Writer) int { requestID = newRequestID() fmt.Fprintf(stderr, "sw-block ops chunk fork: request id %s (reuse it to retry)\n", requestID) } - cat, closeFn, exit := chunkCatalog("fork", filer, base, true, stdout, stderr) + cat, closeFn, exit := chunkCatalog("fork", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -487,7 +491,7 @@ func chunkShow(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("show", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("show", filer, base, false, stdout, stderr) + cat, closeFn, exit := chunkCatalog("show", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_gc.go b/seaweed-block/cmd/sw-block/chunk_gc.go index b802d26e68..41d7071f29 100644 --- a/seaweed-block/cmd/sw-block/chunk_gc.go +++ b/seaweed-block/cmd/sw-block/chunk_gc.go @@ -42,7 +42,7 @@ func chunkGC(args []string, stdout, stderr io.Writer) int { } defer closeFn() if apply { - if exit := refuseUnlessSingleFiler("gc", f, stdout, stderr); exit >= 0 { + if exit := refuseUnlessSingleFiler("gc", f, timeout, stdout, stderr); exit >= 0 { return exit } } diff --git a/seaweed-block/cmd/sw-block/chunk_retain.go b/seaweed-block/cmd/sw-block/chunk_retain.go index 34246710c3..dee26ad7a7 100644 --- a/seaweed-block/cmd/sw-block/chunk_retain.go +++ b/seaweed-block/cmd/sw-block/chunk_retain.go @@ -31,7 +31,7 @@ func chunkUsage(args []string, stdout, stderr io.Writer) int { if volumeID == "" { return chunkFail("usage", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume is required", false) } - cat, closeFn, exit := chunkCatalog("usage", filer, base, false, stdout, stderr) + cat, closeFn, exit := chunkCatalog("usage", filer, base, false, timeout, stdout, stderr) if exit >= 0 { return exit } @@ -74,7 +74,7 @@ func chunkRetain(args []string, stdout, stderr io.Writer) int { if setPolicy && dryRun { return chunkFail("retain", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--set-policy and --dry-run do not combine", false) } - cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, stdout, stderr) + cat, closeFn, exit := chunkCatalog("retain", filer, base, !dryRun, timeout, stdout, stderr) if exit >= 0 { return exit } diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go index 605bde12a9..f3c5e61ab1 100644 --- a/seaweed-block/cmd/sw-block/chunk_start_check_test.go +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -5,6 +5,7 @@ import ( "context" "strings" "testing" + "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" ) @@ -58,3 +59,35 @@ func TestOpsChunk_WritingCommandsRunTheSingleFilerCheck(t *testing.T) { } } } + +// The start check runs within the command's own --timeout: a check stalled +// on its filer or master (here one that blocks until its context ends) ends +// the command at the timeout, as a retryable refusal. +func TestOpsChunk_StartCheckIsBoundedByTheTimeout(t *testing.T) { + mem := chunkstore.NewMemFiler() + prevDial, prevCheck := dialChunkFiler, checkSingleFiler + t.Cleanup(func() { dialChunkFiler, checkSingleFiler = prevDial, prevCheck }) + dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return mem, func() error { return nil }, nil } + checkSingleFiler = func(ctx context.Context, _ chunkstore.Filer) error { + <-ctx.Done() + return ctx.Err() + } + filer := []string{"--chunk-filer", "filer:18888", "--timeout", "200ms"} + for name, args := range map[string][]string{ + "snapshot-delete": append([]string{"ops", "chunk", "snapshot-delete", "--volume", "v1", "--name", "s1"}, filer...), + "gc --apply": append([]string{"ops", "chunk", "gc", "--master", "m:1", "--apply"}, filer...), + } { + done := make(chan struct{}) + var out, errb bytes.Buffer + var code int + go func() { code = run(args, &out, &errb); close(done) }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s: a stalled start check held the command past its 200ms --timeout", name) + } + if code == 0 || !strings.Contains(out.String(), "remote_unavailable") || !strings.Contains(out.String(), `"retryable":true`) { + t.Errorf("%s: exit %d, out %q; want a retryable remote_unavailable refusal", name, code, out.String()) + } + } +} diff --git a/seaweed-block/cmd/sw-block/chunk_volume_delete.go b/seaweed-block/cmd/sw-block/chunk_volume_delete.go index 9054369431..0413f1709f 100644 --- a/seaweed-block/cmd/sw-block/chunk_volume_delete.go +++ b/seaweed-block/cmd/sw-block/chunk_volume_delete.go @@ -46,7 +46,7 @@ func chunkVolumeDelete(args []string, stdout, stderr io.Writer) int { if volumeID == "" || master == "" || requestID == "" || timeout <= 0 { return chunkFail("volume-delete", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "a volume, --master and --request-id are required; --timeout must be positive", false) } - cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, stdout, stderr) + cat, closeFn, exit := chunkCatalog("volume-delete", filer, base, true, timeout, stdout, stderr) if exit >= 0 { return exit } From 3166854cbecc867fdd3ec0b88561e4d9ec8e3dbe Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:30:20 -0800 Subject: [PATCH 12/25] blockvolume: delete --chunk-dirty-threshold outright (pre-GA); a unit passing it fails at start Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 5 --- .../cmd/blockvolume/chunk_remote_test.go | 31 ++++++------------- seaweed-block/cmd/blockvolume/main.go | 10 +----- .../core/host/volume/chunk_control.go | 2 +- .../docs/design/agent-workspace-design.md | 2 +- seaweed-block/docs/standalone-deployment.md | 2 -- 6 files changed, 12 insertions(+), 40 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 1bc51d1c8d..f947f87823 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -31,10 +31,6 @@ const ( defaultChunkIntentTTL = time.Hour ) -// chunkDirtyThresholdRemoval is when --chunk-dirty-threshold, accepted and -// ignored since cuts stage by the COW budget (M5 Stage), is removed. -const chunkDirtyThresholdRemoval = "2027-01-31" - type chunkFlags struct { detachPrecopy bool hostLimit hostlimit.Config @@ -45,7 +41,6 @@ type chunkFlags struct { captureInterval time.Duration maintenanceInterval time.Duration automaticGC bool - dirtyThreshold int // deprecated, ignored (chunkDirtyThresholdRemoval) uploadConcurrency int hydrationWorkers int hydrationQueueDepth int diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index 51dd5615ae..b4083a1648 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -31,8 +31,8 @@ func TestWALStoreChunkFlags(t *testing.T) { if err != nil { t.Fatal(err) } - if d.chunk.captureInterval != 15*time.Minute || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC || len(d.warnings) != 0 { - t.Fatalf("scheduler defaults interval %s warnings %v, want capture 15m, maintenance 1h, GC off and no warning", d.chunk.captureInterval, d.warnings) + if d.chunk.captureInterval != 15*time.Minute || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC { + t.Fatalf("scheduler defaults interval %s, want capture 15m, maintenance 1h and GC off", d.chunk.captureInterval) } off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=0")) @@ -122,25 +122,12 @@ func TestChunkHolderIsServerAndReplica(t *testing.T) { } } -// --chunk-dirty-threshold is deprecated (O-OPS-1): a cut stages by the -// copy-on-write budget (M5 Stage), so the flag never had an effect. It is -// still accepted, with any value and any durable implementation, and warns -// with its removal date; nothing reads its value. -func TestChunkDirtyThresholdIsDeprecatedAndIgnored(t *testing.T) { - base := func(extra ...string) []string { - return append(phase150RequiredBlockvolumeArgs(), extra...) - } - for _, args := range [][]string{ - base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=512"), - base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=-1"), - base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-dirty-threshold=8"), - } { - f, err := parseFlags(args) - if err != nil { - t.Fatalf("%v: refused: %v", args, err) - } - if len(f.warnings) != 1 || !strings.Contains(f.warnings[0], "deprecated") || !strings.Contains(f.warnings[0], chunkDirtyThresholdRemoval) { - t.Fatalf("%v: warnings %v; want one deprecation warning naming %s", args, f.warnings, chunkDirtyThresholdRemoval) - } +// --chunk-dirty-threshold is gone (O-OPS-1): a cut stages by the +// copy-on-write budget (M5 Stage), so the flag never had an effect. A unit +// that still passes it fails at start. +func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=512") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "flag provided but not defined") { + t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err) } } diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 2fcf691f2c..14817c657f 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -42,7 +42,6 @@ import ( ) type flags struct { - warnings []string // printed at start (deprecated flags) cpuProfileDir string memoryLimitMiB int64 masterAddr string @@ -210,7 +209,6 @@ func parseFlags(args []string) (flags, error) { 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)") - fs.IntVar(&f.chunk.dirtyThreshold, "chunk-dirty-threshold", 0, "deprecated and ignored: a cut stages by the copy-on-write budget, not a chunk count; removed after "+chunkDirtyThresholdRemoval) fs.BoolVar(&f.chunk.controlEndpoint, "chunk-control-endpoint", false, "walstore-chunk: expose the /chunk/* control routes (cut, snapshot, snapshots, snapshot/delete, detach) on the status HTTP listener; off by default; loopback-only like the listener") fs.UintVar(&f.durableBlocks, "durable-blocks", 2048, "number of blocks per volume on first create (ignored when opening existing)") fs.UintVar(&f.durableBlockSize, "durable-blocksize", 4096, "block size in bytes on first create") @@ -253,11 +251,8 @@ func parseFlags(args []string) (flags, error) { } memoryFlagSet := false fs.Visit(func(fl *flag.Flag) { - switch fl.Name { - case "memory-limit-mib": + if fl.Name == "memory-limit-mib" { memoryFlagSet = true - case "chunk-dirty-threshold": - f.warnings = append(f.warnings, "--chunk-dirty-threshold is deprecated and has no effect (a cut stages by the copy-on-write budget); it is removed after "+chunkDirtyThresholdRemoval) } }) if !memoryFlagSet && os.Getenv("GOMEMLIMIT") != "" { @@ -588,9 +583,6 @@ func durableCreateGeometry(f flags) (uint32, int, error) { } func run(f flags) int { - for _, w := range f.warnings { - fmt.Fprintln(os.Stderr, "blockvolume: warning:", w) - } // Diagnostics first: parseFlags validated the directory, and nothing // has been activated yet, so a failure here leaves nothing to clean up. stopProfile, err := startCPUProfileSignal(f.cpuProfileDir) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index bc05328565..c95359db6e 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -93,7 +93,7 @@ type ChunkCutStatsBody struct { StagedChunks int `json:"stagedChunks"` StagedChunksUsed int `json:"stagedChunksUsed"` BarrierCopyChunks int `json:"barrierCopyChunks"` - BarrierOverBound bool `json:"barrierOverBound"` // always false in production (legacy fixture bound only); deprecated with --chunk-dirty-threshold + BarrierOverBound bool `json:"barrierOverBound"` // always false in production (legacy fixture bound only); goes with the status schema (O-OPS-2) } func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 6aabd7faef..3cdd1a326b 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -122,7 +122,7 @@ Per volume, under the chunk base directory in the filer (`core/frontend/chunksto `chunkLayerImpl.captureLocked` (`core/storage/chunk_layer.go`; contract in the `chunk_seam.go` header). A checkpoint is not a prefix image (the extent can already hold blocks newer than the checkpoint), so a cut is a quiesced point, not a checkpoint boundary. 1. **Admit:** refuse when closed, fenced, detached, during a base install, or when `CaptureAllowed` fails (healthy primary, unchanged lineage, valid lease). -2. **Pre-copy:** while the chunks that would be copied under the barrier exceed half the copy-on-write side budget, stage the hottest of them per round outside the barrier, repeating only while the remainder shrinks (`stage`). The deprecated `--chunk-dirty-threshold` has no effect here. A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. +2. **Pre-copy:** while the chunks that would be copied under the barrier exceed half the copy-on-write side budget, stage the hottest of them per round outside the barrier, repeating only while the remainder shrinks (`stage`). A staged chunk with new bytes is uploaded under a fresh key named by an intent written first. 3. **Quiesce:** take the capture barrier (walstore `captureMu`) exclusively, then `Sync`. H is the synced LSN; no data newer than H exists in the WAL or the extent. 4. **Open and copy:** install the fixed candidate window under the barrier, then release it. Bounded workers copy through the validated reader outside the barrier. A first writer saves a pending candidate before mutation; a writer waits only for its own copying/saving chunk. A staged copy is reused only if its version and HEAD still match. Pause is Sync plus candidate/window installation, independent of copy bytes. 5. **LSN guard:** if H is below HEAD's `RemoteLSN`, refuse (`lsn_behind`). diff --git a/seaweed-block/docs/standalone-deployment.md b/seaweed-block/docs/standalone-deployment.md index 75fea226a2..1e1f3e1d4f 100644 --- a/seaweed-block/docs/standalone-deployment.md +++ b/seaweed-block/docs/standalone-deployment.md @@ -128,8 +128,6 @@ the example units, which turn them into flags. blockvolume itself reads only | `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one | | `SWB_VOLUME_EXTRA_ARGS` | any | empty | Other flags (Kubernetes gate and source-gated flags) | -`--chunk-dirty-threshold` (and `SWB_CHUNK_DIRTY_THRESHOLD`) is deprecated and ignored: a cut stages by its copy-on-write budget, not a chunk count. It is still accepted with a startup warning, and it is removed after 2027-01-31. With it, the `barrierOverBound` field of a cut's result is always `false` in production; it goes with the flag. - The `--chunk-*` and `--workspace-lease` flags are refused unless `--durable-impl=walstore-chunk`; leave them at their defaults otherwise. From 23c23b72aaa5bd3caa8d9df901ef0aae1dfac8a4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:35:28 -0800 Subject: [PATCH 13/25] status schema: durable volume, chunk and write profile field comments Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 46 +++--- .../core/frontend/durable/write_profile.go | 92 ++++++------ seaweed-block/docs/status-schema.md | 138 +++++++++--------- 3 files changed, 138 insertions(+), 138 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 55eb72554b..82747b2512 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -291,23 +291,23 @@ type volHandle struct { // handle. It intentionally exposes lineage and readiness facts without giving // callers a control surface. type VolumeStatus struct { - VolumeID string - Path string - Impl string - ReplicaID string - Epoch uint64 - EndpointVersion uint64 - Latched bool - Operational bool - FrontierKnown bool - DurableLSN uint64 - RetainedLSN uint64 - HeadLSN uint64 - Evidence string - Closed bool - WriteProfile WriteProfileStatus - DataSync *storage.DataSyncStatus `json:",omitempty"` - CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` + VolumeID string // the volume + Path string // its store path under --durable-root + Impl string // the durable implementation (walstore, smartwal, walstore-chunk, ...) + ReplicaID string // the replica this store holds + Epoch uint64 // the epoch the store is latched to; 0 before an assignment + EndpointVersion uint64 // the endpoint version it is latched to + Latched bool // an assignment latched the store (epoch and endpoint version set) + Operational bool // the backend admits I/O now + FrontierKnown bool // DurableLSN, RetainedLSN and HeadLSN are the store's current boundaries + DurableLSN uint64 // R: the newest LSN made durable + RetainedLSN uint64 // S: the oldest LSN the WAL still retains + HeadLSN uint64 // H: the newest LSN written + Evidence string // why the backend is or is not operational + Closed bool // the backend was closed + WriteProfile WriteProfileStatus // write-path counters since start + DataSync *storage.DataSyncStatus `json:",omitempty"` // data-file sync state, where the store has one + CheckpointPersistence *storage.CheckpointPersistenceStatus `json:",omitempty"` // checkpoint persistence state, where the store has one // Chunk is the chunk layer's state and cut counters; walstore-chunk // volumes only. Chunk *ChunkStatus @@ -322,12 +322,12 @@ type VolumeStatus struct { // AwaitingAuthority: recovered, the layer waits for master authority to // attach. Stats is zero until the layer is attached. type ChunkStatus struct { - Attached bool - AwaitingAuthority bool - Fenced bool - RemoteLSN uint64 - Stats storage.ChunkLayerStats - HostBudget any `json:",omitempty"` + Attached bool // the chunk layer is attached to the remote + AwaitingAuthority bool // recovered; the layer waits for master authority to attach + Fenced bool // a newer holder fenced this layer: it publishes nothing + RemoteLSN uint64 // the LSN of the remote HEAD (what the remote holds durably) + Stats storage.ChunkLayerStats // the layer's cut counters; zero until attached + HostBudget any `json:",omitempty"` // the host background-cut budget state, with --host-limit-dir } // NewDurableProvider constructs a provider. view is the ONLY diff --git a/seaweed-block/core/frontend/durable/write_profile.go b/seaweed-block/core/frontend/durable/write_profile.go index 6a2906f655..9192555c67 100644 --- a/seaweed-block/core/frontend/durable/write_profile.go +++ b/seaweed-block/core/frontend/durable/write_profile.go @@ -12,55 +12,55 @@ import ( // It is not a performance API; callers use it to prove which product-owned // path observed the write and roughly where time accumulated. type WriteProfileStatus struct { - DurabilityLatency DurabilityLatencyStatus - TargetWriteOps uint64 - TargetWriteBytes uint64 - TargetWriteRequestMaxBytes uint64 - TargetWriteDurationNanos uint64 - BackendWriteRequestOps uint64 - BackendWriteRequestBytes uint64 - BackendWriteRequestMaxBytes uint64 - BackendWriteOps uint64 - BackendWriteBytes uint64 - BackendWriteDurationNanos uint64 - BackendStorageWriteCalls uint64 - BackendStorageWriteBlocks uint64 - BackendStorageBatchCalls uint64 - BackendStorageBatchBlocks uint64 - BackendFullBlockBatchCalls uint64 - BackendFullBlockBatchBlocks uint64 - BackendFullBlockBatchMax uint64 - WALCopyOps uint64 - WALCopyBytes uint64 - WALCopyDurationNanos uint64 - WALEncodeOps uint64 - WALEncodeBytes uint64 - WALEncodeDurationNanos uint64 - WALChecksumOps uint64 - WALChecksumBytes uint64 - WALChecksumDurationNanos uint64 - WALAppendOps uint64 - WALAppendBytes uint64 - WALAppendDurationNanos uint64 - WALAppendLockWaitOps uint64 - WALAppendLockWaitNanos uint64 - WriteCommitLockWaitOps uint64 - WriteCommitLockWaitNanos uint64 - WALAppendWriteAtCalls uint64 - WALAppendWriteAtBytes uint64 - WALAppendWriteAtMaxBytes uint64 - WALAppendWrapCount uint64 - WALAppendPaddingBytes uint64 - DirtyMapUpdateOps uint64 - DirtyMapUpdateDurationNanos uint64 - BackendSyncOps uint64 - BackendSyncDurationNanos uint64 + DurabilityLatency DurabilityLatencyStatus // latency distributions of writes, flushes and syncs + TargetWriteOps uint64 // writes the protocol target handed to the volume + TargetWriteBytes uint64 // their bytes + TargetWriteRequestMaxBytes uint64 // the largest of them + TargetWriteDurationNanos uint64 // their total time at the target + BackendWriteRequestOps uint64 // write requests that entered the durable backend + BackendWriteRequestBytes uint64 // their bytes + BackendWriteRequestMaxBytes uint64 // the largest of them + BackendWriteOps uint64 // backend writes completed + BackendWriteBytes uint64 // their bytes + BackendWriteDurationNanos uint64 // their total time + BackendStorageWriteCalls uint64 // single-write calls into the store + BackendStorageWriteBlocks uint64 // blocks they wrote + BackendStorageBatchCalls uint64 // batch-write calls into the store + BackendStorageBatchBlocks uint64 // blocks they wrote + BackendFullBlockBatchCalls uint64 // batch calls made only of whole blocks + BackendFullBlockBatchBlocks uint64 // blocks they wrote + BackendFullBlockBatchMax uint64 // the largest such batch, in blocks + WALCopyOps uint64 // WAL record payload copies + WALCopyBytes uint64 // their bytes + WALCopyDurationNanos uint64 // their total time + WALEncodeOps uint64 // WAL record encodes + WALEncodeBytes uint64 // their bytes + WALEncodeDurationNanos uint64 // their total time + WALChecksumOps uint64 // WAL record checksums + WALChecksumBytes uint64 // their bytes + WALChecksumDurationNanos uint64 // their total time + WALAppendOps uint64 // WAL appends + WALAppendBytes uint64 // their bytes + WALAppendDurationNanos uint64 // their total time + WALAppendLockWaitOps uint64 // appends that waited for the WAL append lock + WALAppendLockWaitNanos uint64 // their total wait + WriteCommitLockWaitOps uint64 // writes that waited for the commit lock + WriteCommitLockWaitNanos uint64 // their total wait + WALAppendWriteAtCalls uint64 // file WriteAt calls made by WAL appends + WALAppendWriteAtBytes uint64 // their bytes + WALAppendWriteAtMaxBytes uint64 // the largest of them + WALAppendWrapCount uint64 // times the WAL append wrapped to the start of the log + WALAppendPaddingBytes uint64 // padding bytes written at those wraps + DirtyMapUpdateOps uint64 // dirty-map updates after writes + DirtyMapUpdateDurationNanos uint64 // their total time + BackendSyncOps uint64 // backend syncs (flush, FUA, explicit sync) + BackendSyncDurationNanos uint64 // their total time } type DurabilityLatencyStatus struct { - Frontend iolatency.RequestStatus - BackendSync iolatency.Distribution - WAL *storage.DurabilityLatencyStatus `json:",omitempty"` + Frontend iolatency.RequestStatus // per-request latency at the frontend, by stage + BackendSync iolatency.Distribution // latency of backend syncs + WAL *storage.DurabilityLatencyStatus `json:",omitempty"` // the WAL's own sync latency, where the store reports it } type writeProfile struct { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 9df8f54859..725d939b48 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -67,23 +67,23 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `ReplicaID` | string | this host's replica | | `VolumeCount` | int | number of entries in Volumes | | `Volumes[]` | object | the durable store state of the served volume | -| `Volumes[].VolumeID` | string | — | -| `Volumes[].Path` | string | — | -| `Volumes[].Impl` | string | — | -| `Volumes[].ReplicaID` | string | — | -| `Volumes[].Epoch` | uint64 | — | -| `Volumes[].EndpointVersion` | uint64 | — | -| `Volumes[].Latched` | bool | — | -| `Volumes[].Operational` | bool | — | -| `Volumes[].FrontierKnown` | bool | — | -| `Volumes[].DurableLSN` | uint64 | — | -| `Volumes[].RetainedLSN` | uint64 | — | -| `Volumes[].HeadLSN` | uint64 | — | -| `Volumes[].Evidence` | string | — | -| `Volumes[].Closed` | bool | — | -| `Volumes[].WriteProfile` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | — | +| `Volumes[].VolumeID` | string | the volume | +| `Volumes[].Path` | string | its store path under --durable-root | +| `Volumes[].Impl` | string | the durable implementation (walstore, smartwal, walstore-chunk, ...) | +| `Volumes[].ReplicaID` | string | the replica this store holds | +| `Volumes[].Epoch` | uint64 | the epoch the store is latched to; 0 before an assignment | +| `Volumes[].EndpointVersion` | uint64 | the endpoint version it is latched to | +| `Volumes[].Latched` | bool | an assignment latched the store (epoch and endpoint version set) | +| `Volumes[].Operational` | bool | the backend admits I/O now | +| `Volumes[].FrontierKnown` | bool | DurableLSN, RetainedLSN and HeadLSN are the store's current boundaries | +| `Volumes[].DurableLSN` | uint64 | R: the newest LSN made durable | +| `Volumes[].RetainedLSN` | uint64 | S: the oldest LSN the WAL still retains | +| `Volumes[].HeadLSN` | uint64 | H: the newest LSN written | +| `Volumes[].Evidence` | string | why the backend is or is not operational | +| `Volumes[].Closed` | bool | the backend was closed | +| `Volumes[].WriteProfile` | object | write-path counters since start | +| `Volumes[].WriteProfile.DurabilityLatency` | object | latency distributions of writes, flushes and syncs | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | per-request latency at the frontend, by stage | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | — | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | — | @@ -124,13 +124,13 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].WriteProfile.DurabilityLatency.Frontend.Flushes` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUAWrites` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.Frontend.Failed` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.BackendSync` | object | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync` | object | latency of backend syncs | | `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Count` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.BackendSync.SumNanos` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P50UpperNanos` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P99UpperNanos` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL` | object | — (omitted when empty) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL` | object | the WAL's own sync latency, where the store reports it (omitted when empty) | | `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend` | object | — | | `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Count` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.SumNanos` | uint64 | — | @@ -149,52 +149,52 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P50UpperNanos` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P99UpperNanos` | uint64 | — | | `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.TargetWriteOps` | uint64 | — | -| `Volumes[].WriteProfile.TargetWriteBytes` | uint64 | — | -| `Volumes[].WriteProfile.TargetWriteRequestMaxBytes` | uint64 | — | -| `Volumes[].WriteProfile.TargetWriteDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.BackendWriteRequestOps` | uint64 | — | -| `Volumes[].WriteProfile.BackendWriteRequestBytes` | uint64 | — | -| `Volumes[].WriteProfile.BackendWriteRequestMaxBytes` | uint64 | — | -| `Volumes[].WriteProfile.BackendWriteOps` | uint64 | — | -| `Volumes[].WriteProfile.BackendWriteBytes` | uint64 | — | -| `Volumes[].WriteProfile.BackendWriteDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.BackendStorageWriteCalls` | uint64 | — | -| `Volumes[].WriteProfile.BackendStorageWriteBlocks` | uint64 | — | -| `Volumes[].WriteProfile.BackendStorageBatchCalls` | uint64 | — | -| `Volumes[].WriteProfile.BackendStorageBatchBlocks` | uint64 | — | -| `Volumes[].WriteProfile.BackendFullBlockBatchCalls` | uint64 | — | -| `Volumes[].WriteProfile.BackendFullBlockBatchBlocks` | uint64 | — | -| `Volumes[].WriteProfile.BackendFullBlockBatchMax` | uint64 | — | -| `Volumes[].WriteProfile.WALCopyOps` | uint64 | — | -| `Volumes[].WriteProfile.WALCopyBytes` | uint64 | — | -| `Volumes[].WriteProfile.WALCopyDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.WALEncodeOps` | uint64 | — | -| `Volumes[].WriteProfile.WALEncodeBytes` | uint64 | — | -| `Volumes[].WriteProfile.WALEncodeDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.WALChecksumOps` | uint64 | — | -| `Volumes[].WriteProfile.WALChecksumBytes` | uint64 | — | -| `Volumes[].WriteProfile.WALChecksumDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendOps` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendBytes` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendLockWaitOps` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendLockWaitNanos` | uint64 | — | -| `Volumes[].WriteProfile.WriteCommitLockWaitOps` | uint64 | — | -| `Volumes[].WriteProfile.WriteCommitLockWaitNanos` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendWriteAtCalls` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendWriteAtBytes` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendWriteAtMaxBytes` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendWrapCount` | uint64 | — | -| `Volumes[].WriteProfile.WALAppendPaddingBytes` | uint64 | — | -| `Volumes[].WriteProfile.DirtyMapUpdateOps` | uint64 | — | -| `Volumes[].WriteProfile.DirtyMapUpdateDurationNanos` | uint64 | — | -| `Volumes[].WriteProfile.BackendSyncOps` | uint64 | — | -| `Volumes[].WriteProfile.BackendSyncDurationNanos` | uint64 | — | -| `Volumes[].DataSync` | object | — (omitted when empty) | +| `Volumes[].WriteProfile.TargetWriteOps` | uint64 | writes the protocol target handed to the volume | +| `Volumes[].WriteProfile.TargetWriteBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.TargetWriteRequestMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.TargetWriteDurationNanos` | uint64 | their total time at the target | +| `Volumes[].WriteProfile.BackendWriteRequestOps` | uint64 | write requests that entered the durable backend | +| `Volumes[].WriteProfile.BackendWriteRequestBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.BackendWriteRequestMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.BackendWriteOps` | uint64 | backend writes completed | +| `Volumes[].WriteProfile.BackendWriteBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.BackendWriteDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.BackendStorageWriteCalls` | uint64 | single-write calls into the store | +| `Volumes[].WriteProfile.BackendStorageWriteBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendStorageBatchCalls` | uint64 | batch-write calls into the store | +| `Volumes[].WriteProfile.BackendStorageBatchBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendFullBlockBatchCalls` | uint64 | batch calls made only of whole blocks | +| `Volumes[].WriteProfile.BackendFullBlockBatchBlocks` | uint64 | blocks they wrote | +| `Volumes[].WriteProfile.BackendFullBlockBatchMax` | uint64 | the largest such batch, in blocks | +| `Volumes[].WriteProfile.WALCopyOps` | uint64 | WAL record payload copies | +| `Volumes[].WriteProfile.WALCopyBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALCopyDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALEncodeOps` | uint64 | WAL record encodes | +| `Volumes[].WriteProfile.WALEncodeBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALEncodeDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALChecksumOps` | uint64 | WAL record checksums | +| `Volumes[].WriteProfile.WALChecksumBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALChecksumDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALAppendOps` | uint64 | WAL appends | +| `Volumes[].WriteProfile.WALAppendBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALAppendDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.WALAppendLockWaitOps` | uint64 | appends that waited for the WAL append lock | +| `Volumes[].WriteProfile.WALAppendLockWaitNanos` | uint64 | their total wait | +| `Volumes[].WriteProfile.WriteCommitLockWaitOps` | uint64 | writes that waited for the commit lock | +| `Volumes[].WriteProfile.WriteCommitLockWaitNanos` | uint64 | their total wait | +| `Volumes[].WriteProfile.WALAppendWriteAtCalls` | uint64 | file WriteAt calls made by WAL appends | +| `Volumes[].WriteProfile.WALAppendWriteAtBytes` | uint64 | their bytes | +| `Volumes[].WriteProfile.WALAppendWriteAtMaxBytes` | uint64 | the largest of them | +| `Volumes[].WriteProfile.WALAppendWrapCount` | uint64 | times the WAL append wrapped to the start of the log | +| `Volumes[].WriteProfile.WALAppendPaddingBytes` | uint64 | padding bytes written at those wraps | +| `Volumes[].WriteProfile.DirtyMapUpdateOps` | uint64 | dirty-map updates after writes | +| `Volumes[].WriteProfile.DirtyMapUpdateDurationNanos` | uint64 | their total time | +| `Volumes[].WriteProfile.BackendSyncOps` | uint64 | backend syncs (flush, FUA, explicit sync) | +| `Volumes[].WriteProfile.BackendSyncDurationNanos` | uint64 | their total time | +| `Volumes[].DataSync` | object | data-file sync state, where the store has one (omitted when empty) | | `Volumes[].DataSync.Mode` | string | — | | `Volumes[].DataSync.Reason` | string | — | -| `Volumes[].CheckpointPersistence` | object | — (omitted when empty) | +| `Volumes[].CheckpointPersistence` | object | checkpoint persistence state, where the store has one (omitted when empty) | | `Volumes[].CheckpointPersistence.Successes` | uint64 | — | | `Volumes[].CheckpointPersistence.Refusals` | uint64 | — | | `Volumes[].CheckpointPersistence.Failures` | uint64 | — | @@ -202,11 +202,11 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].CheckpointPersistence.Advances` | uint64 | — | | `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | — | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | -| `Volumes[].Chunk.Attached` | bool | — | -| `Volumes[].Chunk.AwaitingAuthority` | bool | — | -| `Volumes[].Chunk.Fenced` | bool | — | -| `Volumes[].Chunk.RemoteLSN` | uint64 | — | -| `Volumes[].Chunk.Stats` | object | — | +| `Volumes[].Chunk.Attached` | bool | the chunk layer is attached to the remote | +| `Volumes[].Chunk.AwaitingAuthority` | bool | recovered; the layer waits for master authority to attach | +| `Volumes[].Chunk.Fenced` | bool | a newer holder fenced this layer: it publishes nothing | +| `Volumes[].Chunk.RemoteLSN` | uint64 | the LSN of the remote HEAD (what the remote holds durably) | +| `Volumes[].Chunk.Stats` | object | the layer's cut counters; zero until attached | | `Volumes[].Chunk.Stats.Hydration` | object | — | | `Volumes[].Chunk.Stats.Hydration.WorkerLimit` | int | — | | `Volumes[].Chunk.Stats.Hydration.QueueDepth` | int | — | @@ -275,7 +275,7 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCutNs` | int64 | — | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | -| `Volumes[].Chunk.HostBudget` | interface | — (omitted when empty) | +| `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | | `Volumes[].Warnings[]` | string | Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | | `Volumes[].HolesSuspected` | uint64 | (group of `Warnings`) Warnings are the store's typed recovery warnings (e.g. wal_hole_suspected, issue #51); they do not change readiness. HolesSuspected counts the recoveries that found a WAL hole. (omitted when empty) | From 746a50e44b4b27be843d7acf9379796ea9f508d4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:37:07 -0800 Subject: [PATCH 14/25] status schema: storage and latency field comments; every status field documented Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/iolatency/latency.go | 30 +-- .../core/storage/checkpoint_diagnostics.go | 12 +- seaweed-block/core/storage/chunk_hydration.go | 20 +- seaweed-block/core/storage/chunk_seam.go | 42 ++-- seaweed-block/core/storage/data_sync.go | 4 +- .../core/storage/durability_latency.go | 6 +- seaweed-block/docs/status-schema.md | 202 +++++++++--------- 7 files changed, 158 insertions(+), 158 deletions(-) diff --git a/seaweed-block/core/iolatency/latency.go b/seaweed-block/core/iolatency/latency.go index 21a2a82688..c722f6000b 100644 --- a/seaweed-block/core/iolatency/latency.go +++ b/seaweed-block/core/iolatency/latency.go @@ -16,11 +16,11 @@ type Histogram struct { sum atomic.Uint64 } type Distribution struct { - Count uint64 - SumNanos uint64 - P50UpperNanos uint64 - P99UpperNanos uint64 - Buckets [64]uint64 + Count uint64 // samples observed + SumNanos uint64 // their total nanoseconds + P50UpperNanos uint64 // upper bound of the bucket holding the median + P99UpperNanos uint64 // upper bound of the bucket holding the 99th percentile + Buckets [64]uint64 // bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns } func (h *Histogram) Observe(d time.Duration) { @@ -69,16 +69,16 @@ type Requests struct { writes, flushes, fua, failed atomic.Uint64 } type RequestStatus struct { - WriteTotal Distribution - FlushTotal Distribution - FUATotal Distribution - ReceiveToBackend Distribution - AckDispatch Distribution - RequestTotal Distribution - Writes uint64 - Flushes uint64 - FUAWrites uint64 - Failed uint64 + WriteTotal Distribution // end-to-end latency of writes + FlushTotal Distribution // end-to-end latency of flushes + FUATotal Distribution // end-to-end latency of forced-unit-access writes + ReceiveToBackend Distribution // from request receipt to the backend call + AckDispatch Distribution // from backend completion to the acknowledgement sent + RequestTotal Distribution // end-to-end latency of every request + Writes uint64 // writes observed + Flushes uint64 // flushes observed + FUAWrites uint64 // forced-unit-access writes observed + Failed uint64 // requests that completed with an error } func (c *Requests) Snapshot() RequestStatus { diff --git a/seaweed-block/core/storage/checkpoint_diagnostics.go b/seaweed-block/core/storage/checkpoint_diagnostics.go index 68303be17a..4a2ae329e2 100644 --- a/seaweed-block/core/storage/checkpoint_diagnostics.go +++ b/seaweed-block/core/storage/checkpoint_diagnostics.go @@ -14,12 +14,12 @@ import ( // LastAdvance stays frozen. Fields are cumulative atomic observations, not a // coherent frontier. type CheckpointPersistenceStatus struct { - Successes uint64 - Refusals uint64 - Failures uint64 - CheckpointLSN uint64 - Advances uint64 - LastAdvance time.Time + Successes uint64 // checkpoint calls that succeeded (including unchanged ones) + Refusals uint64 // checkpoint calls refused because the map coverage was stale + Failures uint64 // checkpoint calls that failed with an error + CheckpointLSN uint64 // the persisted checkpoint LSN + Advances uint64 // successes that moved CheckpointLSN forward + LastAdvance time.Time // when the latest advance happened; zero if none in this open } func (s *WALStore) CheckpointPersistence() CheckpointPersistenceStatus { diff --git a/seaweed-block/core/storage/chunk_hydration.go b/seaweed-block/core/storage/chunk_hydration.go index acd4e3f8af..510ed56ed2 100644 --- a/seaweed-block/core/storage/chunk_hydration.go +++ b/seaweed-block/core/storage/chunk_hydration.go @@ -16,16 +16,16 @@ const defaultHydrationQueueDepth = 64 // ChunkHydrationStats separates wait refusals from owned fetch outcomes. // A wait refusal is not necessarily a wire completion (a caller may cancel). type ChunkHydrationStats struct { - WorkerLimit int - QueueDepth int - Active int - Queued int - WaitCalls uint64 - Joined uint64 - WaitRefusals uint64 - Fetches uint64 - Completed uint64 - FetchErrors uint64 + WorkerLimit int // fetch workers allowed (--chunk-hydration-workers) + QueueDepth int // fetch queue capacity (--chunk-hydration-queue-depth) + Active int // fetches running now + Queued int // fetches waiting for a worker now + WaitCalls uint64 // reads that waited for a chunk to arrive + Joined uint64 // of those, reads that joined a fetch already running + WaitRefusals uint64 // waits that ended without the chunk (the caller cancelled, or the fetch was not admitted) + Fetches uint64 // fetches started + Completed uint64 // fetches that installed the chunk + FetchErrors uint64 // fetches that failed } type chunkHydrationFlight struct { diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index d2721cfaaa..c3398e8319 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -398,14 +398,14 @@ type chunkLayerConfig struct { // value means "not measured". // SyncPhaseStats are nested details of SyncNs; never add them to SyncNs. type SyncPhaseStats struct { - LifecycleWaitNs int64 `json:"lifecycleWaitNs"` - StoreWaitNs int64 `json:"storeWaitNs"` - GroupCommitNs int64 `json:"groupCommitNs"` - CompletionWaitNs int64 `json:"completionWaitNs"` + LifecycleWaitNs int64 `json:"lifecycleWaitNs"` // waiting for the store's lifecycle lock + StoreWaitNs int64 `json:"storeWaitNs"` // waiting for the store lock + GroupCommitNs int64 `json:"groupCommitNs"` // in the group commit that made the data durable + CompletionWaitNs int64 `json:"completionWaitNs"` // waiting for the sync leader role to validate the completion } type chunkCutStats struct { - SyncPhases SyncPhaseStats + SyncPhases SyncPhaseStats // the parts of SyncNs (never added to it) // Disjoint non-payload intervals within barrier-to-settlement fixed cost. CandidateNs int64 WindowSetupNs int64 @@ -475,22 +475,22 @@ type chunkCutStats struct { // - LastCut, LastCutH and LastCutNs (wall clock, Unix ns) describe the // last successful cut, whatever triggered it. type chunkLayerStats struct { - Hydration ChunkHydrationStats - CutsOK uint64 - CutsNoop uint64 - CutsFailed uint64 - CutsRefused map[string]uint64 - CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload - CASConflicts uint64 - CASUnknown uint64 - PendingUnresolved bool - DirtyChunks int - Reconciling bool - ReconcileDone int - ReconcileTotal int - LastCut chunkCutStats - LastCutH uint64 - LastCutNs int64 + Hydration ChunkHydrationStats // lazy fetches of absent chunks from the remote + CutsOK uint64 // cuts that installed a HEAD + CutsNoop uint64 // cuts with nothing new (no CAS) + CutsFailed uint64 // every other cut failure + CutsRefused map[string]uint64 // refusals by reason: admission, fenced, detached + CutsAborted map[string]uint64 // saver_capacity, cow_capacity, budget_revoked, upload + CASConflicts uint64 // HEAD CAS precondition failures + CASUnknown uint64 // HEAD CAS results still unresolved after the re-read + PendingUnresolved bool // an unresolved HEAD proposal is held now + DirtyChunks int // chunks dirty since the last HEAD (not counting those awaiting reconciliation) + Reconciling bool // the dirty set is being reconciled against HEAD; no cut publishes meanwhile + ReconcileDone int // chunks compared so far + ReconcileTotal int // chunks to compare + LastCut chunkCutStats // the last successful cut's measurements + LastCutH uint64 // the LSN the last successful cut published + LastCutNs int64 // when it completed (wall clock, Unix ns) // BarrierOverBound counts cuts whose barrier copied more than the // bound after the staging rounds. BarrierOverBound uint64 diff --git a/seaweed-block/core/storage/data_sync.go b/seaweed-block/core/storage/data_sync.go index 960cdf8400..d9c09de74e 100644 --- a/seaweed-block/core/storage/data_sync.go +++ b/seaweed-block/core/storage/data_sync.go @@ -38,8 +38,8 @@ func selectedDataSyncMode(f *os.File) (string, string, error) { // DataSyncStatus is immutable for the lifetime of an open volume. type DataSyncStatus struct { - Mode string - Reason string + Mode string // the data-file sync call in use (fsync or fdatasync) + Reason string // why it was chosen (an explicit SWBLOCK_SYNC, or the automatic choice) } func (s *WALStore) DataSyncPolicy() DataSyncStatus { return s.dataSyncStatus } diff --git a/seaweed-block/core/storage/durability_latency.go b/seaweed-block/core/storage/durability_latency.go index d72c974cf2..aab547da7e 100644 --- a/seaweed-block/core/storage/durability_latency.go +++ b/seaweed-block/core/storage/durability_latency.go @@ -5,9 +5,9 @@ import "github.com/seaweedfs/seaweed-block/core/iolatency" // DurabilityLatencyStatus separates request queue residence from physical file // sync attempts. A shared sync has one sample, not one sample per waiter. type DurabilityLatencyStatus struct { - WALAppend iolatency.Distribution - GroupCommitWait iolatency.Distribution - FileSync iolatency.Distribution + WALAppend iolatency.Distribution // WAL append latency + GroupCommitWait iolatency.Distribution // time a sync request waited in the group commit queue + FileSync iolatency.Distribution // physical file syncs (one sample per sync, however many waiters) } func (s *WALStore) DurabilityLatency() DurabilityLatencyStatus { diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index 725d939b48..f78adb287e 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -84,71 +84,71 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].WriteProfile` | object | write-path counters since start | | `Volumes[].WriteProfile.DurabilityLatency` | object | latency distributions of writes, flushes and syncs | | `Volumes[].WriteProfile.DurabilityLatency.Frontend` | object | per-request latency at the frontend, by stage | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Writes` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Flushes` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUAWrites` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Failed` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal` | object | end-to-end latency of writes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.WriteTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal` | object | end-to-end latency of flushes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FlushTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal` | object | end-to-end latency of forced-unit-access writes | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUATotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend` | object | from request receipt to the backend call | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.ReceiveToBackend.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch` | object | from backend completion to the acknowledgement sent | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.AckDispatch.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal` | object | end-to-end latency of every request | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.RequestTotal.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Writes` | uint64 | writes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Flushes` | uint64 | flushes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.FUAWrites` | uint64 | forced-unit-access writes observed | +| `Volumes[].WriteProfile.DurabilityLatency.Frontend.Failed` | uint64 | requests that completed with an error | | `Volumes[].WriteProfile.DurabilityLatency.BackendSync` | object | latency of backend syncs | -| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.BackendSync.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | | `Volumes[].WriteProfile.DurabilityLatency.WAL` | object | the WAL's own sync latency, where the store reports it (omitted when empty) | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Buckets[]` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync` | object | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Count` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.SumNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P50UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P99UpperNanos` | uint64 | — | -| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Buckets[]` | uint64 | — | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend` | object | WAL append latency | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.WALAppend.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait` | object | time a sync request waited in the group commit queue | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.GroupCommitWait.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync` | object | physical file syncs (one sample per sync, however many waiters) | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Count` | uint64 | samples observed | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.SumNanos` | uint64 | their total nanoseconds | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P50UpperNanos` | uint64 | upper bound of the bucket holding the median | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.P99UpperNanos` | uint64 | upper bound of the bucket holding the 99th percentile | +| `Volumes[].WriteProfile.DurabilityLatency.WAL.FileSync.Buckets[]` | uint64 | bucket i counts samples of i significant bits in ns, i.e. [2^(i-1), 2^i) ns | | `Volumes[].WriteProfile.TargetWriteOps` | uint64 | writes the protocol target handed to the volume | | `Volumes[].WriteProfile.TargetWriteBytes` | uint64 | their bytes | | `Volumes[].WriteProfile.TargetWriteRequestMaxBytes` | uint64 | the largest of them | @@ -192,50 +192,50 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].WriteProfile.BackendSyncOps` | uint64 | backend syncs (flush, FUA, explicit sync) | | `Volumes[].WriteProfile.BackendSyncDurationNanos` | uint64 | their total time | | `Volumes[].DataSync` | object | data-file sync state, where the store has one (omitted when empty) | -| `Volumes[].DataSync.Mode` | string | — | -| `Volumes[].DataSync.Reason` | string | — | +| `Volumes[].DataSync.Mode` | string | the data-file sync call in use (fsync or fdatasync) | +| `Volumes[].DataSync.Reason` | string | why it was chosen (an explicit SWBLOCK_SYNC, or the automatic choice) | | `Volumes[].CheckpointPersistence` | object | checkpoint persistence state, where the store has one (omitted when empty) | -| `Volumes[].CheckpointPersistence.Successes` | uint64 | — | -| `Volumes[].CheckpointPersistence.Refusals` | uint64 | — | -| `Volumes[].CheckpointPersistence.Failures` | uint64 | — | -| `Volumes[].CheckpointPersistence.CheckpointLSN` | uint64 | — | -| `Volumes[].CheckpointPersistence.Advances` | uint64 | — | -| `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | — | +| `Volumes[].CheckpointPersistence.Successes` | uint64 | checkpoint calls that succeeded (including unchanged ones) | +| `Volumes[].CheckpointPersistence.Refusals` | uint64 | checkpoint calls refused because the map coverage was stale | +| `Volumes[].CheckpointPersistence.Failures` | uint64 | checkpoint calls that failed with an error | +| `Volumes[].CheckpointPersistence.CheckpointLSN` | uint64 | the persisted checkpoint LSN | +| `Volumes[].CheckpointPersistence.Advances` | uint64 | successes that moved CheckpointLSN forward | +| `Volumes[].CheckpointPersistence.LastAdvance` | time (RFC 3339) | when the latest advance happened; zero if none in this open | | `Volumes[].Chunk` | object | Chunk is the chunk layer's state and cut counters; walstore-chunk volumes only. | | `Volumes[].Chunk.Attached` | bool | the chunk layer is attached to the remote | | `Volumes[].Chunk.AwaitingAuthority` | bool | recovered; the layer waits for master authority to attach | | `Volumes[].Chunk.Fenced` | bool | a newer holder fenced this layer: it publishes nothing | | `Volumes[].Chunk.RemoteLSN` | uint64 | the LSN of the remote HEAD (what the remote holds durably) | | `Volumes[].Chunk.Stats` | object | the layer's cut counters; zero until attached | -| `Volumes[].Chunk.Stats.Hydration` | object | — | -| `Volumes[].Chunk.Stats.Hydration.WorkerLimit` | int | — | -| `Volumes[].Chunk.Stats.Hydration.QueueDepth` | int | — | -| `Volumes[].Chunk.Stats.Hydration.Active` | int | — | -| `Volumes[].Chunk.Stats.Hydration.Queued` | int | — | -| `Volumes[].Chunk.Stats.Hydration.WaitCalls` | uint64 | — | -| `Volumes[].Chunk.Stats.Hydration.Joined` | uint64 | — | -| `Volumes[].Chunk.Stats.Hydration.WaitRefusals` | uint64 | — | -| `Volumes[].Chunk.Stats.Hydration.Fetches` | uint64 | — | -| `Volumes[].Chunk.Stats.Hydration.Completed` | uint64 | — | -| `Volumes[].Chunk.Stats.Hydration.FetchErrors` | uint64 | — | -| `Volumes[].Chunk.Stats.CutsOK` | uint64 | — | -| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | — | -| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | — | -| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | — | +| `Volumes[].Chunk.Stats.Hydration` | object | lazy fetches of absent chunks from the remote | +| `Volumes[].Chunk.Stats.Hydration.WorkerLimit` | int | fetch workers allowed (--chunk-hydration-workers) | +| `Volumes[].Chunk.Stats.Hydration.QueueDepth` | int | fetch queue capacity (--chunk-hydration-queue-depth) | +| `Volumes[].Chunk.Stats.Hydration.Active` | int | fetches running now | +| `Volumes[].Chunk.Stats.Hydration.Queued` | int | fetches waiting for a worker now | +| `Volumes[].Chunk.Stats.Hydration.WaitCalls` | uint64 | reads that waited for a chunk to arrive | +| `Volumes[].Chunk.Stats.Hydration.Joined` | uint64 | of those, reads that joined a fetch already running | +| `Volumes[].Chunk.Stats.Hydration.WaitRefusals` | uint64 | waits that ended without the chunk (the caller cancelled, or the fetch was not admitted) | +| `Volumes[].Chunk.Stats.Hydration.Fetches` | uint64 | fetches started | +| `Volumes[].Chunk.Stats.Hydration.Completed` | uint64 | fetches that installed the chunk | +| `Volumes[].Chunk.Stats.Hydration.FetchErrors` | uint64 | fetches that failed | +| `Volumes[].Chunk.Stats.CutsOK` | uint64 | cuts that installed a HEAD | +| `Volumes[].Chunk.Stats.CutsNoop` | uint64 | cuts with nothing new (no CAS) | +| `Volumes[].Chunk.Stats.CutsFailed` | uint64 | every other cut failure | +| `Volumes[].Chunk.Stats.CutsRefused{}` | uint64 | refusals by reason: admission, fenced, detached | | `Volumes[].Chunk.Stats.CutsAborted{}` | uint64 | saver_capacity, cow_capacity, budget_revoked, upload | -| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | — | -| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | — | -| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | — | -| `Volumes[].Chunk.Stats.DirtyChunks` | int | — | -| `Volumes[].Chunk.Stats.Reconciling` | bool | — | -| `Volumes[].Chunk.Stats.ReconcileDone` | int | — | -| `Volumes[].Chunk.Stats.ReconcileTotal` | int | — | -| `Volumes[].Chunk.Stats.LastCut` | object | — | -| `Volumes[].Chunk.Stats.LastCut.SyncPhases` | object | — | -| `Volumes[].Chunk.Stats.LastCut.SyncPhases.lifecycleWaitNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | — | -| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | — | +| `Volumes[].Chunk.Stats.CASConflicts` | uint64 | HEAD CAS precondition failures | +| `Volumes[].Chunk.Stats.CASUnknown` | uint64 | HEAD CAS results still unresolved after the re-read | +| `Volumes[].Chunk.Stats.PendingUnresolved` | bool | an unresolved HEAD proposal is held now | +| `Volumes[].Chunk.Stats.DirtyChunks` | int | chunks dirty since the last HEAD (not counting those awaiting reconciliation) | +| `Volumes[].Chunk.Stats.Reconciling` | bool | the dirty set is being reconciled against HEAD; no cut publishes meanwhile | +| `Volumes[].Chunk.Stats.ReconcileDone` | int | chunks compared so far | +| `Volumes[].Chunk.Stats.ReconcileTotal` | int | chunks to compare | +| `Volumes[].Chunk.Stats.LastCut` | object | the last successful cut's measurements | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases` | object | the parts of SyncNs (never added to it) | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.lifecycleWaitNs` | int64 | waiting for the store's lifecycle lock | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.storeWaitNs` | int64 | waiting for the store lock | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.groupCommitNs` | int64 | in the group commit that made the data durable | +| `Volumes[].Chunk.Stats.LastCut.SyncPhases.completionWaitNs` | int64 | waiting for the sync leader role to validate the completion | | `Volumes[].Chunk.Stats.LastCut.CandidateNs` | int64 | Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.WindowSetupNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | | `Volumes[].Chunk.Stats.LastCut.PublishPrepareNs` | int64 | (group of `CandidateNs`) Disjoint non-payload intervals within barrier-to-settlement fixed cost. | @@ -271,8 +271,8 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | | `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | | `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | -| `Volumes[].Chunk.Stats.LastCutH` | uint64 | — | -| `Volumes[].Chunk.Stats.LastCutNs` | int64 | — | +| `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published | +| `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. | | `Volumes[].Chunk.Stats.AbsentChunks` | int | AbsentChunks is the number of HEAD-named chunks still absent with a block not local (what HydrateAll would still fetch); 0 = fully local. | | `Volumes[].Chunk.HostBudget` | interface | the host background-cut budget state, with --host-limit-dir (omitted when empty) | From 9ab17cef8139358da7bbbebdbce4f8de9d4a1d7f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:37:22 -0800 Subject: [PATCH 15/25] status schema: every registered /status route is covered Co-Authored-By: Claude Opus 5.5 --- .../core/host/volume/status_schema_test.go | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/seaweed-block/core/host/volume/status_schema_test.go b/seaweed-block/core/host/volume/status_schema_test.go index 2222189579..348909f843 100644 --- a/seaweed-block/core/host/volume/status_schema_test.go +++ b/seaweed-block/core/host/volume/status_schema_test.go @@ -281,3 +281,28 @@ func TestStatusBodiesMatchTheRoutes(t *testing.T) { } } } + +// Every /status route the server registers is in the schema. +func TestStatusSchemaCoversEveryRoute(t *testing.T) { + listed := map[string]bool{} + for _, r := range statusRoutes { + listed[r.route] = true + } + for _, file := range []string{"status_server.go", "chunk_control.go"} { + src, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(src), "\n") { + i := strings.Index(line, `HandleFunc("/status`) + if i < 0 { + continue + } + route := line[i+len(`HandleFunc("`):] + route = route[:strings.Index(route, `"`)] + if !listed[route] { + t.Errorf("%s registers %s, which docs/status-schema.md does not cover", file, route) + } + } + } +} From 1192866f2ea0712dddd9cb8c21d330767c479464 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:57:56 -0800 Subject: [PATCH 16/25] volume: barrierOverBound comment describes the field only Co-Authored-By: Claude Opus 5.5 --- seaweed-block/core/host/volume/chunk_control.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c95359db6e..e23dc7b6f6 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -93,7 +93,7 @@ type ChunkCutStatsBody struct { StagedChunks int `json:"stagedChunks"` StagedChunksUsed int `json:"stagedChunksUsed"` BarrierCopyChunks int `json:"barrierCopyChunks"` - BarrierOverBound bool `json:"barrierOverBound"` // always false in production (legacy fixture bound only); goes with the status schema (O-OPS-2) + BarrierOverBound bool `json:"barrierOverBound"` // always false in production: its bound is set only by legacy test fixtures } func cutStatsBody(s storage.ChunkCutStats) ChunkCutStatsBody { From b846b3ada48d83a90f37cb535670c1e938a996f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:58:09 -0800 Subject: [PATCH 17/25] blockvolume: test comment describes the behaviour only Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index b4083a1648..40a87bead6 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -122,7 +122,7 @@ func TestChunkHolderIsServerAndReplica(t *testing.T) { } } -// --chunk-dirty-threshold is gone (O-OPS-1): a cut stages by the +// --chunk-dirty-threshold is gone: a cut stages by the // copy-on-write budget (M5 Stage), so the flag never had an effect. A unit // that still passes it fails at start. func TestChunkDirtyThresholdFlagIsGone(t *testing.T) { From 1ef132686657db69476201e6205d8fdf99a145f6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Fri, 20 Nov 2026 23:58:32 -0800 Subject: [PATCH 18/25] sw-block: start-check comments describe the behaviour only Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/sw-block/chunk.go | 2 +- seaweed-block/cmd/sw-block/chunk_start_check_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/seaweed-block/cmd/sw-block/chunk.go b/seaweed-block/cmd/sw-block/chunk.go index 983a7ca611..7942b7a517 100644 --- a/seaweed-block/cmd/sw-block/chunk.go +++ b/seaweed-block/cmd/sw-block/chunk.go @@ -43,7 +43,7 @@ var dialChunkFiler = func(addr string) (chunkstore.Filer, func() error, error) { } // checkSingleFiler is the start check of a command that writes chunk -// metadata (O-ENG-4): block metadata goes through exactly one filer, the +// metadata: block metadata goes through exactly one filer, the // same rule blockvolume enforces at start. Tests replace it. var checkSingleFiler = func(ctx context.Context, f chunkstore.Filer) error { if s, ok := f.(*chunkstore.SWFS); ok { diff --git a/seaweed-block/cmd/sw-block/chunk_start_check_test.go b/seaweed-block/cmd/sw-block/chunk_start_check_test.go index f3c5e61ab1..05ff3c2399 100644 --- a/seaweed-block/cmd/sw-block/chunk_start_check_test.go +++ b/seaweed-block/cmd/sw-block/chunk_start_check_test.go @@ -10,7 +10,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore" ) -// O-ENG-4: every ops chunk command that writes chunk metadata runs the +// Every ops chunk command that writes chunk metadata runs the // single-filer start check before it reads or writes anything, and refuses // when the filer is not the only one of its group; read-only commands (and // read-only modes) do not run it. From 5bb512d0f03cb2ad55ac8cfe99b1734d6f312ca6 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 01:22:15 -0800 Subject: [PATCH 19/25] spec: ForkDelete model and its configurations (exhausted) The fork/restore versus snapshot delete model this change rests on, byte for byte as checked (sha256 c9c7c7fa), with its 28 configurations: 11 safe (exhausted, no error, 18,672 to 15.7 M states, including every boundary G = D + E + P), 12 reds and 5 witnesses each on its expected property. README rows; the invariant rows drop the simulation tag. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/ForkDelete.tla | 305 ++++++++++++++++++ seaweed-block/docs/spec/README.md | 2 + .../spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg | 19 ++ .../spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg | 19 ++ .../spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg | 19 ++ .../spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg | 19 ++ .../cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg | 19 ++ .../cfg/ForkDelete_red_deletedNotRooted.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg | 19 ++ .../spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg | 19 ++ .../cfg/ForkDelete_red_noDeadlineCheck.cfg | 19 ++ .../spec/cfg/ForkDelete_red_noRetryReread.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg | 19 ++ .../spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg | 19 ++ .../docs/spec/cfg/ForkDelete_wit_benefit.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_benefit_na_P1.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_deadlineLoss.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_gcDeletes.cfg | 20 ++ .../spec/cfg/ForkDelete_wit_retryNotFound.cfg | 20 ++ 31 files changed, 845 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/docs/spec/ForkDelete.tla create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg create mode 100644 seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index e826296eca..923982c787 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -570,7 +570,7 @@ Notes: | `INV-GC-CLOCK-SKEW-001` | Time-based GC eligibility subtracts configured pairwise clock skew (default one minute), plus one second for binding timestamps. Future valid intent/deletion stamps retain roots without blocking unrelated work. Future/backward or differently configured marks supply no elapsed coverage; malformed marks still refuse. This assumes clocks stay within the configured pairwise bound. | M6 intent expiry, deleting snapshot roots, bound → tombstoned | `core/frontend/chunkstore/gc.go` `oldEnough`, `run`; `gc_copy.go` `SweepCopies`, `snapshotAttemptHeads`; `gc_execution.go` `readMark`, `executeGC` | `TestGCSkewSnapshotDeleteGraceBothDirections`, `TestGCSkewIntentExpiryUsesConservativeAge`, `TestGCSkewFutureIntentKeepsRootsWithoutBlockingProgress`, `TestGCSkewPersistedCoverageAcrossHosts`, `TestGCSkewBindingAgeIncludesSecondResolution`, `TestGCSkewConfigAndMarkCoverage`, `TestGCSkewBackwardStepDiscardsCoverageAndPreviewDoesNotMutate`, `TestGCSkewFutureCopyDoesNotBlockOtherSettlement` (`core/frontend/chunkstore/gc_clock_skew_test.go`) | `GCClockSkew` `NoEarlyExpiry`, `FutureProtects`, `IndependentProgress`, `EventuallyEligibleAtBound` | ACTIVE | | `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period is at least the catalog operation deadline plus the clock skew bound plus the CAS apply bound (default: the operation deadline). | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | `TestGC_GraceConstructorRequiresDeadlineSkewAndApplyBound` (`core/frontend/chunkstore/gc_volume_test.go`) | `RetentionGCTiming` `NoLiveDelete`; `ForkDelete` `NoGap` (G >= D + E + P) | ACTIVE | | `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt. | 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_RetainSkipsASameNameReplacement` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` (simulation; exhaustive run pending) | ACTIVE | +| `INV-SNAP-DELETE-ANY-ORDER-001` | A snapshot can be deleted (explicitly or by retention) in any order with forks and restores: no fork claim refuses or delays it. A fork publishes only before its read time + deadline, and GC keeps a deleted attempt rooted for its grace (see note). | M6 snapshot: published → deleting, published → fork \| restore | `core/frontend/chunkstore/catalog.go` `Fork`, `readForkParent`, `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting`; `core/frontend/chunkstore/gc.go` `NewCollector` | `TestSnapshotDelete_ForkRetryAfterDeleteRereadsTheParent`, `TestSnapshotDelete_DeleteDuringAForkInFlight`, `TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists` (`core/frontend/chunkstore/snapshot_delete_test.go`) | `ForkDelete` `NoGap` | 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 | | `INV-HEAD-DELETE-FROZEN-001` | Once HEAD is `deleting`, `purging` or `deleted`, `CASHead` refuses every claim or cut; only the delete's own transitions move it. | M6 HEAD: deleting \| purging \| deleted | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `TestCatalog_DeletedHeadCannotBeRevivedByAClaim` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoPublishAfterCommit` | ACTIVE | diff --git a/seaweed-block/docs/spec/ForkDelete.tla b/seaweed-block/docs/spec/ForkDelete.tla new file mode 100644 index 0000000000..f3014fe1c3 --- /dev/null +++ b/seaweed-block/docs/spec/ForkDelete.tla @@ -0,0 +1,305 @@ +---------------------------- MODULE ForkDelete ---------------------------- +(***************************************************************************) +(* Fork / restore versus snapshot delete with NO lock between them. *) +(* *) +(* Volume V has one published snapshot S naming the chunks 1..NC. A fork *) +(* creates a new volume T whose HEAD will name S's chunks. A delete of S *) +(* never waits for, and is never refused because of, a fork. Safety comes *) +(* from two time rules only: *) +(* (F) the fork reads S at its local time readAt and publishes T's HEAD *) +(* only if its local clock is still < readAt + D (checked right *) +(* before publishing: one atomic step, or, with PublishAtomic=FALSE, *) +(* a check step and a later publish step at most P ticks apart); *) +(* (G) the delete is stamped delAt on the catalog's local clock; GC keeps *) +(* S's chunks rooted while ITS local clock is < delAt + G. *) +(* GC is one atomic step deleting every chunk no root names. Roots: V's *) +(* HEAD (V may overwrite chunks), S while not deleted, S's deleted record *) +(* until the grace has passed, T's HEAD once published. *) +(* *) +(* Time: real time `now` ticks by 1. Actor a reads now + bias[a]; biases *) +(* are fixed at start in -E..E with pairwise difference <= E. Clocks do *) +(* not step and run at the same rate. *) +(* *) +(* Mutant switches are CONSTANTS; the design value is noted on each. *) +(***************************************************************************) +EXTENDS Integers, FiniteSets, TLC + +CONSTANTS + NC, \* chunks 1..NC, all named by S (and by V's HEAD at start) + D, \* operation deadline of the fork (on the fork's clock) + G, \* GC grace after a delete (delAt on the catalog clock, compared on the GC clock) + E, \* pairwise clock skew bound + P, \* max ticks between the deadline check and the publish (PublishAtomic=FALSE only) + MaxNow, \* real-time bound + MaxAttempts, \* fork attempts (1 = no retry) + MaxReads, \* reads of T after its publish (witness only) + VCanOverwrite, \* [TRUE] V may stop naming chunks (nondeterministic action) + \* ---- design switches (design value in brackets) ---- + PublishChecksDeadline, \* [TRUE] publish only if local clock < readAt + D + DeletedRecordRooted, \* [TRUE] deleted S roots its chunks until the grace has passed + PublishAtomic, \* [TRUE] check + publish in one step; FALSE: two steps <= P ticks apart + RetryAfterDelete \* [TRUE] a retry re-reads S (fails if deleted); FALSE: reuses old chunk set + +ASSUME NC \in Nat /\ D \in Nat /\ G \in Nat /\ E \in Nat /\ P \in Nat /\ MaxNow \in Nat + +Chunks == 1..NC +SChunks == Chunks +Actors == {"F", "C", "GC"} \* fork process, catalog (stamps delete), garbage collector +NoTime == -1000 +FStates == {"idle", "read", "created", "checked", "published", "failed", "crashed", "notfound"} + +VARIABLES + now, \* real time + bias, \* actor -> clock bias (fixed after Init) + vNames, \* chunks V's HEAD still names + sDeleted, \* S has been deleted + delAt, \* catalog-local time stamped on the delete (NoTime before) + exists, \* chunk -> still stored + fst, \* fork state + attempts, \* fork attempts started + readAt, \* fork-local time of the current attempt's read + readSet, \* chunk set held by the fork (from the last real read of S) + haveRead, \* some attempt has read S successfully + checkAt, \* real time of the deadline check (two-step publish only) + tPub, \* T's HEAD is published + tHead, \* chunks named by T's HEAD + nReads, \* reads of T done + \* ---- history (witnesses / trace readability) ---- + pubAfterDel, \* T's HEAD was published after S was deleted + lateReadOK, \* T read all its chunks after the grace passed, with V no longer naming them + deadlineLoss, \* a fork attempt failed cleanly on the deadline + retryNotFound, \* a retry got "snapshot not found" + lastAct \* name of the last action (for traces) + +forkVars == <> +tVars == <> +histVars == <> +vars == <> + +LC(a) == now + bias[a] \* local clock of actor a + +TypeOK == + /\ now \in 0..MaxNow + /\ bias \in [Actors -> -E..E] + /\ vNames \subseteq Chunks + /\ sDeleted \in BOOLEAN + /\ delAt \in Int + /\ exists \in [Chunks -> BOOLEAN] + /\ fst \in FStates + /\ attempts \in 0..MaxAttempts + /\ readAt \in Int + /\ readSet \subseteq Chunks + /\ haveRead \in BOOLEAN + /\ checkAt \in Int + /\ tPub \in BOOLEAN + /\ tHead \subseteq Chunks + /\ nReads \in 0..MaxReads + /\ pubAfterDel \in BOOLEAN + /\ lateReadOK \in BOOLEAN + /\ deadlineLoss \in BOOLEAN + /\ retryNotFound \in BOOLEAN + /\ lastAct \in STRING + +Init == + /\ now = 0 + /\ bias \in {b \in [Actors -> -E..E] : (\A x, y \in Actors : b[x] - b[y] <= E)} + /\ vNames = Chunks + /\ sDeleted = FALSE + /\ delAt = NoTime + /\ exists = [c \in Chunks |-> TRUE] + /\ fst = "idle" + /\ attempts = 0 + /\ readAt = NoTime + /\ readSet = {} + /\ haveRead = FALSE + /\ checkAt = NoTime + /\ tPub = FALSE + /\ tHead = {} + /\ nReads = 0 + /\ pubAfterDel = FALSE + /\ lateReadOK = FALSE + /\ deadlineLoss = FALSE + /\ retryNotFound = FALSE + /\ lastAct = "Init" + +(* ============================ time ============================ *) + +\* Real time advances. With a two-step publish, at most P ticks pass between check and publish. +Tick == + /\ now < MaxNow + /\ (PublishAtomic \/ fst # "checked" \/ now < checkAt + P) + /\ now' = now + 1 + /\ lastAct' = "Tick" + /\ UNCHANGED <> + +(* ============================ fork ============================ *) + +\* Start an attempt (first try, or retry after a clean failure or a crash). +ReadSnapshot == + /\ fst \in {"idle", "failed", "crashed"} + /\ attempts < MaxAttempts + /\ attempts' = attempts + 1 + /\ lastAct' = "ReadSnapshot" + /\ (IF ~RetryAfterDelete /\ haveRead + THEN \* mutant: reuse the chunk set of an earlier attempt, no re-read of S + /\ fst' = "read" + /\ readAt' = LC("F") + /\ UNCHANGED <> + ELSE (IF sDeleted + THEN /\ fst' = "notfound" \* "snapshot not found": T never gets a HEAD + /\ retryNotFound' = (retryNotFound \/ attempts > 0) + /\ UNCHANGED <> + ELSE /\ fst' = "read" + /\ readAt' = LC("F") + /\ readSet' = SChunks + /\ haveRead' = TRUE + /\ UNCHANGED retryNotFound)) + /\ UNCHANGED <> + +\* Create T's record (no HEAD yet, no effect on roots). +CreateTarget == + /\ fst = "read" + /\ fst' = "created" + /\ lastAct' = "CreateTarget" + /\ UNCHANGED <> + +DeadlineOK == (~PublishChecksDeadline) \/ (LC("F") < readAt + D) + +\* Publish T's HEAD = the chunk set held by the fork. +DoPublish == + /\ fst' = "published" + /\ tPub' = TRUE + /\ tHead' = readSet + /\ pubAfterDel' = (pubAfterDel \/ sDeleted) + +\* (F) atomic: deadline check and publish in one step. +PublishAtomicStep == + /\ PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ DoPublish + /\ lastAct' = "Publish" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "PublishDeadlineFail" + /\ UNCHANGED <>) + /\ UNCHANGED <> + +\* (F) two-step, step 1: the deadline check. +CheckDeadline == + /\ ~PublishAtomic + /\ fst = "created" + /\ (IF DeadlineOK + THEN /\ fst' = "checked" + /\ checkAt' = now + /\ lastAct' = "CheckDeadlineOK" + /\ UNCHANGED deadlineLoss + ELSE /\ fst' = "failed" + /\ deadlineLoss' = TRUE + /\ lastAct' = "CheckDeadlineFail" + /\ UNCHANGED checkAt) + /\ UNCHANGED <> + +\* (F) two-step, step 2: the publish, no new check (Tick bounds it to <= P ticks after the check). +PublishAfterCheck == + /\ fst = "checked" + /\ DoPublish + /\ lastAct' = "PublishAfterCheck" + /\ UNCHANGED <> + +\* The fork crashes in the middle of an attempt; it may later retry or never continue. +Crash == + /\ fst \in {"read", "created", "checked"} + /\ fst' = "crashed" + /\ lastAct' = "Crash" + /\ UNCHANGED <> + +(* ========================== catalog / V ========================== *) + +\* (G) delete S at any time: stamped on the catalog clock; S stops being a live root. +DeleteS == + /\ ~sDeleted + /\ sDeleted' = TRUE + /\ delAt' = LC("C") + /\ lastAct' = "DeleteS" + /\ UNCHANGED <> + +\* V's HEAD stops naming chunk c (V overwrote it). +VOverwrite(c) == + /\ VCanOverwrite + /\ c \in vNames + /\ vNames' = vNames \ {c} + /\ lastAct' = "VOverwrite" + /\ UNCHANGED <> + +(* ============================== GC ============================== *) + +Rooted(c) == + \/ c \in vNames + \/ ~sDeleted + \/ (DeletedRecordRooted /\ LC("GC") < delAt + G) + \/ (tPub /\ c \in tHead) + +\* One step: delete every stored chunk no root names. +GC == + /\ (\E c \in Chunks : exists[c] /\ ~Rooted(c)) + /\ exists' = [c \in Chunks |-> exists[c] /\ Rooted(c)] + /\ lastAct' = "GC" + /\ UNCHANGED <> + +(* ============================ readers of T ============================ *) + +TRead == + /\ tPub + /\ nReads < MaxReads + /\ nReads' = nReads + 1 + /\ lateReadOK' = (lateReadOK \/ + (/\ sDeleted + /\ vNames \cap tHead = {} + /\ LC("GC") >= delAt + G + /\ (\A c \in tHead : exists[c]))) + /\ lastAct' = "TRead" + /\ UNCHANGED <> + +Next == + \/ Tick + \/ ReadSnapshot + \/ CreateTarget + \/ PublishAtomicStep + \/ CheckDeadline + \/ PublishAfterCheck + \/ Crash + \/ DeleteS + \/ (\E c \in Chunks : VOverwrite(c)) + \/ GC + \/ TRead + +Spec == Init /\ [][Next]_vars + +(* ============================ properties ============================ *) + +\* Whenever T's HEAD is published, every chunk it names exists (checked in every state). +NoGap == tPub => (\A c \in tHead : exists[c]) + +(* Witnesses: each is expected VIOLATED (= the behaviour is reachable). *) +\* Benefit: a fork that read S before the delete publishes after the delete and T reads fine +\* after the grace has passed (only T's HEAD roots the chunks then). +WitNoBenefit == ~(pubAfterDel /\ lateReadOK) +\* A fork loses cleanly because the deadline passed. +WitNoDeadlineLoss == ~deadlineLoss +\* A retry gets "snapshot not found". +WitNoRetryNotFound == ~retryNotFound +\* GC deletes some chunk at all (shows GC is not vacuous in a safe configuration). +WitNoGCDelete == \A c \in Chunks : exists[c] +============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 920aa86a83..31d38356b5 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -98,6 +98,7 @@ Two kinds of config are **expected to violate**: | `ReplicationFailover.tla` | `cfg/S6_*` | design-level | | `RetentionGCTiming.tla` | `cfg/S9_*` | | | `RetentionGCMulti.tla` | `cfg/S9b_*` | | +| `ForkDelete.tla` | `cfg/ForkDelete_*` | snapshot delete in any order with forks | | `RestoreIndependence.tla` | `cfg/RestoreIndependence_*` | independent restore | Each `.cfg` names its spec on its first line. @@ -118,6 +119,7 @@ length of TLC's shortest counterexample. | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | | S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg new file mode 100644 index 0000000000..08a0f98ca5 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D1E1G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 1 + E = 1 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg new file mode 100644 index 0000000000..2461983061 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E0G1.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1, E=0). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 1 + E = 0 + P = 0 + MaxNow = 7 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg new file mode 100644 index 0000000000..5231a1b4ed --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg new file mode 100644 index 0000000000..ccb2842e87 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_D3E2G4.cfg @@ -0,0 +1,19 @@ +\* RED boundary (G = D+E-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 4 + E = 2 + P = 0 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg new file mode 100644 index 0000000000..dde4eaec5e --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_bnd_nc2_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED boundary with 2 chunks. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg new file mode 100644 index 0000000000..350144738f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_deletedNotRooted.cfg @@ -0,0 +1,19 @@ +\* RED: a deleted snapshot stops being a root at once. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = FALSE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg new file mode 100644 index 0000000000..51d3895c09 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P0_D2E1G2.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=0 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 1 + P = 0 + MaxNow = 10 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg new file mode 100644 index 0000000000..95f97f1fd1 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P1_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=1 at the atomic grace G = D+E. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 1 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg new file mode 100644 index 0000000000..ced2c0e10d --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D1E2G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2, E=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 4 + E = 2 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg new file mode 100644 index 0000000000..7a07ed8ad3 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_na_P2_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* RED two-step, P=2 (G = D+E+P-1). Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 2 + MaxNow = 14 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg new file mode 100644 index 0000000000..aa381427c9 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noDeadlineCheck.cfg @@ -0,0 +1,19 @@ +\* RED: publish without the deadline check. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = FALSE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg new file mode 100644 index 0000000000..6460befc5f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_red_noRetryReread.cfg @@ -0,0 +1,19 @@ +\* RED: a retry reuses the earlier chunk set without re-reading S. Expected: NoGap violated. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = FALSE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg new file mode 100644 index 0000000000..73d4fdfd71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D1E1G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 2 + E = 1 + P = 0 + MaxNow = 9 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg new file mode 100644 index 0000000000..e696bfb904 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E0G2.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E, E=0; the brief's 'G <= D' case). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 2 + E = 0 + P = 0 + MaxNow = 8 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg new file mode 100644 index 0000000000..0aa22d44df --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg new file mode 100644 index 0000000000..8cb5038239 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+E+1). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 0 + MaxNow = 12 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg new file mode 100644 index 0000000000..64c5cc8045 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D2E2G6.cfg @@ -0,0 +1,19 @@ +\* SAFE margin (G = D+2E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 6 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg new file mode 100644 index 0000000000..fbdcd1ee9a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_D3E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary (G = D+E). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 3 + G = 5 + E = 2 + P = 0 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg new file mode 100644 index 0000000000..1c85552c5c --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P0_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=0 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg new file mode 100644 index 0000000000..d95d95dd61 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P1_D2E1G4.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=1 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg new file mode 100644 index 0000000000..22712e7e9f --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D1E2G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2, E=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 1 + G = 5 + E = 2 + P = 2 + MaxNow = 16 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg new file mode 100644 index 0000000000..d9ade18294 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_na_P2_D2E1G5.cfg @@ -0,0 +1,19 @@ +\* SAFE two-step, P=2 (G = D+E+P). Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 5 + E = 1 + P = 2 + MaxNow = 15 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg new file mode 100644 index 0000000000..d5b21cec71 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_safe_nc2_D2E1G3.cfg @@ -0,0 +1,19 @@ +\* SAFE boundary with 2 chunks, 3 attempts, 2 reads. Expected: no violation. +SPECIFICATION Spec +CONSTANTS + NC = 2 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 3 + MaxReads = 2 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg new file mode 100644 index 0000000000..96ab829d76 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): fork read before the delete, published after it, T reads fine after the grace. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg new file mode 100644 index 0000000000..c1ad118800 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_benefit_na_P1.cfg @@ -0,0 +1,20 @@ +\* WITNESS two-step P=1 at its safe grace (expected VIOLATED = reachable): benefit still reachable. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 4 + E = 1 + P = 1 + MaxNow = 13 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = FALSE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoBenefit diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg new file mode 100644 index 0000000000..278b224e07 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_deadlineLoss.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a fork fails cleanly on the deadline. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoDeadlineLoss diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg new file mode 100644 index 0000000000..c8e81bc147 --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_gcDeletes.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): GC deletes S's chunks in a safe configuration. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoGCDelete diff --git a/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg new file mode 100644 index 0000000000..ab7b41316a --- /dev/null +++ b/seaweed-block/docs/spec/cfg/ForkDelete_wit_retryNotFound.cfg @@ -0,0 +1,20 @@ +\* WITNESS (expected VIOLATED = reachable): a retry gets snapshot-not-found. +SPECIFICATION Spec +CONSTANTS + NC = 1 + D = 2 + G = 3 + E = 1 + P = 0 + MaxNow = 11 + MaxAttempts = 2 + MaxReads = 1 + VCanOverwrite = TRUE + PublishChecksDeadline = TRUE + DeletedRecordRooted = TRUE + PublishAtomic = TRUE + RetryAfterDelete = TRUE +INVARIANTS + TypeOK + NoGap + WitNoRetryNotFound From 93298f9fa602621c4dd10d54c871d7c6602abc9f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:08:31 -0800 Subject: [PATCH 20/25] fold: restore diagram and model row without claims; post-GC checks name every expected chunk The restore diagram's first state reads the parent (no claim, publish before read time + deadline); the S10 model row is marked as the claim-era model. The two post-GC checks go through chunksMismatch, which requires exactly the expected indexes and every payload; a negative test shows a missing index is caught. Co-Authored-By: Claude Opus 5.5 --- .../chunkstore/snapshot_delete_test.go | 60 ++++++++++++++++--- .../docs/design/agent-workspace-design.md | 8 +-- seaweed-block/docs/spec/README.md | 2 +- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go index 84405652db..35b05e3ed0 100644 --- a/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go +++ b/seaweed-block/core/frontend/chunkstore/snapshot_delete_test.go @@ -3,11 +3,13 @@ package chunkstore import ( "bytes" "context" + "fmt" "path" "testing" "time" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" + "github.com/seaweedfs/seaweed-block/core/storage" ) // INV-SNAP-DELETE-ANY-ORDER-001: forks and restores do not hold their parent. @@ -91,11 +93,7 @@ func TestSnapshotDelete_DeleteDuringAForkInFlight(t *testing.T) { if err != nil { t.Fatal(err) } - for idx, ref := range h2.Chunks { - if got, err := r2.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { - t.Fatalf("fork chunk %d lost: %v", idx, err) - } - } + requireChunks(t, ctx, r2, h2, want, "fork") } // An unknown publish outcome keeps the fork's intent, and that intent roots @@ -150,9 +148,57 @@ func TestSnapshotDelete_UnknownPublishKeepsTheKeysWhileItsIntentExists(t *testin t.Fatal("GC settled the fork intent without the target being resolved") } r1, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + requireChunks(t, ctx, r1, h, want, "parent (fork intent still present)") +} + +// requireChunks fails unless h names exactly the indexes of want and each one +// reads back want's bytes (a missing index cannot pass by iterating h alone). +func requireChunks(t *testing.T, ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte, what string) { + t.Helper() + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("%s: %v", what, err) + } +} + +func chunksMismatch(ctx context.Context, r *ChunkRemote, h storage.ChunkHead, want map[uint64][]byte) error { + if len(h.Chunks) != len(want) { + return fmt.Errorf("HEAD names %d chunks, want %d", len(h.Chunks), len(want)) + } + for idx, data := range want { + ref, ok := h.Chunks[idx] + if !ok { + return fmt.Errorf("HEAD lost chunk %d", idx) + } + if got, err := r.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, data) { + return fmt.Errorf("chunk %d unreadable or changed: %v", idx, err) + } + } + return nil +} + +// The check refuses a HEAD that lost an index, even when every chunk it +// still names reads back correctly. +func TestSnapshotDelete_ChunkCheckCatchesAMissingIndex(t *testing.T) { + f, b, _, h := catalogFixture(t) + ctx := context.Background() + r, _ := NewChunkRemote(f, b, path.Join(catBase, "v1")) + want := map[uint64][]byte{} + missing := uint64(0) for idx, ref := range h.Chunks { - if got, err := r1.Get(ctx, ref.Key); err != nil || !bytes.Equal(got, want[idx]) { - t.Fatalf("parent chunk %d reclaimed while the fork intent exists: %v", idx, err) + data, err := r.Get(ctx, ref.Key) + if err != nil { + t.Fatal(err) + } + want[idx] = data + if idx >= missing { + missing = idx + 1 } + } + if err := chunksMismatch(ctx, r, h, want); err != nil { + t.Fatalf("the matching HEAD failed the check: %v", err) + } + want[missing] = chunkBytes(0x62) // an index the HEAD does not name + if err := chunksMismatch(ctx, r, h, want); err == nil { + t.Fatal("a HEAD missing an expected chunk passed the check") } } diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 790fd99811..e01e8abaf2 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -241,16 +241,16 @@ Restore (target volume): ```mermaid stateDiagram-v2 - [*] --> Claimed: claim parent snapshot, write VOLUME (origin restore) - Claimed --> Restoring: first HEAD (parent's refs, owner-qualified); claim dropped - Claimed --> Aborted: GC tombstones the HEAD + [*] --> Forking: read the parent snapshot, write VOLUME (origin restore) + Forking --> Restoring: first HEAD (parent's refs, owner-qualified) before read time + deadline + Forking --> Aborted: GC tombstones the HEAD Restoring --> Restoring: walker fills; batch cut replaces foreign refs with own keys Restoring --> Independent: no foreign ref in the resolved HEAD; RESTORE-INDEPENDENT created Independent --> [*] Aborted --> [*]: target deleted ``` -Snapshots of the target are refused in `Claimed` and `Restoring`. +Snapshots of the target are refused in `Forking` and `Restoring`. ### Attached-volume scheduling diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 31d38356b5..a6380bb678 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -118,7 +118,7 @@ length of TLC's shortest counterexample. | S5 | `ControlPlane` | Blockmaster authority store: one volume record `{epoch, holder, move journal}`, two retried move requests, durable Puts that succeed, fail, or land with the reply lost, and restarts. | `UniqueEpoch` (issued epochs strictly increase), `Idempotent` (one epoch per request id), `JournalComplete` | `S5_code` pass (298). **RED:** `S5_red_noUncertain` UniqueEpoch violated (5-step: a lost-reply Put, then a reservation from stale memory puts the old assignment back). `S5_red_noReserve` passes (the reservation step is not needed for these invariants). | `core/authority/authority.go:436` applyWithWorkspaceMove (uncertain refusal `:442-444`, Put `:564`, mark uncertain `:568`); `core/authority/workspace.go:309` prepareWorkspaceMoveLocked (expected line `:313`, resume a reserved entry `:324-333`, reserve max+1 `:344-355`), journal replay `:192-219`, persist and mark uncertain `:276-288` | | S6 | `ReplicationFailover` | RF=2: P ships to R, R acks what is durable, the client is acked when both are durable; promotion of R at a new epoch with an evidence gate; R refuses old-epoch shipping; cuts and snapshots cover only the replicated-durable frontier; an in-flight snapshot create from the old primary may still land after the failover. Design-level. | `AckedSurvive`, `HeadOnLineage`, `SnapOnLineage`, `NoStaleAck` | `S6_design` pass (52,897), `S6_design_big` (598,353). **RED:** `S6_red_localCut` HeadOnLineage; `S6_red_noFence` AckedSurvive. `S6_red_noEvidence` passes: with synchronous RF=2 acks the gate is redundant (it matters for quorum or async shipping, not modelled). | `core/transport/replica.go:362` replica rejects a stale-lineage ship entry; `core/replication/volume.go:680` RebaseShipLSN; takeover CAS as in S2 | | S9 | `RetentionGCTiming`, `RetentionGCMulti` | GC timing with an explicit clock: a copy operation with deadline D, marks of duration up to MD, deletion only after two marks at least Grace apart; then marks across two volumes with a fork and a snapshot delete. | `NoLiveDelete` | **Single op:** `S9_rule_G4` (G > D + MD) pass (10,798; `_big` 43,780); G = D passes (`S9_red_G2_noguard`, 11,953). **RED:** `S9_red_G1_noguard`, `S9_red_G1_D3` (G < D) NoLiveDelete violated. **Two volumes:** `S9b_G1_MD2`, `_G2_MD2`, `_G2_MD3`, `_G3_MD1` pass (5,743-9,079). | `core/frontend/chunkstore/gc.go:89` grace > operation deadline, `:280` mark-duration margin, `:306-318` two-mark rule, `:214-221` intent expiry; `catalog.go:896-905` intent deadline re-checked before publish; `gc_copy.go:143`, `:177` a deleting attempt stays a root until grace | -| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. `ClaimUntilHead` selects today's fork claim (dropped at the first HEAD); the strict variant keeps the claim until independent. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | +| S10 | `RestoreIndependence` | Independent restore: claim, two-step fork, hydrate, bounded batch cuts (own keys uploaded under an intent, one HEAD CAS per batch), the independence marker after the last foreign ref, claim drop; GC, source snapshot and volume delete, snapshot retention, and crashes with resume from remote facts at any point. Claim-era model: `ClaimUntilHead` selects the fork claim as it was before fork claims were removed (`INV-SNAP-DELETE-ANY-ORDER-001`), the strict variant keeps it until independent; the code no longer claims, and the no-claim variant ships with the restore driver. | `NoGap` (the target's chunks are always rooted), `Independent`, `NoForeignList`, `ClaimUntilHead_Inv`, `LifecycleFree`, `StateRemote` | **Exhaustive (TLC breadth-first, complete state graph, no error)** at MaxCrash 2, MaxGc 3 (4 for `n4`): option 1 (claim dropped at the first HEAD, the code): `safe` (NIdx 3, Batch 1) 3,639 distinct states; `safe_b2` 4,492; `safe_n4` (NIdx 4, Batch 2) 25,240. Strict variant `strict_claim_until_independent` 1,599 (and 2,003 / 9,838 at the `b2` / `n4` sizes, not shipped as cfgs here). **RED** (each violated at its invariant): `red_drop_claim_at_fork` ClaimUntilHead_Inv; `red_cas_before_upload`, `red_no_intent` NoGap; `red_marker_early`, `red_marker_before_cas`, `red_snap_during_restore` Independent; `red_list_foreign` NoForeignList; `red_resume_local` StateRemote; `red_retention_ignores_marker` LifecycleFree. **Witnesses reached:** `wit_done`, `wit_crash_resume`. Limits: no guest writes to the target while it takes ownership, GC acts immediately (no grace), one restore per snapshot. | `core/frontend/chunkstore/catalog.go` `Restore`, `CreateSnapshot` (restore refusal); `restore.go` `MarkIndependent`, `foreignRefsOf`; `retention.go` `liveClaims`, `forkParentsNeeded`; `gc.go` `Collector.run` (qualified refs rooted by owner); `core/storage/chunk_hydrate_all.go` `HydrateAll`. Batch cuts and the restore driver are not merged yet. | | S11 | `ForkDelete` | Fork or restore against snapshot delete with no claim: the fork reads the parent, may crash and retry (a retry re-reads it), and publishes only before its read time + D, as one atomic step or check-then-publish with up to P ticks between; delete stamps its time; GC (one atomic step) keeps a deleted attempt rooted while its clock is below delete time + G. Three clocks with pairwise skew up to E. | `NoGap` (a published fork HEAD names only existing chunks) | **Exhaustive (TLC breadth-first, complete state graph, no error)**: all 11 safe cfgs, from `safe_D2E0G2` (18,672 distinct states) to `safe_na_P2_D1E2G5` (15,730,209), including every boundary G = D + E + P (atomic and two-step, NC = 2). **RED**, each violating NoGap: the boundary minus one (`red_bnd_*`, `red_na_P*`), `red_noDeadlineCheck`, `red_deletedNotRooted`, `red_noRetryReread`. **Witnesses reached:** `wit_benefit`, `wit_benefit_na_P1`, `wit_deadlineLoss`, `wit_gcDeletes`, `wit_retryNotFound`. Safe iff G >= D + E + P. | `core/frontend/chunkstore/catalog.go` `Fork` (deadline start before `readForkParent`, publish before start + deadline); `retention.go` `markDeleting` (no claim); `gc.go` `NewCollector` (grace >= deadline + skew + CAS apply bound); `gc_copy.go` `snapshotAttemptHeads` (deleted attempt rooted for grace) | ## Limits From e4ec43224f58b71ee20bebe342b81b2cbc1b47ac Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:37:57 -0800 Subject: [PATCH 21/25] test(storage): require complete frozen admission quantities in candidate tail --- .../core/storage/chunk_frozen_report_test.go | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 seaweed-block/core/storage/chunk_frozen_report_test.go diff --git a/seaweed-block/core/storage/chunk_frozen_report_test.go b/seaweed-block/core/storage/chunk_frozen_report_test.go new file mode 100644 index 0000000000..d247b69acb --- /dev/null +++ b/seaweed-block/core/storage/chunk_frozen_report_test.go @@ -0,0 +1,54 @@ +package storage + +import ( + "encoding/json" + "testing" + "time" +) + +func TestCandidateTailReportsCompleteFrozenBudget(t *testing.T) { + for _, tc := range []struct { + name string + fixed time.Duration + samples int + tail uint64 + estimate, slack int64 + known bool + }{ + {"d05_fixed_does_not_fit", 5370 * time.Millisecond, 3, 1000, 5570000000, 0, true}, + {"small_complete_estimate", 200 * time.Millisecond, 3, 1000, 400000000, 4600000000, true}, + {"known_zero_tail", 200 * time.Millisecond, 1, 0, 300000000, 4700000000, true}, + {"zero_tail_without_fixed_sample", 0, 0, 0, 0, 0, false}, + {"partial_unknown_rate", 200 * time.Millisecond, 1, 1000, 300000000, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + l := &chunkLayerImpl{} + for i := 0; i < tc.samples; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: tc.fixed, rate: 20000}) + } + tail := l.estimateCandidateTail(tc.tail) + b, err := json.Marshal(tail) + if err != nil { + t.Fatal(err) + } + var got map[string]json.RawMessage + if err = json.Unmarshal(b, &got); err != nil { + t.Fatal(err) + } + for key, want := range map[string]int64{"frozenEstimateNs": tc.estimate, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": tc.slack} { + var value int64 + if raw, ok := got[key]; !ok { + t.Errorf("missing %s: %s", key, b) + } else if err = json.Unmarshal(raw, &value); err != nil || value != want { + t.Errorf("%s=%s want %d", key, raw, want) + } + } + var known bool + if raw, ok := got["frozenEstimateKnown"]; !ok { + t.Errorf("missing frozenEstimateKnown: %s", b) + } else if err = json.Unmarshal(raw, &known); err != nil || known != tc.known { + t.Errorf("known=%s want %v", raw, tc.known) + } + }) + } +} From 06a841009992426ed955e0d50f2ab0f4c75727b9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 02:44:51 -0800 Subject: [PATCH 22/25] storage: report the complete frozen estimate and refreeze quiesce slack --- .../core/host/volume/chunk_control.go | 16 ++++++- .../host/volume/chunk_frozen_budget_test.go | 47 +++++++++++++++++++ .../core/storage/chunk_frozen_budget.go | 35 ++++++++++++-- .../core/storage/chunk_frozen_report_test.go | 13 +++++ seaweed-block/core/storage/chunk_precopy.go | 3 +- seaweed-block/core/storage/chunk_seam.go | 1 + seaweed-block/docs/design/invariants.md | 6 ++- .../docs/spec/FrozenDetachBudget.tla | 9 +++- seaweed-block/docs/spec/README.md | 18 +++++++ .../docs/spec/cfg/FrozenDetachBudget.cfg | 2 +- 10 files changed, 140 insertions(+), 10 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index c1e4029609..a203d4a27d 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -174,7 +174,14 @@ type snapshotBody struct { Replayed bool `json:"replayed"` } +type chunkFrozenRefusalBody struct { + storage.FrozenBudget + RemainingFreeze time.Duration `json:"remainingFreezeNs"` + GuestFreezeElapsed time.Duration `json:"guestFreezeElapsedNs"` +} + type chunkErrorBody struct { + *chunkFrozenRefusalBody Code string `json:"code"` Message string `json:"message"` Retryable bool `json:"retryable"` @@ -257,7 +264,14 @@ func writeChunkFailure(w http.ResponseWriter, err error) { if errors.As(err, &ce) { msg = ce.Detail() // the code is in its own field } - writeChunkJSON(w, status, chunkErrorBody{Code: code, Message: msg, Retryable: retryable}) + body := chunkErrorBody{Code: code, Message: msg, Retryable: retryable} + var refusal *storage.FrozenRefusal + // INV-WS-FREEZE-ACCOUNTING-001: transport observation, never a second forecast. + if code == "frozen_tail_too_large" && errors.As(err, &refusal) { + r := refusal.Report + body.chunkFrozenRefusalBody = &chunkFrozenRefusalBody{FrozenBudget: r.FrozenBudget, RemainingFreeze: r.RemainingFreeze, GuestFreezeElapsed: r.GuestFreezeElapsed} + } + writeChunkJSON(w, status, body) } // chunkErrorCode maps an operation's error to (HTTP status, code, diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go index 7c9064aadb..fc72ce4797 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -105,3 +105,50 @@ func TestChunkFrozenValidationHasDistinctPreMutationCode(t *testing.T) { } } } + +func TestChunkFrozenRefusalCarriesServerBudget(t *testing.T) { + report := storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 5570 * time.Millisecond, FrozenEstimateKnown: true, FreezeLimit: 5 * time.Second}, Estimate: 5570 * time.Millisecond, RemainingFreeze: 4 * time.Second, GuestFreezeElapsed: time.Second, Reason: "frozen_tail_too_large"} + refusal := &storage.FrozenRefusal{Report: report} + p := &frozenDetachProvider{fakeChunkProvider: &fakeChunkProvider{}, err: refusal} + srv := chunkServer(t, NewChunkControl(p, nil), true) + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d}`, time.Now().Add(-time.Second).UnixNano()) + w := serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + var got map[string]json.RawMessage + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || w.Code != 409 { + t.Fatalf("refusal %d %s", w.Code, w.Body) + } + for key, want := range map[string]int64{"frozenEstimateNs": 5570000000, "freezeLimitNs": 5000000000, "maxRefreezeQuiesceNs": 0, "remainingFreezeNs": 4000000000, "guestFreezeElapsedNs": 1000000000} { + var value int64 + if raw, ok := got[key]; !ok { + t.Errorf("missing %s: %s", key, w.Body) + } else if err := json.Unmarshal(raw, &value); err != nil || value != want { + t.Errorf("%s=%s want%d", key, raw, want) + } + } + var known bool + if err := json.Unmarshal(got["frozenEstimateKnown"], &known); err != nil || !known { + t.Errorf("known lost: %s", w.Body) + } + p.err = &storage.FrozenRefusal{Report: storage.PrecopyReport{FrozenBudget: storage.FrozenBudget{FrozenEstimate: 300 * time.Millisecond, FreezeLimit: 5 * time.Second}, Estimate: 300 * time.Millisecond, Reason: "frozen_tail_too_large", RemainingFreeze: 5 * time.Second}} + w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + got = nil + _ = json.Unmarshal(w.Body.Bytes(), &got) + if string(got["frozenEstimateKnown"]) != "false" || string(got["maxRefreezeQuiesceNs"]) != "0" || string(got["frozenEstimateNs"]) != "300000000" { + t.Fatalf("unknown refusal became an actionable estimate: %s", w.Body) + } + p.err = errors.Join(storage.ErrChunkLayerClosed, refusal) + w = serve(t, srv, http.MethodPost, "/chunk/detach", body, "") + got = nil + if json.Unmarshal(w.Body.Bytes(), &got) != nil { + t.Fatal(w.Body) + } + status, code, _ := chunkErrorCode(storage.ErrChunkLayerClosed) + var gotCode string + _ = json.Unmarshal(got["code"], &gotCode) + if w.Code != status || gotCode != code { + t.Fatalf("terminal precedence lost: %d %s", w.Code, w.Body) + } + if _, ok := got["frozenEstimateNs"]; ok { + t.Fatalf("terminal response offered retry budget: %s", w.Body) + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go index 4f6ce4090e..5c855c824f 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget.go +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -17,6 +17,33 @@ type FrozenDetachOptions struct { StartedAt time.Time AllowOverBudget bool } + +// FrozenBudget reports the exact storage-owned forecast and its quiesce slack. +// INV-WS-FREEZE-ACCOUNTING-001: same-host durations; admission still rechecks. +type FrozenBudget struct { + FrozenEstimate time.Duration `json:"frozenEstimateNs"` + FrozenEstimateKnown bool `json:"frozenEstimateKnown"` + FreezeLimit time.Duration `json:"freezeLimitNs"` + MaxRefreezeQuiesce time.Duration `json:"maxRefreezeQuiesceNs"` +} + +func (r PrecopyReport) frozenBudgetEstimate() FrozenBudget { + b := FrozenBudget{FrozenEstimate: r.Estimate, FrozenEstimateKnown: r.Reason != "samples_unknown" && r.Estimate > 0, FreezeLimit: precopyFreezeLimit} + if b.FrozenEstimateKnown { + b.MaxRefreezeQuiesce = max(time.Duration(0), b.FreezeLimit-b.FrozenEstimate) + } + return b +} + +// FrozenRefusal keeps the admission observation attached to the typed error. +type FrozenRefusal struct{ Report PrecopyReport } + +func (e *FrozenRefusal) Error() string { + r := e.Report + return fmt.Sprintf("%s: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) +} +func (e *FrozenRefusal) Unwrap() error { return ErrFrozenTailTooLarge } + type frozenDetachKey struct{} func WithFrozenDetach(ctx context.Context, opts FrozenDetachOptions) (context.Context, error) { @@ -36,10 +63,12 @@ func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { return r.admitFrozenAt(opts, time.Now()) } func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { + r.FrozenBudget = r.frozenBudgetEstimate() r.GuestFrozen = true r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt)) - r.RemainingFreeze = max(time.Duration(0), precopyFreezeLimit-r.GuestFreezeElapsed) - known := r.Reason != "samples_unknown" && r.Estimate > 0 + budget := r.FrozenBudget + r.RemainingFreeze = max(time.Duration(0), budget.FreezeLimit-r.GuestFreezeElapsed) + known := budget.FrozenEstimateKnown if opts.AllowOverBudget { r.Reason = "over_budget" r.OverBudget = true @@ -56,7 +85,7 @@ func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) b return true } func frozenRefusal(r PrecopyReport) error { - return fmt.Errorf("%w: reason=%s estimate=%s remaining=%s elapsed=%s", ErrFrozenTailTooLarge, r.Reason, r.Estimate, r.RemainingFreeze, r.GuestFreezeElapsed) + return &FrozenRefusal{Report: r} } // IsReplay distinguishes a replayed applied point from a newly completed freeze. diff --git a/seaweed-block/core/storage/chunk_frozen_report_test.go b/seaweed-block/core/storage/chunk_frozen_report_test.go index d247b69acb..7c18bace4c 100644 --- a/seaweed-block/core/storage/chunk_frozen_report_test.go +++ b/seaweed-block/core/storage/chunk_frozen_report_test.go @@ -52,3 +52,16 @@ func TestCandidateTailReportsCompleteFrozenBudget(t *testing.T) { }) } } + +func TestFrozenRefusalRetainsUnknownCompleteEstimate(t *testing.T) { + l := &chunkLayerImpl{precopySamples: []precopySample{{at: time.Now(), fixed: 200 * time.Millisecond, rate: 20000}}} + r := l.precopyEstimate(1000, 0) + now := time.Now() + if r.admitFrozenAt(FrozenDetachOptions{StartedAt: now}, now) { + t.Fatal("unknown rate admitted") + } + refusal, ok := frozenRefusal(r).(*FrozenRefusal) + if !ok || refusal.Report.FrozenEstimateKnown || refusal.Report.MaxRefreezeQuiesce != 0 || refusal.Report.FrozenEstimate != 300*time.Millisecond { + t.Fatalf("partial estimate became known after reason changed: %+v", r) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index da22b9a1a9..0f8d545046 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -80,6 +80,7 @@ type PrecopyAttempt struct { // PrecopyReport records admission estimates, not a worst-case latency proof. type PrecopyReport struct { + FrozenBudget replayed bool // transport-local marker; never replaces the original freeze telemetry. // Live barrier prefix is diagnostic, not additive to the selected forecast. @@ -524,5 +525,5 @@ func (l *chunkLayerImpl) candidateTailBytes() uint64 { func (l *chunkLayerImpl) estimateCandidateTail(bytes uint64) *ChunkCandidateTail { r := l.precopyEstimate(bytes, 0) - return &ChunkCandidateTail{Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} + return &ChunkCandidateTail{FrozenBudget: r.frozenBudgetEstimate(), Bytes: bytes, Estimate: r.TailEstimate, BytesPerSecond: r.BytesPerSecond, RateSamples: r.RateSamples, SampleAge: r.SampleAge, Known: bytes == 0 || r.BytesPerSecond > 0} } diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index d2721cfaaa..09616eb534 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -513,6 +513,7 @@ type chunkLayerStats struct { // Bytes and rate/estimate belong to one sampler observation; Known=false must // never be interpreted as a zero-cost tail. Admission rechecks at its barrier. type ChunkCandidateTail struct { + FrozenBudget Bytes uint64 `json:"bytes"` Estimate time.Duration `json:"estimateNs"` BytesPerSecond float64 `json:"bytesPerSecond"` diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 5023b8dc8a..504e74421b 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -248,7 +248,7 @@ stateDiagram-v2 | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` | -| Checkpoint tail | successful cuts sample remaining candidates and transfer cost from one rate observation after publication; zero bytes is known zero, insufficient history for a nonzero tail is unknown. This is advisory; frozen admission rechecks its own candidates. | `chunk_precopy.go` `candidateTail`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001` | +| Checkpoint tail | one cost observation reports remaining bytes, tail cost, complete frozen estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | @@ -526,7 +526,7 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-WS-FREEZE-ACCOUNTING-001` | A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible` (classification itself does not alter the admission model) | ACTIVE | +| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports the complete estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | | `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | | `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | @@ -557,6 +557,8 @@ Notes: - `INV-CUT-STAGED-REUSE-001`: `captureLocked` also requires HEAD's generation to be the one the stage was compared against (code reading; not asserted by these tests). +- `INV-WS-FREEZE-ACCOUNTING-001` details retained: A frozen detach validates a positive, non-future origin before admission, converts it once to a local monotonic origin, and subtracts elapsed time from the five-second freeze budget at forecast and barrier. Only explicit final override may exceed the forecast budget, and its report records that override and actual elapsed time. New F2 wire fields are durations, not a changed clock-origin request. Existing Unix-nanosecond origin validation/conversion remains; new advice is same-host only. Estimate growth and request delay may cause a bounded refusal, not a promise every advised cycle admits. No new margin. + ### B.6 Workspace: chunk lifecycle, GC and delete | ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | diff --git a/seaweed-block/docs/spec/FrozenDetachBudget.tla b/seaweed-block/docs/spec/FrozenDetachBudget.tla index e8f83cb8ee..e39c3eeffb 100644 --- a/seaweed-block/docs/spec/FrozenDetachBudget.tla +++ b/seaweed-block/docs/spec/FrozenDetachBudget.tla @@ -11,13 +11,15 @@ VARIABLES phase, elapsed, estimate, known, force, authority, admitted, vars == <> Init == /\ phase = "forecast" /\ elapsed \in {0,30,60} - /\ estimate \in {5,30,60} /\ known \in BOOLEAN + /\ estimate \in {0,5,30,60} /\ known \in BOOLEAN /\ force \in BOOLEAN /\ authority \in BOOLEAN /\ admitted = FALSE /\ uploaded = FALSE /\ published = FALSE /\ overBudget = FALSE /\ atElapsed = 0 /\ atEstimate = 0 /\ atKnown = FALSE AuthorityOK == authority \/ OmitAuthority -Fits == known /\ estimate > 0 /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit +FrozenEstimateKnown == known /\ estimate > 0 +MaxRefreezeQuiesce == IF FrozenEstimateKnown /\ estimate < Limit THEN Limit-estimate ELSE 0 +Fits == FrozenEstimateKnown /\ estimate + (IF OmitElapsed THEN 0 ELSE elapsed) <= Limit Eligible == AuthorityOK /\ (force \/ Fits) Forecast == /\ phase = "forecast" /\ Eligible /\ phase' = "stage" /\ UNCHANGED < admitted BudgetAtAdmission == admitted /\ ~force => atKnown /\ atEstimate > 0 /\ atElapsed + atEstimate <= Limit OverrideVisible == admitted /\ force => overBudget AuthorityAtPublication == published => authority +ReportSlackSound == MaxRefreezeQuiesce >= 0 /\ + (MaxRefreezeQuiesce > 0 => known /\ estimate > 0 /\ MaxRefreezeQuiesce + estimate = Limit) /\ + (~FrozenEstimateKnown => MaxRefreezeQuiesce = 0) ============================================================================= diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 920aa86a83..8f430c6481 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -495,3 +495,21 @@ distinct states, depth4. `GCDeleteProgress_stop.cfg` exits12 at `LaterProgress` (2 generated /2 distinct, depth2). The HTTP source red uses an actual400 and checks later reclamation, retained failed tombstones, younger-object progress across separate collectors and permanent no-rebind behavior. + +### Frozen budget response quantities (F2) + +The additive `candidateTail` and typed refusal quantities share storage's +complete estimate, including its existing margin. Tail-known alone is not +complete-estimate-known. `FrozenDetachBudget` now includes estimate zero and +derives `FrozenEstimateKnown` and `MaxRefreezeQuiesce`; `ReportSlackSound` checks +positive slack implies a known positive estimate and slack + estimate = limit. +These durations are same-host advice, not a physical completion bound or a change +to the existing wall-origin request. Admission still rechecks at its barrier. + +TLC 2.19, tools SHA256 `936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88`, +local 2026-11-21 10:43Z: `FrozenDetachBudget.cfg` exhausted 829 generated / 535 +distinct states, depth 6, queue empty, no invariant violation. Bounds: elapsed +{0,30,60}, estimate {0,5,30,60} (then barrier growth), known/force/authority Boolean; +limit 50, no physical I/O latency. Raw quantities and JSON preservation are +checked by native Go tests; this derived arithmetic model does not model the HTTP +encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun. diff --git a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg index 7992b80dde..1fbd6505f5 100644 --- a/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg +++ b/seaweed-block/docs/spec/cfg/FrozenDetachBudget.cfg @@ -5,4 +5,4 @@ CONSTANTS OmitStageGuard = FALSE OmitOverrideRecord = FALSE OmitAuthority = FALSE -INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication +INVARIANTS NoUploadBeforeAdmission BudgetAtAdmission OverrideVisible AuthorityAtPublication ReportSlackSound From 461272afc41339528953c65251b3b58a32ae93d8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:00:18 -0800 Subject: [PATCH 23/25] fix(storage): retain frozen observation on drain refusal --- .../host/volume/chunk_frozen_budget_test.go | 84 +++++++++++++++++++ .../core/storage/chunk_frozen_budget.go | 28 +++++-- .../core/storage/chunk_frozen_report_test.go | 35 ++++++++ seaweed-block/core/storage/chunk_precopy.go | 1 + seaweed-block/docs/design/invariants.md | 6 +- seaweed-block/docs/spec/README.md | 2 + 6 files changed, 149 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go index fc72ce4797..f905b2fe6f 100644 --- a/seaweed-block/core/host/volume/chunk_frozen_budget_test.go +++ b/seaweed-block/core/host/volume/chunk_frozen_budget_test.go @@ -5,8 +5,10 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" "github.com/seaweedfs/seaweed-block/core/storage" "net/http" + "sync" "testing" "time" ) @@ -152,3 +154,85 @@ func TestChunkFrozenRefusalCarriesServerBudget(t *testing.T) { t.Fatalf("terminal response offered retry budget: %s", w.Body) } } + +// Hold a real admitted Sync through the replication observer, so the actual +// frontend drain expires before storage frozen admission. No report is injected. +type frozenDrainObserver struct{ entered, release chan struct{} } + +func (*frozenDrainObserver) Observe(context.Context, uint32, uint64, []byte) error { return nil } +func (o *frozenDrainObserver) Sync(ctx context.Context, _ uint64) error { + close(o.entered) + select { + case <-o.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} +func TestChunkFrozenDrainRefusalCarriesObservedBudget(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + dp, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: 256, ChunkBlocks: 16, + ChunkDetachPrecopy: true, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dp.Close() }) + if _, err = dp.EnsureStorage("v1"); err != nil { + t.Fatal(err) + } + if _, err = dp.RecoverVolume(ctx, "v1"); err != nil { + t.Fatal(err) + } + backend, err := dp.Open(ctx, "v1") + if err != nil { + t.Fatal(err) + } + if _, err = backend.Write(ctx, 4096, make([]byte, 4096)); err != nil { + t.Fatal(err) + } + observer := &frozenDrainObserver{make(chan struct{}), make(chan struct{})} + if err = backend.(*durable.StorageBackend).SetWriteObserver(observer); err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + var once sync.Once + t.Cleanup(func() { + once.Do(func() { close(observer.release) }) + select { + case <-done: + case <-time.After(3 * time.Second): + t.Error("Sync did not join") + } + }) + go func() { done <- backend.Sync(ctx) }() + select { + case <-observer.entered: + case <-ctx.Done(): + t.Fatal("Sync never admitted") + } + before, _ := remote.GetHead(ctx) + puts := remote.Puts() + server := chunkServer(t, NewChunkControl(dp, nil), true) + body := fmt.Sprintf(`{"volumeID":"v1","frozen":true,"freezeStartedAtNs":%d,"allowOverBudget":true}`, time.Now().Add(-time.Second).UnixNano()) + response := serve(t, server, http.MethodPost, "/chunk/detach", body, "") + var got struct { + Code string `json:"code"` + storage.FrozenBudget + Remaining time.Duration `json:"remainingFreezeNs"` + Elapsed time.Duration `json:"guestFreezeElapsedNs"` + } + if err = json.Unmarshal(response.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if response.Code != 409 || got.Code != "frozen_tail_too_large" || got.FreezeLimit != 5*time.Second || got.Elapsed < time.Second || got.Remaining <= 0 || got.Elapsed+got.Remaining != got.FreezeLimit || got.FrozenEstimateKnown || got.MaxRefreezeQuiesce != 0 { + t.Fatalf("real drain refusal lost observation: %d %s", response.Code, response.Body) + } + after, _ := remote.GetHead(ctx) + if after.Gen != before.Gen || remote.Puts() != puts { + t.Fatal("failed drain uploaded or published") + } +} diff --git a/seaweed-block/core/storage/chunk_frozen_budget.go b/seaweed-block/core/storage/chunk_frozen_budget.go index 5c855c824f..1e87bba27b 100644 --- a/seaweed-block/core/storage/chunk_frozen_budget.go +++ b/seaweed-block/core/storage/chunk_frozen_budget.go @@ -18,7 +18,9 @@ type FrozenDetachOptions struct { AllowOverBudget bool } -// FrozenBudget reports the exact storage-owned forecast and its quiesce slack. +// FrozenBudget reports the storage-owned admission forecast and quiesce slack. +// A tail above the existing 60s ceiling is a saturated rejection sentinel, +// not a complete duration: it stays known but offers zero quiesce slack. // INV-WS-FREEZE-ACCOUNTING-001: same-host durations; admission still rechecks. type FrozenBudget struct { FrozenEstimate time.Duration `json:"frozenEstimateNs"` @@ -62,13 +64,17 @@ func FrozenDetachFromContext(ctx context.Context) (FrozenDetachOptions, bool) { func (r *PrecopyReport) admitFrozen(opts FrozenDetachOptions) bool { return r.admitFrozenAt(opts, time.Now()) } -func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { +func (r *PrecopyReport) observeFrozenAt(opts FrozenDetachOptions, now time.Time) { r.FrozenBudget = r.frozenBudgetEstimate() r.GuestFrozen = true r.GuestFreezeElapsed = max(time.Duration(0), now.Sub(opts.StartedAt)) budget := r.FrozenBudget r.RemainingFreeze = max(time.Duration(0), budget.FreezeLimit-r.GuestFreezeElapsed) - known := budget.FrozenEstimateKnown +} + +func (r *PrecopyReport) admitFrozenAt(opts FrozenDetachOptions, now time.Time) bool { + r.observeFrozenAt(opts, now) + known := r.FrozenBudget.FrozenEstimateKnown if opts.AllowOverBudget { r.Reason = "over_budget" r.OverBudget = true @@ -92,12 +98,24 @@ func frozenRefusal(r PrecopyReport) error { // The original report remains unchanged on the wire. func (r PrecopyReport) IsReplay() bool { return r.replayed } -func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { +func (l *chunkLayerImpl) frozenNow() time.Time { now := time.Now() if hook := l.testFrozenNow; hook != nil { now = hook() } - return r.admitFrozenAt(opts, now) + return now +} + +// M5 frozen-detach report: observe before drain/reason handling, without +// deciding admission or overriding an existing refusal. +func (l *chunkLayerImpl) observeFrozen(r *PrecopyReport, opts FrozenDetachOptions, enabled bool) { + if enabled { + r.observeFrozenAt(opts, l.frozenNow()) + } +} + +func (l *chunkLayerImpl) admitFrozen(r *PrecopyReport, opts FrozenDetachOptions) bool { + return r.admitFrozenAt(opts, l.frozenNow()) } // RememberDetachReport completes the telemetry kept with an applied or still diff --git a/seaweed-block/core/storage/chunk_frozen_report_test.go b/seaweed-block/core/storage/chunk_frozen_report_test.go index 7c18bace4c..22430ec208 100644 --- a/seaweed-block/core/storage/chunk_frozen_report_test.go +++ b/seaweed-block/core/storage/chunk_frozen_report_test.go @@ -1,7 +1,9 @@ package storage import ( + "context" "encoding/json" + "errors" "testing" "time" ) @@ -19,6 +21,8 @@ func TestCandidateTailReportsCompleteFrozenBudget(t *testing.T) { {"small_complete_estimate", 200 * time.Millisecond, 3, 1000, 400000000, 4600000000, true}, {"known_zero_tail", 200 * time.Millisecond, 1, 0, 300000000, 4700000000, true}, {"zero_tail_without_fixed_sample", 0, 0, 0, 0, 0, false}, + {"ceiling_boundary_is_complete", 200 * time.Millisecond, 3, 600000, 60300000000, 0, true}, + {"saturated_tail_is_non_actionable", 200 * time.Millisecond, 3, 610000, 60000000000, 0, true}, {"partial_unknown_rate", 200 * time.Millisecond, 1, 1000, 300000000, 0, false}, } { t.Run(tc.name, func(t *testing.T) { @@ -65,3 +69,34 @@ func TestFrozenRefusalRetainsUnknownCompleteEstimate(t *testing.T) { t.Fatalf("partial estimate became known after reason changed: %+v", r) } } + +func TestFrozenDrainObservationPreservesKnownBeforeReasonMutation(t *testing.T) { + s, f, l, w := precopyLayer(t, 1, 3) + w.write(t, s, 1, 0x71) + seedFrozenSamples(l, 200*time.Millisecond) + before := f.stats() + result, err := l.PrecopyDetachWithAdmission(frozenContext(t, time.Second, false), func(context.Context) (func(), error) { return nil, context.Canceled }, func() bool { t.Fatal("drain refusal stopped I/O"); return true }) + var refusal *FrozenRefusal + if !errors.As(err, &refusal) || result.Precopy.Reason != "drain_refused" { + t.Fatalf("drain path not witnessed: %+v %v", result.Precopy, err) + } + r := refusal.Report + if !r.FrozenEstimateKnown || r.FrozenEstimate != r.Estimate || r.FreezeLimit != 5*time.Second || r.GuestFreezeElapsed < time.Second || r.RemainingFreeze <= 0 || r.RemainingFreeze+r.GuestFreezeElapsed != 5*time.Second { + t.Fatalf("drain reason destroyed known observation: %+v", r) + } + after := f.stats() + if after.puts != before.puts || after.cas != before.cas { + t.Fatal("drain refusal did remote work") + } +} +func TestFrozenSaturatedTailRemainsKnownButNonActionable(t *testing.T) { + l := &chunkLayerImpl{} + for i := 0; i < 3; i++ { + l.precopySamples = append(l.precopySamples, precopySample{at: time.Now(), fixed: 200 * time.Millisecond, rate: 20000}) + } + r := l.precopyEstimate(610000, 0) // safe rate 10000 B/s -> 61s tail, beyond the existing ceiling. + now := time.Now() + if r.admitFrozenAt(FrozenDetachOptions{StartedAt: now}, now) || r.Estimate != 60*time.Second || r.TailEstimate != 60*time.Second || !r.FrozenEstimateKnown || r.FrozenEstimate != 60*time.Second || r.FreezeLimit != 5*time.Second || r.MaxRefreezeQuiesce != 0 { + t.Fatalf("saturated sentinel became actionable or changed admission: %+v", r) + } +} diff --git a/seaweed-block/core/storage/chunk_precopy.go b/seaweed-block/core/storage/chunk_precopy.go index 0f8d545046..2a7a0e4655 100644 --- a/seaweed-block/core/storage/chunk_precopy.go +++ b/seaweed-block/core/storage/chunk_precopy.go @@ -219,6 +219,7 @@ func (l *chunkLayerImpl) precopyDetach(ctx context.Context, prepare func(context } l.precopyFreeze = func(tail uint64, barrierStart time.Time, current chunkCutStats) bool { report = l.precopyEstimate(tail, report.Attempts) + l.observeFrozen(&report, guestFreeze, externallyFrozen) report.Drain = drain report.DrainTimedOut = errors.Is(drainErr, context.DeadlineExceeded) if drainErr != nil { diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 504e74421b..3bb8d99e1d 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -248,7 +248,7 @@ stateDiagram-v2 | Quiesce | the capture barrier (`captureMu`) is held exclusively, then `Sync` fixes H; `Recover` and writes hold the barrier shared | `core/storage/chunk_layer.go` `captureLocked`; `core/storage/walstore.go` `WALStore.Recover`, `WALStore.Write` | `INV-CUT-QUIESCED-001`, `INV-CUT-RECOVER-BARRIER-001` | | Pre-copy detach | at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` | | Guest-frozen detach | `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001` | -| Checkpoint tail | one cost observation reports remaining bytes, tail cost, complete frozen estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | +| Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` | | Pre-copy host drain | a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` | | Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001` | | LSN guard | refuse when H is below HEAD's `RemoteLSN` (`lsn_behind`) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-MONOTONE-001` | @@ -526,7 +526,7 @@ Notes: | `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE | | `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE | | `INV-CUT-PLAIN-DETACH-001` | A plain detach closes the frontend only when no I/O holds its admission lock; no store or remote call occurs while this lock is held. An admitted or entering operation makes the request refuse unchanged. Cost admission alone is bypassed; ordinary detached publication and unknown/fenced/aborted settlement stay enforced. An absent or false field preserves pre-copy policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE | -| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports the complete estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | +| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRefusalCarriesServerBudget`, `TestChunkFrozenDrainRefusalCarriesObservedBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE | | `INV-WS-FREEZE-REFUSAL-001` | HTTP400 `invalid_freeze_budget`, retryable=false, is emitted only for frozen-request validation before any provider admission or mutation. Missing/zero/future origin, override without frozen, and frozen+plain preserve that boundary. Generic `bad_request` is not a clean-refusal proof. Terminal and unknown-publication causes retain precedence; no production path emits this typed code after mutation. | G frozen detach: request → refused before admission (M5) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode`, `TestFrozenValidationPrecedesAnyProviderAccess` | — (wire classification; validation/admission guards unchanged) | ACTIVE | | `INV-CUT-PRECOPY-001` | Resume grants waiters FIFO under one lock; gates and completion are independent. Each command keeps its arrival/caller bound. Only pause refusals requeue; stale and terminal errors survive. Detached handoff requires settled publication. See Notes for admission and freeze guards. | M5 tentative admission -> ordinary COW or FinalFreeze | `chunk_precopy.go`; `chunk_frozen_budget.go`; `precopy_admission.go`; `storage_adapter.go`; `provider_chunk.go` | `TestFrozenDetachRejectsBeforeStagingOrUpload`, `TestFrozenDetachRechecksBudgetAtBarrierWithoutUpload`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestCheckpointTailScanIncludedInTotalAndFixedCosts`, `TestCheckpointTailUsesLiteralLatestThreeConservativeRate`, `TestFrozenDetachForcedFinalCommitsSamePoint`, `TestFrozenFinalOverrideKeepsAuthorityAndCloseGuards`, `TestFrozenRetryDoesNotHideUnknownPublication`, `TestFrozenProviderFlagOffRefusesWithoutUploadThenFinalCommits`, `TestChunkFrozenDetachWireContractAndPrecedence`, `TestCheckpointTailMeasuresWritesAfterItsCut`, `TestChunkCutFixedSpansAttributeManifestAndCleanup`, `TestPrecopyLiveBarrierSpansExplainOverage`, `TestPrecopyFixedPartsDoNotDoubleCountSyncPhases`, `TestPrecopyProviderBusyOwnerKeepsServing`, `TestPrecopyProviderBusyOwnerRetryRetainsSlowFixedSample`, `TestPrecopyDetachBusyOwnerExhaustsWithoutStopping`, `TestPrecopyDetachBusyOwnerRetainsSlowFixedCost`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachRefusedFinalCutRetainsSlowFixedCost`, `TestPrecopyDetachRetryResolvesPreviouslyAppliedDetachedCut`, `TestPrecopyDetachAppliedRetryRetainsSlowFixedCost`, `TestPrecopyAttemptDiagnosticsSeparateTimeoutFromFit`, `TestPrecopyAttemptDiagnosticsRetainSlowFixedCost`, `TestPrecopyStopIOReturnTimestampPrecedesFinalPublication`, `TestPrecopyCountsWarmAttemptsSeparatelyFromMeasurementRounds`, `TestPrecopyUnknownPreviousCannotClaimProgress`, `TestPrecopyCallerExpiryVersusClose`, `TestPrecopySmokeTraceAmendment4`, `TestPrecopyFixedWindowDecays`, `TestPrecopyFinalAttemptFreezeCeiling`, `TestPrecopyFixedCostSmallTailCommitsBySecondAttempt`, `TestPrecopyLargeTailStillRefusesFixedCostException`, `TestPrecopyFixedCommitRuleKeepsProgressAndFreezeBounds`, `TestPrecopyFixedPartsStayWithLargestObservation`, `TestPrecopyFixedPartsMeasureCASAndReadbackSeparately`, `TestPrecopyFixedExceptionFinishUsesDeclaredFreeze` (`core/storage/chunk_precopy_fixed_commit_test.go`), `TestPrecopyFiftyIOPSSyncConvergesFirstAttempt` (first eligible allowance or plateau attempt), `TestPrecopyFiftyIOPSSlowMeasuredCostsKeepServing` (retained slow cost, declared admission or refusal, active owner and exact local bytes), `TestPrecopyFiftyIOPSColdCostsKeepAdmissionHonest`, `TestPrecopyFiftyIOPSRoundAccounting` (five total physical rounds, including success and measurement rounds), `TestPrecopyHostDrainDoesNotCompleteHeldGuestIO`, `TestPrecopyTargetCloseDropsHeldCommandWithoutCompletion`, `TestPrecopyDrainLetsAnAdmittedWriterReachTheBarrier`, `TestPrecopyDrainReceives100MillisecondBound`, `TestPrecopyDrainTimeoutReopensWithoutWaitingUnderCapture`, `TestPrecopyLateGateCallerCannotCrossFreeze`, `TestPrecopyResumeReleasesAllWaiters` (FIFO grants under one lock, concurrent outstanding I/O), `TestPrecopyResumedArrivalDoesNotInheritExpiredPause`, `TestPrecopyQueueBoundStartsAtCommandArrival`, `TestPrecopyResumeGrantVersusExpiry`, `TestPrecopyGrantedWaiterFollowsReplacementPause`, `TestPrecopyNewPauseCannotEraseObservedStalePrimary`, `TestPrecopyStopFallbackPreservesQueuedPause`, `TestPrecopyQueueUsesFiveSecondCutoverBudget`, `TestPrecopyRollingUploadReopensTentativeAdmission`, `TestPrecopyDetachRefusedFinalCutKeepsChangedBytes`, `TestPrecopyDetachSustainedWrapFlushAndFreshRestore` | `PrecopyFixedAdmission.tla` (ordinary admission), `FrozenDetachBudget.tla` (forecast/barrier budget, upload guard, explicit override and stable-authority publication); controlled callers and measured latency are not a model proof | ACTIVE | | `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | @@ -666,3 +666,5 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a | Wait | Machine / invariant | Bound | Release and cancellation | Locks / remote work | |---|---|---|---|---| | Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. | + +Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes. diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 8f430c6481..f103e9786d 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -513,3 +513,5 @@ distinct states, depth 6, queue empty, no invariant violation. Bounds: elapsed limit 50, no physical I/O latency. Raw quantities and JSON preservation are checked by native Go tests; this derived arithmetic model does not model the HTTP encoder, sampler atomicity, orchestrator timing or an unbounded estimator overrun. + +#344 review qualification: `TestChunkFrozenDrainRefusalCarriesObservedBudget` drives a real admitted Sync through frontend drain expiry, durable provider and HTTP, with no report injection; `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation` covers the known observation. `TestFrozenSaturatedTailRemainsKnownButNonActionable` and the literal 60 s/61 s candidate cases preserve the existing saturation sentinel (zero slack, not a complete duration). These native controls add no model claim or admission guard. From c329c579857a6fd8ab41699680ab9209025a5520 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 03:14:07 -0800 Subject: [PATCH 24/25] blockvolume: the periodic HEAD capture is off by default (opt-in, at least 5m when set) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/cmd/blockvolume/chunk_remote.go | 2 +- seaweed-block/cmd/blockvolume/chunk_remote_test.go | 8 ++++++-- seaweed-block/cmd/blockvolume/main.go | 2 +- seaweed-block/docs/design/agent-workspace-design.md | 8 ++++---- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/chunk_remote.go b/seaweed-block/cmd/blockvolume/chunk_remote.go index 7bc5d5eb20..9d54ae5b66 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote.go @@ -23,7 +23,7 @@ const ( defaultChunkPath = "/swblock/chunks" // Periodic HEAD publication bounds the host-loss recovery point. Automatic // named snapshots remain explicit catalog operations. - defaultChunkCaptureInterval = 15 * time.Minute + defaultChunkCaptureInterval = 0 defaultChunkMaintenanceInterval = time.Hour defaultChunkCutTimeout = 5 * time.Minute defaultChunkMaintenanceTimeout = time.Minute diff --git a/seaweed-block/cmd/blockvolume/chunk_remote_test.go b/seaweed-block/cmd/blockvolume/chunk_remote_test.go index c885307e7c..d05d04ca01 100644 --- a/seaweed-block/cmd/blockvolume/chunk_remote_test.go +++ b/seaweed-block/cmd/blockvolume/chunk_remote_test.go @@ -31,8 +31,12 @@ func TestWALStoreChunkFlags(t *testing.T) { if err != nil { t.Fatal(err) } - 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) + if d.chunk.captureInterval != 0 || d.chunk.maintenanceInterval != time.Hour || d.chunk.automaticGC || d.chunk.dirtyThreshold != 512 { + t.Fatalf("scheduler defaults interval %s threshold %d, want capture off (0), maintenance 1h, GC off and 512", d.chunk.captureInterval, d.chunk.dirtyThreshold) + } + on, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=15m")) + if err != nil || on.chunk.captureInterval != 15*time.Minute { + t.Fatalf("opting in to a 15m periodic cut: %+v %v", on.chunk, err) } 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")) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 394ef1d974..fa345d35c0 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -203,7 +203,7 @@ func parseFlags(args []string) (flags, error) { fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)") fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)") fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: converge rolling cuts before final detach; refuse cutover if measured tail does not fit") - fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 15m, minimum 5m); 0 disables") + fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)") fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables") fs.BoolVar(&f.chunk.automaticGC, "chunk-maintenance-gc", false, "walstore-chunk: enable scoped automatic GC; off pending restart-safe unknown-CAS settlement and density qualification") fs.IntVar(&f.chunk.uploadConcurrency, "chunk-upload-concurrency", 8, "walstore-chunk: maximum concurrent dirty-chunk uploads (1..64)") diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 480573c503..1a7621b078 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, 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. +- **When cuts happen.** At semantic points chosen by the integrator, on explicit request, and by the periodic timer (off by default; when set, at least 5m in the OSS CLI). 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. With the periodic timer off (the default), HEAD advances at explicit cuts, snapshots and detach; 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 @@ -253,8 +253,8 @@ Snapshots of the target are refused in `Claimed` and `Restoring`. ### 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. +Periodic HEAD capture is off by default (opt-in; when set, at least 5 +minutes), and retention runs 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 From 262900416709162cf2054718d75c4cec72aa1f96 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Sat, 21 Nov 2026 04:06:11 -0800 Subject: [PATCH 25/25] train 8: regenerate the status schema page after #338's comment change docs/status-schema.md is generated from the Go field comments (#341); #338 rewrote the StageRounds comment group, so the composed train needs the page regenerated (STATUS_SCHEMA_UPDATE=1). Docs only. Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/status-schema.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/seaweed-block/docs/status-schema.md b/seaweed-block/docs/status-schema.md index f78adb287e..02d7a1d468 100644 --- a/seaweed-block/docs/status-schema.md +++ b/seaweed-block/docs/status-schema.md @@ -266,11 +266,11 @@ Durable store state of the served volume. Go type `volume.durableStatusBody`. | `Volumes[].Chunk.Stats.LastCut.MapPersistNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | | `Volumes[].Chunk.Stats.LastCut.CASResult` | string | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | | `Volumes[].Chunk.Stats.LastCut.TotalNs` | int64 | (group of `BarrierPauseNs`) BarrierPauseNs is the guest pause: from the capture barrier's Lock request until it is released. LockWaitNs is its first part, the wait for writers already holding the capture barrier shared. | -| `Volumes[].Chunk.Stats.LastCut.StageRounds` | int | Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | -| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | -| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | -| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | -| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (BarrierBound > 0): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier; BarrierOverBound: more than the bound (the staging rounds did not converge). | +| `Volumes[].Chunk.Stats.LastCut.StageRounds` | int | Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.StagedChunks` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.StagedChunksUsed` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.BarrierCopyChunks` | int | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | +| `Volumes[].Chunk.Stats.LastCut.BarrierOverBound` | bool | (group of `StageRounds`) Pre-copy (staging by the copy-on-write side budget, M5 Stage): StageRounds staging rounds staged StagedChunks chunks outside the barrier; StagedChunksUsed of the uploads in HEAD came from staging. BarrierCopyChunks were copied under the barrier. BarrierOverBound: more than the legacy fixture BarrierBound; always false in production, where that bound is zero. | | `Volumes[].Chunk.Stats.LastCutH` | uint64 | the LSN the last successful cut published | | `Volumes[].Chunk.Stats.LastCutNs` | int64 | when it completed (wall clock, Unix ns) | | `Volumes[].Chunk.Stats.BarrierOverBound` | uint64 | BarrierOverBound counts cuts whose barrier copied more than the bound after the staging rounds. |