From fcb170c8d8d614ba75a09ca4842637968038032c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:00:46 -0800 Subject: [PATCH 01/33] test(chunkstore): measure unchanged manifest group scaling --- .../chunkstore/manifest_scaling_test.go | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go diff --git a/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go b/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go new file mode 100644 index 0000000000..dd093d6c84 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/manifest_scaling_test.go @@ -0,0 +1,36 @@ +package chunkstore + +import ( + "context" + "fmt" + "testing" + + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// Metadata-only scaling probe: one chunk per 1-GiB segment, all unchanged. +// No volume data allocation or remote I/O is included. Report ns/op and allocs; +// the old per-group scan visits groups*groups base references. +func BenchmarkPrepareManifestUnchangedGroups(b *testing.B) { + for _, n := range []int{256, 1024, 4096} { + b.Run(fmt.Sprint(n), func(b *testing.B) { + r, err := NewChunkRemote(newFakeFiler(), newFakeBlobs(), "/chunks/v1") + if err != nil { + b.Fatal(err) + } + base := storage.ChunkHead{Chunks: map[uint64]storage.ChunkRef{}, Segments: map[uint64]storage.ChunkSegment{}, ChunkBytes: 1 << 30, ManifestChunkCount: n} + for i := 0; i < n; i++ { + base.Chunks[uint64(i)] = storage.ChunkRef{Key: fmt.Sprintf("@v1/chunk/%d", i)} + base.Segments[uint64(i)] = storage.ChunkSegment{Key: fmt.Sprintf("@v1/seg/%d", i), Owner: "v1", Count: 1} + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + next, ids, err := r.PrepareManifest(context.Background(), base, base, 1<<30) + if err != nil || len(ids) != 0 || len(next.Segments) != n { + b.Fatalf("unchanged segment reuse: %v, intents=%v", err, ids) + } + } + }) + } +} From 75725d6b327fd58f5e03f8e3a077f0270f25a278 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:04:21 -0800 Subject: [PATCH 02/33] test: require volume capacity refusal at create boundaries --- .../chunkstore/volume_size_limit_test.go | 28 ++++++++++++++++++ .../core/lifecycle/volume_size_limit_test.go | 27 +++++++++++++++++ .../core/storage/volume_size_limit_test.go | 29 +++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go create mode 100644 seaweed-block/core/lifecycle/volume_size_limit_test.go create mode 100644 seaweed-block/core/storage/volume_size_limit_test.go diff --git a/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go new file mode 100644 index 0000000000..debc3434e1 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/volume_size_limit_test.go @@ -0,0 +1,28 @@ +package chunkstore + +import ( + "context" + "strings" + "testing" +) + +func TestEnsureVolumeRejectsBeyondUint32LBACap(t *testing.T) { + f, b, _, _, _ := gcFixture(t) + c, err := NewCatalog(manifestFilerBlobs{f, b}, catBase) + if err != nil { + t.Fatal(err) + } + ctx := context.Background() + if _, err = c.EnsureVolume(ctx, "at-cap", Geometry{NumBlocks: 4294967295, BlockSize: 4096, ChunkBlocks: 1024}); err != nil { + t.Fatal(err) + } + for _, blocks := range []uint64{4294967296, ^uint64(0)} { + _, err = c.EnsureVolume(ctx, "too-large", Geometry{NumBlocks: blocks, BlockSize: 4096, ChunkBlocks: 1024}) + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("blocks %d: want capacity refusal, got %v", blocks, err) + } + if _, ok, e := c.ReadVolume(ctx, "too-large"); e != nil || ok { + t.Fatalf("refusal changed catalog: exists=%v err=%v", ok, e) + } + } +} diff --git a/seaweed-block/core/lifecycle/volume_size_limit_test.go b/seaweed-block/core/lifecycle/volume_size_limit_test.go new file mode 100644 index 0000000000..7aa7627f55 --- /dev/null +++ b/seaweed-block/core/lifecycle/volume_size_limit_test.go @@ -0,0 +1,27 @@ +package lifecycle + +import ( + "errors" + "strings" + "testing" +) + +func TestCreateVolumeRejectsBeyondUint32LBACap(t *testing.T) { + s, err := OpenFileStore(t.TempDir()) + if err != nil { + t.Fatal(err) + } + const capBytes = uint64(17592186040320) // 16 TiB - 4 KiB + if _, err = s.CreateVolume(VolumeSpec{VolumeID: "at-cap", SizeBytes: capBytes, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + for _, size := range []uint64{capBytes + 1, capBytes + 4096, ^uint64(0)} { + _, err = s.CreateVolume(VolumeSpec{VolumeID: "too-large", SizeBytes: size, ReplicationFactor: 1}) + if !errors.Is(err, ErrInvalidVolumeSpec) || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("size %d: want clear capacity refusal, got %v", size, err) + } + if _, ok := s.GetVolumeSnapshot("too-large"); ok { + t.Fatal("refusal persisted oversized volume") + } + } +} diff --git a/seaweed-block/core/storage/volume_size_limit_test.go b/seaweed-block/core/storage/volume_size_limit_test.go new file mode 100644 index 0000000000..489ff8a02f --- /dev/null +++ b/seaweed-block/core/storage/volume_size_limit_test.go @@ -0,0 +1,29 @@ +package storage + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCreateWALStoreRefusesOversizeBeforeFilesystem(t *testing.T) { + // An invalid parent prevents even the old implementation from creating a + // huge sparse image; the capacity error must precede all filesystem work. + parent := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(parent, []byte("untouched"), 0600); err != nil { + t.Fatal(err) + } + s, err := CreateWALStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) + if s != nil { + s.Close() + t.Fatal("oversized store created") + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("want capacity refusal before I/O, got %v", err) + } + got, e := os.ReadFile(parent) + if e != nil || string(got) != "untouched" { + t.Fatal("parent changed") + } +} From 1f36db305f173bc9cca00f096f07b7bdb8ea5564 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:06:23 -0800 Subject: [PATCH 03/33] fix(chunkstore): partition base manifest chunks once per preparation --- .../core/frontend/chunkstore/manifest.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/manifest.go b/seaweed-block/core/frontend/chunkstore/manifest.go index 01781b4b06..9a4708655d 100644 --- a/seaweed-block/core/frontend/chunkstore/manifest.go +++ b/seaweed-block/core/frontend/chunkstore/manifest.go @@ -90,14 +90,19 @@ func (r *ChunkRemote) PrepareManifest(ctx context.Context, base, next storage.Ch data []byte } var uploads []upload - for group, chunks := range groups { - old := map[uint64]storage.ChunkRef{} - for idx, ref := range base.Chunks { - if idx/per == group { - ref.Key = qualifyManifestKey(owner, ref.Key) - old[idx] = ref - } + // Partition the base once, rather than scanning every base chunk for each + // segment group. Keep the same qualified-key comparison for segment reuse. + baseGroups := map[uint64]map[uint64]storage.ChunkRef{} + for idx, ref := range base.Chunks { + group := idx / per + if baseGroups[group] == nil { + baseGroups[group] = map[uint64]storage.ChunkRef{} } + ref.Key = qualifyManifestKey(owner, ref.Key) + baseGroups[group][idx] = ref + } + for group, chunks := range groups { + old := baseGroups[group] if previous, ok := base.Segments[group]; ok && base.ChunkBytes == chunkBytes && reflect.DeepEqual(chunks, old) { next.Segments[group] = previous continue From 766596ffd76249487c513c4e17223e844ce1444a Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:07:15 -0800 Subject: [PATCH 04/33] docs: record manifest base partition cost invariant --- seaweed-block/docs/design/invariants.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..d2e60e38ba 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -469,6 +469,12 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | +### Manifest preparation scan cost + +| ID | Invariant | Transition | Enforced in | Regression/qualification | Model | Status | +|---|---|---|---|---|---|---| +| `INV-CUT-MANIFEST-SCAN-001` | PrepareManifest partitions base references once; each segment compares only its own base group. Unchanged segment identities remain reusable. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `BenchmarkPrepareManifestUnchangedGroups`; `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` | Algorithmic cost; no state/transition change to `CutPipeline` | ACTIVE | + ## Part C. Change rules How a fix or a feature is calibrated against this model: From 8f377a2f1744db65c6a7de93e16e0e19a58681b1 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:07:46 -0800 Subject: [PATCH 05/33] test(csi): refuse oversized capacity before provisioning --- .../core/csi/volume_size_limit_test.go | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 seaweed-block/core/csi/volume_size_limit_test.go diff --git a/seaweed-block/core/csi/volume_size_limit_test.go b/seaweed-block/core/csi/volume_size_limit_test.go new file mode 100644 index 0000000000..49570c143c --- /dev/null +++ b/seaweed-block/core/csi/volume_size_limit_test.go @@ -0,0 +1,29 @@ +package csi + +import ( + "context" + csipb "github.com/container-storage-interface/spec/lib/go/csi" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "strings" + "testing" +) + +func TestCSICreateVolumeCapacityCapBeforeProvision(t *testing.T) { + const capBytes = int64(17592186040320) + p := &stubProvisioner{} + s := NewControllerServerWithProvisioner(&stubLookup{}, p) + req := &csipb.CreateVolumeRequest{Name: "v", CapacityRange: &csipb.CapacityRange{RequiredBytes: capBytes}, VolumeCapabilities: []*csipb.VolumeCapability{testVolumeCapability()}} + if _, err := s.CreateVolume(context.Background(), req); err != nil { + t.Fatal(err) + } + p.calls = nil + req.CapacityRange.RequiredBytes = capBytes + 4096 + _, err := s.CreateVolume(context.Background(), req) + if status.Code(err) != codes.InvalidArgument || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("want clear InvalidArgument, got %v", err) + } + if len(p.calls) != 0 { + t.Fatal("oversized request reached provisioner") + } +} From f67517f2e47f7ec9ac7a8d08cd4853e7f57b57f0 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:09:12 -0800 Subject: [PATCH 06/33] fix: refuse volume creation above the uint32 LBA capacity limit --- seaweed-block/core/csi/controller.go | 4 +++ .../core/frontend/chunkstore/catalog.go | 26 ++++++++------- seaweed-block/core/geometry/volume_size.go | 16 ++++++++++ seaweed-block/core/lifecycle/store.go | 4 +++ seaweed-block/core/storage/walstore.go | 32 +++++++++++-------- 5 files changed, 57 insertions(+), 25 deletions(-) create mode 100644 seaweed-block/core/geometry/volume_size.go diff --git a/seaweed-block/core/csi/controller.go b/seaweed-block/core/csi/controller.go index c4471f4bd9..c3032079c9 100644 --- a/seaweed-block/core/csi/controller.go +++ b/seaweed-block/core/csi/controller.go @@ -3,6 +3,7 @@ package csi import ( "context" "errors" + "github.com/seaweedfs/seaweed-block/core/geometry" "log" "strconv" "time" @@ -248,6 +249,9 @@ func volumeSpecFromCreateRequest(req *csipb.CreateVolumeRequest) (VolumeSpec, er if size <= 0 { return VolumeSpec{}, status.Error(codes.InvalidArgument, "capacity is required") } + if err := geometry.ValidateVolumeSize(uint64(size)); err != nil { + return VolumeSpec{}, status.Error(codes.InvalidArgument, err.Error()) + } if len(req.GetVolumeCapabilities()) == 0 { return VolumeSpec{}, status.Error(codes.InvalidArgument, "volume capabilities are required") } diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 1e1889e3d0..f6a634a16c 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1,7 +1,7 @@ package chunkstore // Catalog: the chunk control plane's filer metadata and Fork (B9 W2 spec -// §3-§5). Under the chunk base directory, per volume: +// §3-§5). Under the chunk base directory, per volume: // // //HEAD the published HEAD (ChunkRemote) // //keys/ chunk key bindings (ChunkRemote) @@ -15,7 +15,7 @@ package chunkstore // // Snapshot and fork are read-then-write. Each writes an intent naming the // keys it references before its final manifest write, and refuses that -// write once OpDeadline has passed since it read its source (spec §2.3). +// write once OpDeadline has passed since it read its source (spec §2.3). // The operation's intents are removed only once its outcome is settled: the // manifest is confirmed published (re-read shows it), or the attempt // cleanly aborted (it never sent the write, or another entry already holds @@ -30,6 +30,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "path" "strconv" "strings" @@ -74,7 +75,7 @@ const ( OriginFork = "fork" // DefaultOpDeadline bounds a snapshot or fork from reading its source to - // its final write (spec §2.3). + // its final write (spec §2.3). DefaultOpDeadline = 5 * time.Minute defaultListLimit = 100 @@ -85,7 +86,7 @@ const ( maxSnapName = 128 ) -// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI +// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI // report them. const ( CodeNotChunkVolume = "not_chunk_volume" @@ -160,7 +161,7 @@ type Parent struct { Gen uint64 `json:"gen"` } -// VolumeInfo is the VOLUME entry (spec §4.2). +// VolumeInfo is the VOLUME entry (spec §4.2). type VolumeInfo struct { Format int `json:"format"` VolumeID string `json:"volume_id"` @@ -207,7 +208,7 @@ type snapDoc struct { } // SnapshotInfo describes one snapshot, with the field names of the HTTP API -// (spec §3.2-§3.3). +// (spec §3.2-§3.3). type SnapshotInfo struct { VolumeID string `json:"volumeID"` Name string `json:"name"` @@ -268,7 +269,7 @@ type ForkRequest struct { } // ForkResult reports a fork, with the field names of the CLI output -// (spec §3.5). +// (spec §3.5). type ForkResult struct { Target string `json:"target"` Source string `json:"source"` @@ -325,7 +326,7 @@ func (c *Catalog) volRoot(vol string) (string, error) { return path.Join(c.base, vol), nil } -// CheckSnapshotName enforces the snapshot name rule (spec §4.4). +// CheckSnapshotName enforces the snapshot name rule (spec §4.4). func CheckSnapshotName(name string) error { if name == "" || len(name) > maxSnapName || strings.HasPrefix(name, ".") { return catErr(CodeInvalidName, false, nil, "snapshot name %q: 1-%d characters, not starting with '.'", name, maxSnapName) @@ -473,7 +474,7 @@ func (c *Catalog) ReadHead(ctx context.Context, vol string) (storage.ChunkHead, return h, true, nil } -// EnsureVolume applies the attach rules of spec §4.2 for a volume served +// EnsureVolume applies the attach rules of spec §4.2 for a volume served // with geometry g: it creates a missing VOLUME entry (origin create), and // refuses with geometry_mismatch when VOLUME disagrees with g, or with // fork_incomplete when VOLUME is a fork whose HEAD is not written yet. @@ -487,6 +488,9 @@ func (c *Catalog) EnsureVolume(ctx context.Context, vol string, g Geometry) (Vol return VolumeInfo{}, err } if !ok { + if g.BlockSize != 0 && g.NumBlocks > geometry.MaxVolumeBytes/uint64(g.BlockSize) { + return VolumeInfo{}, catErr(CodeGeometryMismatch, false, nil, "volume size exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", geometry.MaxVolumeBytes) + } v = VolumeInfo{Format: volumeFormat, VolumeID: vol, Geometry: g, Origin: OriginCreate, CreatedNs: c.now().UnixNano()} e, err := volumeEntry(v, "") if err != nil { @@ -965,7 +969,7 @@ func (c *Catalog) claimName(ctx context.Context, vol, root string, req SnapshotR } // SnapshotReplay resolves a snapshot request against the catalog before -// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's +// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's // request and its attempt published, it returns that snapshot (Replayed, // true); held by another request, snapshot_exists; free, or held by req's // unpublished attempt, (zero, false, nil). It validates the whole request @@ -1049,7 +1053,7 @@ func (c *Catalog) ListSnapshots(ctx context.Context, vol string, opts ListOption } } -// DeleteSnapshot frees the name (spec §3.4, W5): +// DeleteSnapshot frees the name (spec §3.4, W5): // it marks the attempt deleting (or, when the attempt never published, // claims its path with an aborted tombstone so a late insert cannot land), // then removes the name record. The attempt path is never removed. It diff --git a/seaweed-block/core/geometry/volume_size.go b/seaweed-block/core/geometry/volume_size.go new file mode 100644 index 0000000000..0d317ede02 --- /dev/null +++ b/seaweed-block/core/geometry/volume_size.go @@ -0,0 +1,16 @@ +// Package geometry defines shared volume capacity limits at creation boundaries. +package geometry + +import "fmt" + +// MaxVolumeBytes is the uint32-LBA limit with the supported 4-KiB IO unit. +const MaxVolumeBytes uint64 = (16 << 40) - 4096 + +// ValidateVolumeSize rejects an unsupported capacity before any allocation or +// durable create. Division also makes block geometry checks overflow-safe. +func ValidateVolumeSize(size uint64) error { + if size > MaxVolumeBytes { + return fmt.Errorf("volume size %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", size, MaxVolumeBytes) + } + return nil +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 68b7243cb4..e1c5ab62e9 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "os" "path/filepath" "regexp" @@ -106,6 +107,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { if err := validateSpec(spec); err != nil { return VolumeRecord{}, err } + if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil { + return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err) + } s.mu.Lock() defer s.mu.Unlock() if existing, ok := s.records[spec.VolumeID]; ok { diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index c148ce5f1f..9c1c737229 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -3,6 +3,7 @@ package storage import ( "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "os" "path/filepath" "sync" @@ -63,7 +64,7 @@ type WALStore struct { syncDirectFrontierMetadata func([]byte) error writeSuperblockMetadata func([]byte) error syncSuperblockMetadata func() error - flusher *flusher // background WAL→extent applier; nil if disabled + flusher *flusher // background WAL→extent applier; nil if disabled admission *walAdmission // backpressure on WAL pressure; nil if disabled // admissionTimeout is the per-Write deadline for admission. If @@ -118,7 +119,7 @@ type WALStore struct { // as fromLSN > checkpointLSN - recoveryRetentionLSNs. Zero means // strict checkpoint-driven recycle. Operator sets via // blockvolume's --wal-retention-lsns flag at store construction. - // Stored in-memory only — NOT persisted to the superblock; on + // Stored in-memory only — NOT persisted to the superblock; on // restart the daemon re-applies the flag. // // Pinned by: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. @@ -131,7 +132,7 @@ type WALStore struct { // --recovery-mode=dual-lane. // // nil = no gate (legacy behavior). Per docs/recovery-wiring-plan.md - // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. + // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. recycleFloorSrc RecycleFloorSource syncs atomic.Uint64 // completed logical Sync calls (test/diagnostic) @@ -191,6 +192,9 @@ func CreateWALStoreWithOptions(path string, numBlocks uint32, blockSize int, opt if blockSize < 0 || uint64(blockSize) > uint64(^uint32(0)) { return nil, errSuperblockBadVolume } + if err := geometry.ValidateVolumeSize(uint64(numBlocks) * uint64(blockSize)); err != nil { + return nil, err + } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return nil, err } @@ -370,7 +374,7 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B } s.syncSuperblockMetadata = f.Sync - // Background flusher: drains dirty map → extent, advances + // Background flusher: drains dirty map → extent, advances // checkpoint, allows WAL recycling. Defaults are conservative // for the demo workload; tunable via config in future. s.flusher = newFlusher(s, flusherConfig{}) @@ -383,7 +387,7 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B // returning ErrWALFull to callers under transient load. // Watermarks 0.7/0.9 match V2 config.go defaults // (WALSoftWatermark, WALHardWatermark). Admission wakes the - // flusher via NotifyUrgent — same seam V2 wires for pressure- + // flusher via NotifyUrgent — same seam V2 wires for pressure- // driven flushes. s.admissionTimeout = 30 * time.Second s.admission = newWALAdmission(walAdmissionConfig{ @@ -762,7 +766,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { // WAL admission: throttle/block under WAL pressure. If admission // is disabled (admission==nil), Write proceeds immediately. The - // admission Acquire may block up to admissionTimeout — under + // admission Acquire may block up to admissionTimeout — under // hard pressure it spins waiting for the flusher to drain. s.beforeChunkMutation(uint64(lba), 1) s.lifecycleMu.RLock() @@ -1231,7 +1235,7 @@ func (s *WALStore) Sync() (uint64, error) { return frontier, nil } -// Boundaries returns the current R/S/H boundaries — what is durable, +// Boundaries returns the current R/S/H boundaries — what is durable, // what the WAL still retains, what's the newest write. func (s *WALStore) Boundaries() (R, S, H uint64) { s.mu.RLock() @@ -1269,7 +1273,7 @@ func (s *WALStore) BlockSize() int { return int(s.sb.BlockSize) } // persistCheckpoint to clamp checkpoint advancement against active // recover-session pin floors. Pass nil to disable. // -// Idempotent. Safe to call at any time — the gate is read under +// Idempotent. Safe to call at any time — the gate is read under // s.mu so concurrent persistCheckpoint sees a consistent value. // // Implements storage.RecycleFloorGate. @@ -1336,8 +1340,8 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) { } // WriteExtentDirect installs a base block directly into the extent -// without going through the WAL append path — INV-RECV-BITMAP-CORE -// (§6.10). The receiver's per-session bitmap is the sole arbiter of +// without going through the WAL append path — INV-RECV-BITMAP-CORE +// (§6.10). The receiver's per-session bitmap is the sole arbiter of // BASE-vs-WAL conflict at this LBA; substrate-level WAL replay / // stale-skip is intentionally bypassed. // @@ -1478,16 +1482,16 @@ func (s *WALStore) RecoveryMode() RecoveryMode { // AppliedLSNs returns a partial view of per-LBA applied LSN: only // LBAs whose latest write is still in the WAL (not yet flushed to // extent) are reported. Once an entry is flushed and the dirty-map -// entry is cleared, walstore loses per-LBA LSN tracking — the +// entry is cleared, walstore loses per-LBA LSN tracking — the // extent stores data only, not per-LBA LSN. // // PARTIAL-VIEW LIMITATION: for full per-LBA applied-LSN tracking, // walstore would need a permanent per-LBA LSN map (substrate // refactor). The replica recovery apply gate is the authoritative -// correctness boundary; this partial seed is defense-in-depth — +// correctness boundary; this partial seed is defense-in-depth — // it correctly stale-skips recovery entries for LBAs still in the // WAL window, and falls back to "appliedLSN[LBA] = 0" semantics -// for flushed LBAs (which means recovery WILL apply them — +// for flushed LBAs (which means recovery WILL apply them — // acceptable when the gate's session-only tracking + live-lane // updates fill in the gap during the session). // @@ -1512,7 +1516,7 @@ func (s *WALStore) AppliedLSNs() (map[uint32]uint64, error) { // content is non-zero. // // This honors the LogicalStorage contract: "snapshots every -// written LBA's current bytes" — including LBAs whose data has +// written LBA's current bytes" — including LBAs whose data has // been flushed out of the dirty map into the extent. Filtering // zeros preserves the "snapshot of dirty bits" semantics callers // expect (a never-written LBA shouldn't appear in the output; From f00dcdbb08ffb66437c06eb62a52b98386d54170 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:10:38 -0800 Subject: [PATCH 07/33] docs: record volume create capacity invariant --- seaweed-block/docs/design/invariants.md | 988 ++++++++++++------------ 1 file changed, 497 insertions(+), 491 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..bcd8e43870 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1,494 +1,500 @@ -# Seaweed Block invariants and state machines +# Seaweed Block invariants and state machines + +This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. + +This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. + +The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). + +**Conventions.** These are the same as in the design documents. + +- Code references name a file and a function, not a line number. Test references name the test function and its file. +- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). +- Status: + - `ACTIVE`: a Go test in this repository asserts the statement. + - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. + - `ARCHIVED`: a retired row, kept with its reason. There are none yet. +- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. + +## Contents + +- [Part A. State machines](#part-a-state-machines) + - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) + - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) + - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) + - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) + - [M5 The cut pipeline](#m5-the-cut-pipeline) + - [M6 Chunk lifecycle](#m6-chunk-lifecycle) +- [Part B. Invariant ledger](#part-b-invariant-ledger) +- [Part C. Change rules](#part-c-change-rules) + +--- + +## Part A. State machines + +Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. + +### M1 walstore: open, recover, serve, fault + +The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). + +```mermaid +stateDiagram-v2 + [*] --> Opened: OpenWALStore / CreateWALStore + Opened --> Recovering: RecoverVolume + Recovering --> Serving: Recover ok, backend operational + Recovering --> RecoveryFailed: Recover error (typed reason) + Serving --> FaultLatched: fsync or WAL append fails + FaultLatched --> Closed: Close + RecoveryFailed --> Closed: Close + Serving --> Closed: Close + Closed --> Opened: reopen +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | +| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | +| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | +| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | +| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | + +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. + +Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). + +Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. + +### M2 Authority: assignment, epoch, lease + +blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves). + +**Assignment line, per volume.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | +| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | +| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | + +**Workspace lease and move, in blockmaster.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | +| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | +| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | + +### M3 Replica role and peer state + +The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). + +```mermaid +stateDiagram-v2 + [*] --> Unassigned: listener with a floor record, no role yet + Unassigned --> Primary: fact names self, listener fenced at e + Unassigned --> Supporting: fact names another primary, self in peers + Supporting --> Primary: promotion, fact names self at a higher epoch + Primary --> Supporting: fact names another primary, self in peers + Primary --> Excluded: fact names another primary, self not in peers + Supporting --> Excluded: fact names another primary, self not in peers + Excluded --> Supporting: later fact lists self as a peer +``` + +**Host role and listener admission.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | +| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | +| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | +| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | +| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | +| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | +| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | +| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | + +**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | +| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | +| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | + +`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). + +### M4 Workspace HEAD holder and takeover + +One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. + +```mermaid +stateDiagram-v2 + state "Lease guard (host)" as G { + [*] --> NoLease + NoLease --> Valid: renewal reply for this volume, replica and epoch + Valid --> Valid: renewal before the local deadline + Valid --> Fenced: deadline passed, invalid reply, or revoking + Fenced --> Drained: frontend and cuts stopped + Drained --> Acked: revocation acknowledged with the HEAD gen + } + state "HEAD holder" as H { + [*] --> Attaching + Attaching --> Claiming: fresh local root + Attaching --> Holder: existing root, HEAD is this holder's + Attaching --> Refused: existing root, HEAD published by another holder + Claiming --> Holder: CAS to this epoch and holder, state active + Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch + Holder --> Detached: Detach final cut, state detached + Holder --> HolderFenced: a superseding HEAD is seen + } +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | +| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | +| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | +| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | +| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | +| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | +| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | +| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | + +### M5 The cut pipeline + +A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. + +```mermaid +stateDiagram-v2 + [*] --> Admit + Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid + Admit --> Stage: earlier unknown CAS settled + Stage --> Quiesce: at most 3 pre-copy rounds + Quiesce --> OpenWindow: Sync H and D fixed under barrier + OpenWindow --> Copy: release barrier + Copy --> Closed: all candidates done + Copy --> Aborted: error, cancellation, observed fence, recovery or close + Aborted --> Refused: drain owners, cleanup, merge candidates + Copy --> Refused: H below HEAD RemoteLSN + Closed --> Upload: drain and cleanup; intent durable first + Upload --> Manifest + Manifest --> Readmit + Readmit --> Fenced: superseding HEAD + Readmit --> CAS + CAS --> Settled: CAS ok, or a re-read shows the proposal + CAS --> Pending: outcome unknown and HEAD unchanged + CAS --> Fenced: HEAD moved to a superseding holder + CAS --> Refused: HEAD moved otherwise (conflict) + Pending --> Admit: next cut settles it first +``` + +| Step | Guard | Enforced in | Protects | +|---|---|---|---| +| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | +| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | +| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | +| 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` | +| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; 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` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | +| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | +| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | +| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | +| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | +| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | + +### M6 Chunk lifecycle + +HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). + +**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | +| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | +| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | +| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | +| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | +| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | +| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | + +**Snapshots and forks.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | 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` | + +**Intents and key bindings.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | +| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | +| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | +| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | +| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | + +--- + +## Part B. Invariant ledger + +80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. + +### B.1 Core: storage, durability and the frontend gate + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | +| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | +| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | +| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | +| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | +| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | +| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | +| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | +| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | +| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | +| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | + +Notes: + +- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. +- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. + +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. + +- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively. + +- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. +- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. +- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. +- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. +- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). + +### B.2 Core: authority and epochs + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | + +Notes: + +- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. +- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). +- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. + +### B.3 Core: replication and replica roles + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | +| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | +| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | +| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | +| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | +| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | + +Notes: + +- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. +- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). + +### B.4 Workspace: HEAD holder, lease and takeover + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `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-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`) | `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-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | + +Notes: + +- `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. + +### B.5 Workspace: the cut pipeline + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `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-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | +| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | + +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). + +### B.6 Workspace: chunk lifecycle, GC and delete + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | +| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | +| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | +| `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 | + +Notes: + +- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. + +### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | +| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | +| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | +| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | +| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | +| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | +| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | + +Notes: + +- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). +- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. +- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. +- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. +- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. +- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. +- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. +- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. +- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. +- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. + +**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. + +--- + + +### B.8 NVMe/TCP receive bounds + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | + +### Volume create capacity -This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. - -This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. - -The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). - -**Conventions.** These are the same as in the design documents. - -- Code references name a file and a function, not a line number. Test references name the test function and its file. -- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). -- Status: - - `ACTIVE`: a Go test in this repository asserts the statement. - - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. - - `ARCHIVED`: a retired row, kept with its reason. There are none yet. -- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. - -## Contents - -- [Part A. State machines](#part-a-state-machines) - - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) - - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) - - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) - - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) - - [M5 The cut pipeline](#m5-the-cut-pipeline) - - [M6 Chunk lifecycle](#m6-chunk-lifecycle) -- [Part B. Invariant ledger](#part-b-invariant-ledger) -- [Part C. Change rules](#part-c-change-rules) - ---- - -## Part A. State machines - -Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. - -### M1 walstore: open, recover, serve, fault - -The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). - -```mermaid -stateDiagram-v2 - [*] --> Opened: OpenWALStore / CreateWALStore - Opened --> Recovering: RecoverVolume - Recovering --> Serving: Recover ok, backend operational - Recovering --> RecoveryFailed: Recover error (typed reason) - Serving --> FaultLatched: fsync or WAL append fails - FaultLatched --> Closed: Close - RecoveryFailed --> Closed: Close - Serving --> Closed: Close - Closed --> Opened: reopen -``` - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | -| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | -| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | -| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | -| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | -| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | - -Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. - -Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). - -Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. - -### M2 Authority: assignment, epoch, lease - -blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves). - -**Assignment line, per volume.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | -| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | -| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | - -**Workspace lease and move, in blockmaster.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | -| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | -| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | -| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | -| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | - -### M3 Replica role and peer state - -The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). - -```mermaid -stateDiagram-v2 - [*] --> Unassigned: listener with a floor record, no role yet - Unassigned --> Primary: fact names self, listener fenced at e - Unassigned --> Supporting: fact names another primary, self in peers - Supporting --> Primary: promotion, fact names self at a higher epoch - Primary --> Supporting: fact names another primary, self in peers - Primary --> Excluded: fact names another primary, self not in peers - Supporting --> Excluded: fact names another primary, self not in peers - Excluded --> Supporting: later fact lists self as a peer -``` - -**Host role and listener admission.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | -| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | -| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | -| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | -| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | -| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | -| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | -| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | - -**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | -| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | -| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | - -`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). - -### M4 Workspace HEAD holder and takeover - -One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. - -```mermaid -stateDiagram-v2 - state "Lease guard (host)" as G { - [*] --> NoLease - NoLease --> Valid: renewal reply for this volume, replica and epoch - Valid --> Valid: renewal before the local deadline - Valid --> Fenced: deadline passed, invalid reply, or revoking - Fenced --> Drained: frontend and cuts stopped - Drained --> Acked: revocation acknowledged with the HEAD gen - } - state "HEAD holder" as H { - [*] --> Attaching - Attaching --> Claiming: fresh local root - Attaching --> Holder: existing root, HEAD is this holder's - Attaching --> Refused: existing root, HEAD published by another holder - Claiming --> Holder: CAS to this epoch and holder, state active - Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch - Holder --> Detached: Detach final cut, state detached - Holder --> HolderFenced: a superseding HEAD is seen - } -``` - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | -| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | -| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | -| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | -| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | -| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | -| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | -| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | - -### M5 The cut pipeline - -A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. - -```mermaid -stateDiagram-v2 - [*] --> Admit - Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid - Admit --> Stage: earlier unknown CAS settled - Stage --> Quiesce: at most 3 pre-copy rounds - Quiesce --> OpenWindow: Sync H and D fixed under barrier - OpenWindow --> Copy: release barrier - Copy --> Closed: all candidates done - Copy --> Aborted: error, cancellation, observed fence, recovery or close - Aborted --> Refused: drain owners, cleanup, merge candidates - Copy --> Refused: H below HEAD RemoteLSN - Closed --> Upload: drain and cleanup; intent durable first - Upload --> Manifest - Manifest --> Readmit - Readmit --> Fenced: superseding HEAD - Readmit --> CAS - CAS --> Settled: CAS ok, or a re-read shows the proposal - CAS --> Pending: outcome unknown and HEAD unchanged - CAS --> Fenced: HEAD moved to a superseding holder - CAS --> Refused: HEAD moved otherwise (conflict) - Pending --> Admit: next cut settles it first -``` - -| Step | Guard | Enforced in | Protects | -|---|---|---|---| -| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | -| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | -| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | -| 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` | -| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; 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` | -| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | -| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | -| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | -| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | -| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | -| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | -| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | - -### M6 Chunk lifecycle - -HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). - -**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | -| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | -| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | -| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | -| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | -| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | -| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | -| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | - -**Snapshots and forks.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | 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` | - -**Intents and key bindings.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | -| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | -| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | -| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | -| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | - ---- - -## Part B. Invariant ledger - -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. - -### B.1 Core: storage, durability and the frontend gate - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +| ID | Invariant | Transition | Enforced in | Regression tests | Model | Status | |---|---|---|---|---|---|---| -| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | -| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | -| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | -| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | -| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | -| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | -| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | -| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | -| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | -| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | -| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | -| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | -| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | -| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | -| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | -| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | -| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | -| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | -| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | -| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | +| `INV-VOLUME-CREATE-SIZE-001` | Creation refuses capacity above 16 TiB - 4 KiB before provisioning, allocating a WAL, or persisting a volume record. Geometry checks cannot overflow. | M6 initial create (static parameter admission) | `core/geometry/volume_size.go`; lifecycle `CreateVolume`, CSI `volumeSpecFromCreateRequest`, catalog `EnsureVolume`, storage `CreateWALStoreWithOptions` | `TestCreateVolumeRejectsBeyondUint32LBACap`, `TestCSICreateVolumeCapacityCapBeforeProvision`, `TestEnsureVolumeRejectsBeyondUint32LBACap`, `TestCreateWALStoreRefusesOversizeBeforeFilesystem` | Static geometry bound; no protocol state or transition added | ACTIVE | -Notes: - -- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. -- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. - -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - -- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively. - -- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. -- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. -- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). -- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. -- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. -- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. -- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). - -### B.2 Core: authority and epochs - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | -| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | - -Notes: - -- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. -- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). -- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. - -### B.3 Core: replication and replica roles - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | -| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | -| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | -| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | -| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | -| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | -| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | -| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | - -Notes: - -- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. -- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). - -### B.4 Workspace: HEAD holder, lease and takeover - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | -| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | -| `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-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`) | `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-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | - -Notes: - -- `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. - -### B.5 Workspace: the cut pipeline - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `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-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | -| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | -| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | -| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | - -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). - -### B.6 Workspace: chunk lifecycle, GC and delete - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | -| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | -| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | -| `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 | - -Notes: - -- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. - -### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | -| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | -| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | -| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | -| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | -| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | -| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | -| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | - -Notes: - -- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). -- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. -- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. -- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. -- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. -- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. -- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. -- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. -- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. -- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. - -**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. - ---- - - -### B.8 NVMe/TCP receive bounds - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | - -## Part C. Change rules - -How a fix or a feature is calibrated against this model: - -1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. -2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). -3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. -4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. -5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. -6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. - -Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. - -### Dark v3 offline reader (row12a) - -- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. -- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. - -### Dark v3 chunk/BASE integration (row12a) - -- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. -- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. -- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. +## Part C. Change rules + +How a fix or a feature is calibrated against this model: + +1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. +2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). +3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. +4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. +5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. +6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. + +Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. + +### Dark v3 offline reader (row12a) + +- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. +- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. + +### Dark v3 chunk/BASE integration (row12a) + +- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. +- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. +- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. From 26426dd50efb8c01d8ee269837db743fcba29118 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:12:57 -0800 Subject: [PATCH 08/33] durable: a failed detach never leaves the guest frozen (MIGRATION E4) DetachVolume stopped guest I/O, then ran the whole final cut; on any error I/O stayed stopped for the process, even when nothing was published, and the only bound was the caller's context (up to 5 min). Now: - The freeze (drain + final cut) is bounded by DetachFreezeTimeout (default 20 s, below the host's 30 s I/O timeout); a freeze past the 5 s target is logged as an ALARM. - A detach that provably did not publish (the drain or the cut failed before its CAS, the CAS was refused, or an unresolved detach CAS was cancelled) resumes serving: periodic cuts restart, the stop is lifted, and ErrDetachAborted (HTTP detach_aborted, 409, retryable) is returned. The dirty set stays dirty, so the next cut publishes it. - The new ChunkLayer.SettleDetach decides an unresolved detach CAS: if HEAD is still that CAS's base, a CAS at the same base to the non-detached base image (this holder, this epoch) cancels it, so the detach can never land afterwards; HEAD carrying the detach means it applied (the detached result is returned, I/O stays stopped); a newer holder means fenced (stays stopped); HEAD unreadable leaves it undecided: ErrDetachOutcomeUnknown, I/O stays stopped. Never resume on top of a possibly detached HEAD. Tests: failed upload, refused CAS, lost unapplied CAS (cancelled, HEAD one generation on, not detached) resume and the next cut publishes the dirty blocks; an applied CAS whose reply was lost (found by the cut's re-read or only by the settle) stays detached; undecidable and fenced stay stopped; a hung CAS ends at the freeze bound, is settled and resumes; the old drain-timeout test flips (it asserted I/O stays stopped). Six declared mutants each turn exactly their declared tests red. Known limit: after an abort whose drain is still pending (an admitted I/O stuck), new I/O queues behind that admitted I/O (the drain holds a pending ioMu.Lock); serving resumes once it completes, not instantly. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 13 + .../core/frontend/durable/provider_chunk.go | 92 ++++-- .../provider_chunk_detach_abort_test.go | 272 ++++++++++++++++++ .../provider_chunk_detach_stop_test.go | 34 ++- .../core/host/volume/chunk_control.go | 4 + .../core/host/volume/chunk_control_test.go | 2 + seaweed-block/core/storage/chunk_layer.go | 69 +++++ seaweed-block/core/storage/chunk_public.go | 8 + seaweed-block/core/storage/chunk_seam.go | 17 ++ 9 files changed, 482 insertions(+), 29 deletions(-) create mode 100644 seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 1b9f8e565f..d115bc07af 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -81,6 +81,14 @@ var ErrImplKindMismatch = errors.New("durable: impl kind mismatch between select // volumeID has not been Open'd. var ErrVolumeNotOpen = errors.New("durable: volume not opened") +// ErrDetachAborted: the detach did not happen (its final cut provably did not +// publish), so the volume resumed serving on this host (MIGRATION E4). +var ErrDetachAborted = errors.New("durable: detach aborted; the volume keeps serving on this host") + +// ErrDetachOutcomeUnknown: whether the detach landed cannot be decided yet; +// I/O stays stopped (never resumed on a possibly detached HEAD). +var ErrDetachOutcomeUnknown = errors.New("durable: detach outcome unknown; I/O stays stopped") + // ProviderConfig configures a DurableProvider. type ProviderConfig struct { // Impl selects which LogicalStorage implementation to open or @@ -157,6 +165,11 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration + // DetachFreezeTimeout bounds how long DetachVolume keeps guest I/O + // stopped for its drain and final cut (the caller's context can only + // shorten it). Zero: 20 s, below the host's 30 s I/O timeout; a freeze + // past the 5 s target is logged as an alarm. + DetachFreezeTimeout time.Duration // ChunkDirtyThreshold is the bound on one cut's barrier copy, in // chunks. It never triggers a cut: the remote holds snapshots, and // cuts are published only by CaptureVolume, MakeVolumeRemoteDurable diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 7b4da71e7d..95add9aadc 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -262,15 +262,22 @@ func (p *DurableProvider) attachChunk(ctx context.Context, volumeID string, h *v h.backend.mu.Lock() h.backend.chunkFenced = layer.Fenced h.backend.mu.Unlock() - if p.cfg.ChunkCaptureInterval > 0 { - loopCtx, cancel := context.WithCancel(context.Background()) - h.chunkStop, h.chunkDone = cancel, make(chan struct{}) - go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) - } + p.startChunkLoop(volumeID, h, layer) } return nil } +// startChunkLoop starts the periodic cuts of an attached layer, if configured +// and not already running. The caller holds h.attachMu and p.mu. +func (p *DurableProvider) startChunkLoop(volumeID string, h *volHandle, layer storage.ChunkLayer) { + if p.cfg.ChunkCaptureInterval <= 0 || h.chunkStop != nil { + return + } + loopCtx, cancel := context.WithCancel(context.Background()) + h.chunkStop, h.chunkDone = cancel, make(chan struct{}) + go p.chunkLoop(loopCtx, volumeID, layer, h.chunkDone) +} + func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h *volHandle) (storage.ChunkLayer, error) { ws, ok := h.storage.(*storage.WALStore) if !ok { @@ -743,12 +750,19 @@ func (p *DurableProvider) CutVolume(ctx context.Context, volumeID string, minLSN } // DetachVolume is a clean stop's final cut (B9 W2 §3.6): it stops the -// volume's frontend I/O and waits (bounded by ctx) for the I/O already -// admitted to finish, stops the periodic cuts, then publishes one cut with -// HEAD state detached. It also returns the last LSN written. From its -// start, the volume stays stopped for this process, through any later -// RecoverVolume, even when the detach fails; a retry settles it and a -// repeated call returns the first result. +// volume's frontend I/O and waits for the I/O already admitted to finish, +// stops the periodic cuts, then publishes one cut with HEAD state detached. +// It also returns the last LSN written. The freeze (drain + final cut) is +// bounded by DetachFreezeTimeout and ctx. After a successful detach the +// volume stays stopped for this process, through any later RecoverVolume, +// and a repeated call returns the first result. A failed detach never leaves +// the guest frozen by a detach that did not happen (MIGRATION E4): +// - nothing published (the drain or the cut failed before its CAS, or the +// CAS was refused, or an unresolved detach CAS was cancelled): serving +// resumes and ErrDetachAborted is returned; +// - the detach CAS applied (its reply was lost): the detached result; +// - HEAD belongs to another holder: stays stopped (fenced); +// - undecidable (HEAD unreadable): stays stopped, ErrDetachOutcomeUnknown. func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (storage.ChunkCutResult, uint64, error) { p.mu.Lock() h, ok := p.volumes[volumeID] @@ -762,16 +776,60 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if err != nil { return storage.ChunkCutResult{}, 0, err } + freeze := p.cfg.DetachFreezeTimeout + if freeze <= 0 { + freeze = defaultDetachFreezeTimeout + } + fctx, cancel := context.WithTimeout(ctx, freeze) + defer cancel() + start := time.Now() + defer func() { + if d := time.Since(start); d > detachFreezeTarget { + log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) + } + }() h.chunkDetach = true - if err := h.backend.StopIO(ctx, "chunk detach: I/O stopped until a new attach"); err != nil { - return storage.ChunkCutResult{}, 0, err + if err := h.backend.StopIO(fctx, "chunk detach: I/O stopped until a new attach"); err != nil { + return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) // nothing was cut } p.stopChunkLoop(h) - r, err := layer.Detach(ctx) - if err != nil { - return storage.ChunkCutResult{}, 0, err + r, err := layer.Detach(fctx) + if err == nil { + return r, h.storage.NextLSN() - 1, nil } - return r, h.storage.NextLSN() - 1, nil + // Settle with time of its own: the freeze bound may be what ended the cut. + sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), detachSettleTimeout) + defer scancel() + how, dr, serr := layer.SettleDetach(sctx) + switch { + case serr != nil: + return storage.ChunkCutResult{}, 0, fmt.Errorf("%w: %w (settle: %w)", ErrDetachOutcomeUnknown, err, serr) + case how == storage.DetachApplied: + return dr, h.storage.NextLSN() - 1, nil + case how == storage.DetachFenced: + return storage.ChunkCutResult{}, 0, fmt.Errorf("durable: detach of %s: HEAD belongs to a newer epoch or another holder; I/O stays stopped: %w: %w", volumeID, storage.ErrChunkLayerFenced, err) + default: + return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) + } +} + +const ( + defaultDetachFreezeTimeout = 20 * time.Second + detachFreezeTarget = 5 * time.Second + detachSettleTimeout = 10 * time.Second +) + +// resumeAfterDetach undoes a detach that provably did not happen: the +// periodic cuts restart, the stop is lifted, and the volume serves again. +// The caller holds h.attachMu. +func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error { + h.chunkDetach = false + p.mu.Lock() + p.startChunkLoop(volumeID, h, layer) + p.mu.Unlock() + h.backend.SetOperational(true, "chunk detach aborted: serving resumed") + log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause) + return fmt.Errorf("%w: %w", ErrDetachAborted, cause) } // Preserve the optional manifest capability only when the inner remote has it; diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go new file mode 100644 index 0000000000..556dabe8bd --- /dev/null +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -0,0 +1,272 @@ +package durable_test + +// A failed detach (design MIGRATION E4, review S6): the guest is never left +// frozen by a detach that did not happen. When the final cut provably did not +// publish (a failed upload, a refused CAS, an unresolved detach CAS that a +// cancel at the same base settles), serving resumes on this host. When the +// detach landed, the volume stays stopped with the detached result. When the +// outcome cannot be decided (HEAD unreadable), it stays stopped: never resume +// on top of a possibly detached HEAD. + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +// faultRemote injects one fault into the next detach's remote calls. +type faultRemote struct { + *storage.MemChunkRemote + mu sync.Mutex + putErr error // returned by every Put while set + casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold" + getHeadErr error // returned by every GetHead while set + getHeadFail int // the next N GetHead calls fail +} + +var errInjected = errors.New("injected remote fault") + +func (r *faultRemote) set(f func(r *faultRemote)) { r.mu.Lock(); f(r); r.mu.Unlock() } + +func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error { + r.mu.Lock() + err := r.putErr + r.mu.Unlock() + if err != nil { + return err + } + return r.MemChunkRemote.Put(ctx, key, data) +} + +func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { + r.mu.Lock() + err := r.getHeadErr + if err == nil && r.getHeadFail > 0 { + r.getHeadFail-- + err = errInjected + } + r.mu.Unlock() + if err != nil { + return storage.ChunkHead{}, err + } + return r.MemChunkRemote.GetHead(ctx) +} + +func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) { + r.mu.Lock() + mode := r.casMode + r.casMode = "" // one fault, on the next CAS only + r.mu.Unlock() + switch mode { + case "precondition": + return 0, storage.ErrChunkHeadPrecondition + case "lost": + return 0, errInjected + case "hold": // held until the caller gives up: not applied + <-ctx.Done() + return 0, ctx.Err() + case "applied-lost": + if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil { + return 0, err + } + return 0, errInjected + } + return r.MemChunkRemote.CASHead(ctx, expected, next) +} + +// detachFixture: a chunk volume with one cut published and one more write +// (dirty), so the detach's final cut has something to upload. +func detachFixture(t *testing.T) (*faultRemote, *durable.DurableProvider, frontend.Backend) { + t.Helper() + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p := chunkProvider(t, t.TempDir(), remote, v1View(), 0) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 8192, block(2)); err != nil { + t.Fatal(err) + } + return remote, p, b +} + +// assertServing: the volume accepts writes and a cut publishes them, with a +// HEAD that is not detached. +func assertServing(t *testing.T, p *durable.DurableProvider, b frontend.Backend, remote *faultRemote) { + t.Helper() + ctx := context.Background() + if _, err := b.Write(ctx, 12288, block(3)); err != nil { + t.Fatalf("write after an aborted detach: %v; want the volume serving again", err) + } + r, err := p.CutVolume(ctx, "v1", 0) + if err != nil { + t.Fatalf("cut after an aborted detach: %v", err) + } + if r.Head.State == storage.ChunkHeadDetached { + t.Fatal("HEAD is detached after a detach that was reported aborted") + } + if !bytesEqual(headBlock(t, remote.MemChunkRemote, 2), block(2)) || !bytesEqual(headBlock(t, remote.MemChunkRemote, 3), block(3)) { + t.Fatal("the cut after an aborted detach lost the dirty blocks") + } +} + +func TestWALStoreChunk_FailedDetachUploadResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.putErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with failing uploads: %v; want ErrDetachAborted", err) + } + remote.set(func(r *faultRemote) { r.putErr = nil }) + assertServing(t, p, b, remote) +} + +func TestWALStoreChunk_RefusedDetachCASResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "precondition" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a refused CAS: %v; want ErrDetachAborted", err) + } + assertServing(t, p, b, remote) +} + +// The detach CAS's reply is lost and it did not apply: the settle cancels it +// with a CAS at the same base, so it can never land, and serving resumes. +func TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes(t *testing.T) { + remote, p, b := detachFixture(t) + base, _ := remote.MemChunkRemote.GetHead(context.Background()) + remote.set(func(r *faultRemote) { r.casMode = "lost" }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a lost, unapplied CAS: %v; want ErrDetachAborted after the cancel", err) + } + // The cancel is a real CAS at the detach's base: HEAD moved one generation + // and is not detached, so the lost detach CAS can never land afterwards. + if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached || head.Gen != base.Gen+1 { + t.Fatalf("HEAD after the cancel: gen %d state %q; want gen %d, not detached", head.Gen, head.State, base.Gen+1) + } + assertServing(t, p, b, remote) +} + +// The detach CAS's reply is lost but it applied: the detach succeeded, the +// volume stays stopped and DetachVolume returns the detached result. +func TestWALStoreChunk_LostDetachCASAppliedStaysDetached(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost" }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose CAS applied but lost its reply: %+v %v; want the detached result", r, err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an applied detach: %v; want ErrNotReady", err) + } +} + +// The detach CAS applied but its reply was lost AND the cut's own HEAD re-read +// failed: only the settle can tell. It reads HEAD, finds the detach, and the +// detach succeeds (stays stopped) instead of resuming on a detached HEAD. +func TestWALStoreChunk_LostDetachCASAppliedFoundBySettle(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "applied-lost"; r.getHeadFail = 1 }) + r, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil || r.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach whose applied CAS only the settle can see: %+v %v; want the detached result", r, err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a settled, applied detach: %v; want ErrNotReady", err) + } +} + +// The detach CAS's reply is lost and HEAD cannot be read: the outcome is +// unknown, so the volume stays stopped (also through a recovery). +func TestWALStoreChunk_UndecidableDetachStaysStopped(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with an undecidable outcome: %v; want ErrDetachOutcomeUnknown", err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an undecidable detach: %v; want ErrNotReady", err) + } + if _, err := p.RecoverVolume(context.Background(), "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { + t.Fatalf("recovery after an undecidable detach: %v; want the volume to stay stopped", err) + } +} + +// The freeze is bounded by DetachFreezeTimeout: a CAS that hangs ends there, +// the outcome is settled (HEAD still at base: cancelled) and serving resumes, +// all well inside bound + settle. +func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) { + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, + StorageRoot: t.TempDir(), + BlockSize: 4096, + NumBlocks: pcBlocks, + ChunkBlocks: pcChunkBlocks, + DetachFreezeTimeout: 300 * time.Millisecond, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + if _, err := p.CutVolume(context.Background(), "v1", 0); err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 8192, block(2)); err != nil { + t.Fatal(err) + } + remote.set(func(r *faultRemote) { r.casMode = "hold" }) + start := time.Now() + _, _, err = p.DetachVolume(context.Background(), "v1") + took := time.Since(start) + if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err) + } + if took < 300*time.Millisecond || took > 3*time.Second { + t.Fatalf("detach with a hung CAS took %v; want about the 300 ms freeze bound", took) + } + assertServing(t, p, b, remote) +} + +// HEAD belongs to a newer epoch: the detach's CAS is refused and the volume +// is fenced; it stays stopped (never resumes against another holder). +func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) { + remote, p, b := detachFixture(t) + ctx := context.Background() + cur, err := remote.MemChunkRemote.GetHead(ctx) + if err != nil { + t.Fatal(err) + } + newer := cur + newer.Epoch, newer.Holder = cur.Epoch+1, "another-holder" + if _, err := remote.MemChunkRemote.CASHead(ctx, storage.ChunkHeadVersion{Gen: cur.Gen, Epoch: cur.Epoch}, newer); err != nil { + t.Fatal(err) + } + if _, _, err := p.DetachVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerFenced) || errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach against a newer epoch: %v; want fenced, not aborted", err) + } + if _, err := b.Write(ctx, 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) && !errors.Is(err, frontend.ErrStalePrimary) { + t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err) + } +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index 368b60d143..b52c96f1ec 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -118,10 +118,11 @@ func TestWALStoreChunk_DetachDrainsAdmittedWrite(t *testing.T) { } } -// The drain is bounded by the caller's context: a detach that cannot drain -// fails, publishes nothing and keeps I/O stopped, also through a recovery; -// once the admitted write finishes, a retry settles the detach with it. -func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { +// The drain is bounded (the caller's context or the freeze bound): a detach +// that cannot drain publishes nothing, so it aborts and the volume serves +// again (MIGRATION E4; it used to stay stopped, review S6); once the admitted +// write finishes, a retry detaches with every acknowledged write. +func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { ctx := context.Background() remote := storage.NewMemChunkRemote() p, view := parkedProvider(t, remote) @@ -139,21 +140,27 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { dctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) _, _, err = p.DetachVolume(dctx, "v1") cancel() - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("detach that cannot drain: %v; want the context's deadline", err) + if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach that cannot drain: %v; want an aborted detach on the context's deadline", err) } if head, _ := remote.GetHead(ctx); head.State == storage.ChunkHeadDetached { t.Fatalf("a detach that did not drain published a detached HEAD: %+v", head) } - if _, err := p.RecoverVolume(ctx, "v1"); !errors.Is(err, storage.ErrChunkLayerDetached) { - t.Fatalf("recovery after a failed detach: %v; want the volume to stay stopped", err) - } - if _, err := b.Write(ctx, 8192, block(6)); !errors.Is(err, frontend.ErrNotReady) { - t.Fatalf("new write after a failed detach and a recovery: %v; want ErrNotReady", err) - } + // Serving resumes: a new write is accepted. The drain still pending from + // the aborted stop orders new I/O after the I/O admitted before it, so + // this write completes once that admitted write does (never on the + // detach itself). + nerr := make(chan error, 1) + go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() view.unpark() acked := <-werr == nil + if err := <-nerr; err != nil { + t.Fatalf("new write after an aborted detach: %v; want it accepted", err) + } + if _, err := p.RecoverVolume(ctx, "v1"); errors.Is(err, storage.ErrChunkLayerDetached) { + t.Fatalf("recovery after an aborted detach: %v; want the volume serving", err) + } o := detachOutcome{} o.r, o.last, o.err = p.DetachVolume(ctx, "v1") if o.err != nil || o.r.Head.State != storage.ChunkHeadDetached { @@ -162,6 +169,9 @@ func TestWALStoreChunk_DetachDrainIsBoundedAndStaysStopped(t *testing.T) { if acked && !bytesEqual(headBlock(t, remote, 1), block(5)) { t.Fatal("the write admitted before the stop was acknowledged but is not in the detached HEAD") } + if !bytesEqual(headBlock(t, remote, 2), block(6)) { + t.Fatal("the write accepted after the aborted detach is not in the detached HEAD") + } } // After a successful detach, RecoverVolume keeps I/O stopped and a repeated diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 9e0746d99c..d9365811c2 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -159,6 +159,7 @@ const ( codeFenced = "fenced" codeHeadConflict = "head_conflict" codeClosing = "closing" + codeDetachAborted = "detach_aborted" // the detach did not happen; the volume keeps serving here codeLSNBehind = "lsn_behind" codeInternal = "internal" codeBadRequest = "bad_request" @@ -231,6 +232,9 @@ func chunkErrorCode(err error) (int, string, bool) { switch { case errors.As(err, &ce): return catalogStatus(ce.Code), ce.Code, ce.Retryable + case errors.Is(err, durable.ErrDetachAborted): + // Before its cause: nothing was published and serving resumed here. + return http.StatusConflict, codeDetachAborted, true case errors.Is(err, storage.ErrChunkLayerFenced): return http.StatusConflict, codeFenced, false case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 34bc6f3baf..60e9c7f302 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -222,6 +222,8 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {fmt.Errorf("x: %w", storage.ErrChunkRemoteUnavailable), "remote_unavailable", 503, true}, {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, + {fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true}, + {fmt.Errorf("%w: %w (settle: %w)", durable.ErrDetachOutcomeUnknown, storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkRemoteUnavailable), "outcome_unknown", 503, true}, {fmt.Errorf("%w: %w: cut LSN 1, HEAD remote_lsn 10", storage.ErrChunkCaptureRefused, storage.ErrChunkLSNBehind), "lsn_behind", 409, false}, {&chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: "m"}, "invalid_label", 400, false}, {fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false}, diff --git a/seaweed-block/core/storage/chunk_layer.go b/seaweed-block/core/storage/chunk_layer.go index 7c96b0d050..0d9421bc20 100644 --- a/seaweed-block/core/storage/chunk_layer.go +++ b/seaweed-block/core/storage/chunk_layer.go @@ -1157,6 +1157,75 @@ func (l *chunkLayerImpl) Detach(ctx context.Context) (chunkCutResult, error) { return r, err } +// SettleDetach: see chunkLayer. Only an unresolved DETACH proposal needs a +// remote decision: if HEAD is still that CAS's base, it is cancelled by a CAS +// at the same base to the non-detached base image (this holder, this epoch), +// so whichever lands first decides and the detach can never land after a +// successful cancel. resolvePending would re-propose the detach instead. +func (l *chunkLayerImpl) SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) { + l.capMu.Lock() + defer l.capMu.Unlock() + if r, ok := l.storedDetach(); ok { + return detachApplied, r, nil + } + l.stMu.Lock() + fenced, pending, isDetach, base, intents := l.fenced, l.pending, l.pendingDetach, l.pendingBase, l.pendingIntents + baseHead := copyHead(l.head) + l.stMu.Unlock() + if fenced { + return detachFenced, chunkCutResult{}, nil + } + if pending == nil || !isDetach { + // Nothing of this detach can land: it failed before its CAS or was + // definitely refused (an unresolved ordinary cut settles as usual). + return detachNotPublished, chunkCutResult{}, nil + } + cur, err := l.remote.GetHead(ctx) + if err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved: %w: %w", errChunkCASOutcomeUnknown, err) + } + if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + if err := l.admit(); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (%w); cancel refused: %w", errChunkCASOutcomeUnknown, err) + } + cancel := copyHead(baseHead) + cancel.Epoch, cancel.Holder = l.cfg.Epoch, l.cfg.Holder + cancel.State, cancel.DetachedBy = chunkHeadActive, nil + gen, casErr := l.remote.CASHead(ctx, base, cancel) + if casErr == nil { + cancel.Gen = gen + cur = cancel + } else if cur, err = l.remote.GetHead(ctx); err != nil { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): %w: %w", casErr, errChunkCASOutcomeUnknown, err) + } else if !sameProposal(cur, *pending) && !l.supersededBy(cur) && cur.Gen == base.Gen && cur.Epoch == base.Epoch { + return 0, chunkCutResult{}, fmt.Errorf("storage: detach outcome unresolved (cancel: %v): HEAD unchanged: %w", casErr, errChunkCASOutcomeUnknown) + } + } + // Settled: the detach landed, or it can never land. + l.dropIntents(ctx, intents) + l.stMu.Lock() + defer l.stMu.Unlock() + cut := l.pendingCut + l.pending, l.pendingIntents = nil, nil + l.pendingDetach, l.pendingCut, l.pendingBase = false, chunkCutResult{}, chunkHeadVersion{} + switch { + case sameProposal(cur, *pending): + l.head, l.remoteLSN = copyHead(cur), cur.RemoteLSN + cut.Head = copyHead(cur) + l.detached = &cut + r := cut + r.Head = copyHead(cur) + return detachApplied, r, nil + case l.supersededBy(cur): + l.fenced = true + l.head = copyHead(cur) + return detachFenced, chunkCutResult{}, nil + default: + l.head = copyHead(cur) + return detachNotPublished, chunkCutResult{}, nil + } +} + func (l *chunkLayerImpl) storedDetach() (chunkCutResult, bool) { l.stMu.Lock() defer l.stMu.Unlock() diff --git a/seaweed-block/core/storage/chunk_public.go b/seaweed-block/core/storage/chunk_public.go index 5ec9d54104..8dcfb337a7 100644 --- a/seaweed-block/core/storage/chunk_public.go +++ b/seaweed-block/core/storage/chunk_public.go @@ -20,6 +20,14 @@ type ( ChunkLayerStats = chunkLayerStats ChunkIntent = chunkIntent ChunkDetachedBy = chunkDetachedBy + DetachSettlement = detachSettlement +) + +// How a failed Detach ended (ChunkLayer.SettleDetach). +const ( + DetachNotPublished = detachNotPublished + DetachApplied = detachApplied + DetachFenced = detachFenced ) // HEAD states. diff --git a/seaweed-block/core/storage/chunk_seam.go b/seaweed-block/core/storage/chunk_seam.go index 62f105cd1f..ae8cf78292 100644 --- a/seaweed-block/core/storage/chunk_seam.go +++ b/seaweed-block/core/storage/chunk_seam.go @@ -457,6 +457,15 @@ type chunkCutResult struct { } // chunkLayer is what the store owner drives. +// detachSettlement is how a failed Detach ended (SettleDetach). +type detachSettlement int + +const ( + detachNotPublished detachSettlement = iota + detachApplied + detachFenced +) + type chunkLayer interface { chunkSink // Cut takes a quiesced cut at H (the last written LSN), uploads the @@ -475,6 +484,14 @@ type chunkLayer interface { // Detach returns the first result. An unresolved detach CAS is settled // like any other unresolved CAS, before the next capture or Detach. Detach(ctx context.Context) (chunkCutResult, error) + // SettleDetach decides how a failed Detach ended, with the caller's I/O + // still stopped: detachNotPublished (HEAD does not and can never carry + // this layer's detach: serving may resume; the dirty set stays dirty), + // detachApplied (HEAD carries it: the detached result is returned) or + // detachFenced (HEAD belongs to a newer epoch or another holder). An + // error wrapping errChunkCASOutcomeUnknown leaves it undecided: stay + // stopped. It never resumes on top of a possibly detached HEAD. + SettleDetach(ctx context.Context) (detachSettlement, chunkCutResult, error) // MakeRemoteDurable is the durability point for snapshot, detach and // migrate: a Capture whose H >= t. Only a nil return makes t remote // durable; it requires the local Sync to cover t first, and fails From 7a1f9826fcf67e2a55424e272fe473e53b09f8a8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:13:30 -0800 Subject: [PATCH 09/33] chore: preserve original UTF-8 text and group shared geometry imports --- seaweed-block/core/csi/controller.go | 2 +- .../core/frontend/chunkstore/catalog.go | 24 +- seaweed-block/core/lifecycle/store.go | 3 +- seaweed-block/core/storage/walstore.go | 30 +- seaweed-block/docs/design/invariants.md | 988 +++++++++--------- 5 files changed, 524 insertions(+), 523 deletions(-) diff --git a/seaweed-block/core/csi/controller.go b/seaweed-block/core/csi/controller.go index c3032079c9..4e9f41ff26 100644 --- a/seaweed-block/core/csi/controller.go +++ b/seaweed-block/core/csi/controller.go @@ -3,12 +3,12 @@ package csi import ( "context" "errors" - "github.com/seaweedfs/seaweed-block/core/geometry" "log" "strconv" "time" csipb "github.com/container-storage-interface/spec/lib/go/csi" + "github.com/seaweedfs/seaweed-block/core/geometry" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index f6a634a16c..2b65ff8c4a 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1,7 +1,7 @@ package chunkstore // Catalog: the chunk control plane's filer metadata and Fork (B9 W2 spec -// §3-§5). Under the chunk base directory, per volume: +// §3-§5). Under the chunk base directory, per volume: // // //HEAD the published HEAD (ChunkRemote) // //keys/ chunk key bindings (ChunkRemote) @@ -15,7 +15,7 @@ package chunkstore // // Snapshot and fork are read-then-write. Each writes an intent naming the // keys it references before its final manifest write, and refuses that -// write once OpDeadline has passed since it read its source (spec §2.3). +// write once OpDeadline has passed since it read its source (spec §2.3). // The operation's intents are removed only once its outcome is settled: the // manifest is confirmed published (re-read shows it), or the attempt // cleanly aborted (it never sent the write, or another entry already holds @@ -30,12 +30,12 @@ import ( "encoding/json" "errors" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "path" "strconv" "strings" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" @@ -75,7 +75,7 @@ const ( OriginFork = "fork" // DefaultOpDeadline bounds a snapshot or fork from reading its source to - // its final write (spec §2.3). + // its final write (spec §2.3). DefaultOpDeadline = 5 * time.Minute defaultListLimit = 100 @@ -86,7 +86,7 @@ const ( maxSnapName = 128 ) -// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI +// Error codes of the control plane (spec §2.2), as the HTTP API and the CLI // report them. const ( CodeNotChunkVolume = "not_chunk_volume" @@ -161,7 +161,7 @@ type Parent struct { Gen uint64 `json:"gen"` } -// VolumeInfo is the VOLUME entry (spec §4.2). +// VolumeInfo is the VOLUME entry (spec §4.2). type VolumeInfo struct { Format int `json:"format"` VolumeID string `json:"volume_id"` @@ -208,7 +208,7 @@ type snapDoc struct { } // SnapshotInfo describes one snapshot, with the field names of the HTTP API -// (spec §3.2-§3.3). +// (spec §3.2-§3.3). type SnapshotInfo struct { VolumeID string `json:"volumeID"` Name string `json:"name"` @@ -269,7 +269,7 @@ type ForkRequest struct { } // ForkResult reports a fork, with the field names of the CLI output -// (spec §3.5). +// (spec §3.5). type ForkResult struct { Target string `json:"target"` Source string `json:"source"` @@ -326,7 +326,7 @@ func (c *Catalog) volRoot(vol string) (string, error) { return path.Join(c.base, vol), nil } -// CheckSnapshotName enforces the snapshot name rule (spec §4.4). +// CheckSnapshotName enforces the snapshot name rule (spec §4.4). func CheckSnapshotName(name string) error { if name == "" || len(name) > maxSnapName || strings.HasPrefix(name, ".") { return catErr(CodeInvalidName, false, nil, "snapshot name %q: 1-%d characters, not starting with '.'", name, maxSnapName) @@ -474,7 +474,7 @@ func (c *Catalog) ReadHead(ctx context.Context, vol string) (storage.ChunkHead, return h, true, nil } -// EnsureVolume applies the attach rules of spec §4.2 for a volume served +// EnsureVolume applies the attach rules of spec §4.2 for a volume served // with geometry g: it creates a missing VOLUME entry (origin create), and // refuses with geometry_mismatch when VOLUME disagrees with g, or with // fork_incomplete when VOLUME is a fork whose HEAD is not written yet. @@ -969,7 +969,7 @@ func (c *Catalog) claimName(ctx context.Context, vol, root string, req SnapshotR } // SnapshotReplay resolves a snapshot request against the catalog before -// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's +// the caller cuts (B9 W2 §3.2 step 1): when the name is held by req's // request and its attempt published, it returns that snapshot (Replayed, // true); held by another request, snapshot_exists; free, or held by req's // unpublished attempt, (zero, false, nil). It validates the whole request @@ -1053,7 +1053,7 @@ func (c *Catalog) ListSnapshots(ctx context.Context, vol string, opts ListOption } } -// DeleteSnapshot frees the name (spec §3.4, W5): +// DeleteSnapshot frees the name (spec §3.4, W5): // it marks the attempt deleting (or, when the attempt never published, // claims its path with an aborted tombstone so a late insert cannot land), // then removes the name record. The attempt path is never removed. It diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index e1c5ab62e9..5e3c4fea32 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -10,13 +10,14 @@ import ( "encoding/json" "errors" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "os" "path/filepath" "regexp" "sort" "sync" "sync/atomic" + + "github.com/seaweedfs/seaweed-block/core/geometry" ) var ( diff --git a/seaweed-block/core/storage/walstore.go b/seaweed-block/core/storage/walstore.go index 9c1c737229..196e024c65 100644 --- a/seaweed-block/core/storage/walstore.go +++ b/seaweed-block/core/storage/walstore.go @@ -3,13 +3,13 @@ package storage import ( "errors" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "os" "path/filepath" "sync" "sync/atomic" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/iolatency" ) @@ -64,7 +64,7 @@ type WALStore struct { syncDirectFrontierMetadata func([]byte) error writeSuperblockMetadata func([]byte) error syncSuperblockMetadata func() error - flusher *flusher // background WAL→extent applier; nil if disabled + flusher *flusher // background WAL→extent applier; nil if disabled admission *walAdmission // backpressure on WAL pressure; nil if disabled // admissionTimeout is the per-Write deadline for admission. If @@ -119,7 +119,7 @@ type WALStore struct { // as fromLSN > checkpointLSN - recoveryRetentionLSNs. Zero means // strict checkpoint-driven recycle. Operator sets via // blockvolume's --wal-retention-lsns flag at store construction. - // Stored in-memory only — NOT persisted to the superblock; on + // Stored in-memory only — NOT persisted to the superblock; on // restart the daemon re-applies the flag. // // Pinned by: INV-G6-RETENTION-POLICY-OPERATOR-VISIBLE. @@ -132,7 +132,7 @@ type WALStore struct { // --recovery-mode=dual-lane. // // nil = no gate (legacy behavior). Per docs/recovery-wiring-plan.md - // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. + // §6 + INV-RECYCLE-GATED-BY-MIN-ACTIVE-PIN. recycleFloorSrc RecycleFloorSource syncs atomic.Uint64 // completed logical Sync calls (test/diagnostic) @@ -374,7 +374,7 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B } s.syncSuperblockMetadata = f.Sync - // Background flusher: drains dirty map → extent, advances + // Background flusher: drains dirty map → extent, advances // checkpoint, allows WAL recycling. Defaults are conservative // for the demo workload; tunable via config in future. s.flusher = newFlusher(s, flusherConfig{}) @@ -387,7 +387,7 @@ func openInitializedInternal(path string, f *os.File, sb *superblock, metadata B // returning ErrWALFull to callers under transient load. // Watermarks 0.7/0.9 match V2 config.go defaults // (WALSoftWatermark, WALHardWatermark). Admission wakes the - // flusher via NotifyUrgent — same seam V2 wires for pressure- + // flusher via NotifyUrgent — same seam V2 wires for pressure- // driven flushes. s.admissionTimeout = 30 * time.Second s.admission = newWALAdmission(walAdmissionConfig{ @@ -766,7 +766,7 @@ func (s *WALStore) Write(lba uint32, data []byte) (uint64, error) { // WAL admission: throttle/block under WAL pressure. If admission // is disabled (admission==nil), Write proceeds immediately. The - // admission Acquire may block up to admissionTimeout — under + // admission Acquire may block up to admissionTimeout — under // hard pressure it spins waiting for the flusher to drain. s.beforeChunkMutation(uint64(lba), 1) s.lifecycleMu.RLock() @@ -1235,7 +1235,7 @@ func (s *WALStore) Sync() (uint64, error) { return frontier, nil } -// Boundaries returns the current R/S/H boundaries — what is durable, +// Boundaries returns the current R/S/H boundaries — what is durable, // what the WAL still retains, what's the newest write. func (s *WALStore) Boundaries() (R, S, H uint64) { s.mu.RLock() @@ -1273,7 +1273,7 @@ func (s *WALStore) BlockSize() int { return int(s.sb.BlockSize) } // persistCheckpoint to clamp checkpoint advancement against active // recover-session pin floors. Pass nil to disable. // -// Idempotent. Safe to call at any time — the gate is read under +// Idempotent. Safe to call at any time — the gate is read under // s.mu so concurrent persistCheckpoint sees a consistent value. // // Implements storage.RecycleFloorGate. @@ -1340,8 +1340,8 @@ func (s *WALStore) AdvanceWALTail(newTail uint64) { } // WriteExtentDirect installs a base block directly into the extent -// without going through the WAL append path — INV-RECV-BITMAP-CORE -// (§6.10). The receiver's per-session bitmap is the sole arbiter of +// without going through the WAL append path — INV-RECV-BITMAP-CORE +// (§6.10). The receiver's per-session bitmap is the sole arbiter of // BASE-vs-WAL conflict at this LBA; substrate-level WAL replay / // stale-skip is intentionally bypassed. // @@ -1482,16 +1482,16 @@ func (s *WALStore) RecoveryMode() RecoveryMode { // AppliedLSNs returns a partial view of per-LBA applied LSN: only // LBAs whose latest write is still in the WAL (not yet flushed to // extent) are reported. Once an entry is flushed and the dirty-map -// entry is cleared, walstore loses per-LBA LSN tracking — the +// entry is cleared, walstore loses per-LBA LSN tracking — the // extent stores data only, not per-LBA LSN. // // PARTIAL-VIEW LIMITATION: for full per-LBA applied-LSN tracking, // walstore would need a permanent per-LBA LSN map (substrate // refactor). The replica recovery apply gate is the authoritative -// correctness boundary; this partial seed is defense-in-depth — +// correctness boundary; this partial seed is defense-in-depth — // it correctly stale-skips recovery entries for LBAs still in the // WAL window, and falls back to "appliedLSN[LBA] = 0" semantics -// for flushed LBAs (which means recovery WILL apply them — +// for flushed LBAs (which means recovery WILL apply them — // acceptable when the gate's session-only tracking + live-lane // updates fill in the gap during the session). // @@ -1516,7 +1516,7 @@ func (s *WALStore) AppliedLSNs() (map[uint32]uint64, error) { // content is non-zero. // // This honors the LogicalStorage contract: "snapshots every -// written LBA's current bytes" — including LBAs whose data has +// written LBA's current bytes" — including LBAs whose data has // been flushed out of the dirty map into the extent. Filtering // zeros preserves the "snapshot of dirty bits" semantics callers // expect (a never-written LBA shouldn't appear in the output; diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index bcd8e43870..2eca4bf5da 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -1,500 +1,500 @@ -# Seaweed Block invariants and state machines - -This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. - -This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. - -The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). - -**Conventions.** These are the same as in the design documents. - -- Code references name a file and a function, not a line number. Test references name the test function and its file. -- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). -- Status: - - `ACTIVE`: a Go test in this repository asserts the statement. - - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. - - `ARCHIVED`: a retired row, kept with its reason. There are none yet. -- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. - -## Contents - -- [Part A. State machines](#part-a-state-machines) - - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) - - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) - - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) - - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) - - [M5 The cut pipeline](#m5-the-cut-pipeline) - - [M6 Chunk lifecycle](#m6-chunk-lifecycle) -- [Part B. Invariant ledger](#part-b-invariant-ledger) -- [Part C. Change rules](#part-c-change-rules) - ---- - -## Part A. State machines - -Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. - -### M1 walstore: open, recover, serve, fault - -The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). - -```mermaid -stateDiagram-v2 - [*] --> Opened: OpenWALStore / CreateWALStore - Opened --> Recovering: RecoverVolume - Recovering --> Serving: Recover ok, backend operational - Recovering --> RecoveryFailed: Recover error (typed reason) - Serving --> FaultLatched: fsync or WAL append fails - FaultLatched --> Closed: Close - RecoveryFailed --> Closed: Close - Serving --> Closed: Close - Closed --> Opened: reopen -``` - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | -| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | -| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | -| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | -| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | -| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | -| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | -| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | -| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | - -Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. - -Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). - -Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. - -### M2 Authority: assignment, epoch, lease - -blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves). - -**Assignment line, per volume.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | -| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | -| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | -| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | - -**Workspace lease and move, in blockmaster.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | -| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | -| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | -| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | -| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | -| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | -| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | -| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | - -### M3 Replica role and peer state - -The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). - -```mermaid -stateDiagram-v2 - [*] --> Unassigned: listener with a floor record, no role yet - Unassigned --> Primary: fact names self, listener fenced at e - Unassigned --> Supporting: fact names another primary, self in peers - Supporting --> Primary: promotion, fact names self at a higher epoch - Primary --> Supporting: fact names another primary, self in peers - Primary --> Excluded: fact names another primary, self not in peers - Supporting --> Excluded: fact names another primary, self not in peers - Excluded --> Supporting: later fact lists self as a peer -``` - -**Host role and listener admission.** - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | -| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | -| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | -| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | -| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | -| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | -| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | -| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | - -**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). - -| From | To | Event and guard | Enforced in | Protects | -|---|---|---|---|---| -| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | -| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | -| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | -| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | - -`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). - -### M4 Workspace HEAD holder and takeover - -One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. - -```mermaid -stateDiagram-v2 - state "Lease guard (host)" as G { - [*] --> NoLease - NoLease --> Valid: renewal reply for this volume, replica and epoch - Valid --> Valid: renewal before the local deadline - Valid --> Fenced: deadline passed, invalid reply, or revoking - Fenced --> Drained: frontend and cuts stopped - Drained --> Acked: revocation acknowledged with the HEAD gen - } - state "HEAD holder" as H { - [*] --> Attaching - Attaching --> Claiming: fresh local root - Attaching --> Holder: existing root, HEAD is this holder's - Attaching --> Refused: existing root, HEAD published by another holder - Claiming --> Holder: CAS to this epoch and holder, state active - Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch - Holder --> Detached: Detach final cut, state detached - Holder --> HolderFenced: a superseding HEAD is seen - } -``` - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | -| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | -| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | -| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | -| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | -| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | -| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | -| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | - -### M5 The cut pipeline - -A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. - -```mermaid -stateDiagram-v2 - [*] --> Admit - Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid - Admit --> Stage: earlier unknown CAS settled - Stage --> Quiesce: at most 3 pre-copy rounds - Quiesce --> OpenWindow: Sync H and D fixed under barrier - OpenWindow --> Copy: release barrier - Copy --> Closed: all candidates done - Copy --> Aborted: error, cancellation, observed fence, recovery or close - Aborted --> Refused: drain owners, cleanup, merge candidates - Copy --> Refused: H below HEAD RemoteLSN - Closed --> Upload: drain and cleanup; intent durable first - Upload --> Manifest - Manifest --> Readmit - Readmit --> Fenced: superseding HEAD - Readmit --> CAS - CAS --> Settled: CAS ok, or a re-read shows the proposal - CAS --> Pending: outcome unknown and HEAD unchanged - CAS --> Fenced: HEAD moved to a superseding holder - CAS --> Refused: HEAD moved otherwise (conflict) - Pending --> Admit: next cut settles it first -``` - -| Step | Guard | Enforced in | Protects | -|---|---|---|---| -| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | -| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | -| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | -| 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` | -| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; 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` | -| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | -| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | -| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | -| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | -| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | -| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | -| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | - -### M6 Chunk lifecycle - -HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). - -**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | -| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | -| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | -| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | -| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | -| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | -| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | -| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | -| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | -| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | - -**Snapshots and forks.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | 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` | - -**Intents and key bindings.** - -| From | To | Guard | Enforced in | Protects | -|---|---|---|---|---| -| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | -| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | -| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | -| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | -| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | -| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | - ---- - -## Part B. Invariant ledger - -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. - -### B.1 Core: storage, durability and the frontend gate - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | -| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | -| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | -| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | -| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | -| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | -| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | -| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | -| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | -| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | -| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | -| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | -| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | -| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | -| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | -| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | -| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | -| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | -| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | -| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | -| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | -| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | -| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | -| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | -| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | -| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | -| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | -| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | -| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | -| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | -| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | -| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | - -Notes: - -- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. -- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. - -- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. - -- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively. - -- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. -- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. -- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. -- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). -- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. -- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. -- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. -- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). - -### B.2 Core: authority and epochs - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | -| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | -| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | -| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | -| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | - -Notes: - -- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. -- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). -- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. - -### B.3 Core: replication and replica roles - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | -| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | -| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | -| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | -| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | -| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | -| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | -| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | -| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | -| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | - -Notes: - -- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. -- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). - -### B.4 Workspace: HEAD holder, lease and takeover - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | -| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | -| `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-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`) | `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-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | -| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | - -Notes: - -- `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. - -### B.5 Workspace: the cut pipeline - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `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-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | -| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | -| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | -| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | -| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | -| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | - -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). - -### B.6 Workspace: chunk lifecycle, GC and delete - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | -| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | -| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | -| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | -| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | -| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | -| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | -| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | -| `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 | - -Notes: - -- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. - -### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | -| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | -| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | -| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | -| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | -| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | -| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | -| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | -| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | -| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | - -Notes: - -- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). -- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. -- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. -- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. -- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. -- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. -- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. -- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. -- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. -- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. - -**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. - ---- - - -### B.8 NVMe/TCP receive bounds - -| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | -|---|---|---|---|---|---|---| -| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | - +# Seaweed Block invariants and state machines + +This is the protocol contract of Seaweed Block: the state machines the code implements, the invariants each transition must keep, where each invariant is enforced, which test asserts it, and which TLA+ property models it. It is written for people and for coding agents. Before changing a protocol path, find the machine in Part A and the rows in Part B, and follow the change rules in Part C. + +This document supersedes the internal ledger [`internal/docs/protocol/invariant-ledger.md`](../../internal/docs/protocol/invariant-ledger.md). Every ID from that ledger is kept here and was re-checked against the code; some statements were narrowed to what the tests in this repository actually assert, and each narrowing is noted under its table. The internal file stays for history; new rows go here. + +The design is described in three documents, and this one collects their machines and invariants in one place: the [core design](block-design.md), the [agent workspace design](agent-workspace-design.md) and the [Kubernetes block design](kubernetes-block-design.md). + +**Conventions.** These are the same as in the design documents. + +- Code references name a file and a function, not a line number. Test references name the test function and its file. +- A TLA+ entry names a specification in [`docs/spec/`](../spec/README.md) and an invariant or property defined in it. The models check designs at small scale and are mapped to the code by reading (see the [limits](../spec/README.md#limits)). +- Status: + - `ACTIVE`: a Go test in this repository asserts the statement. + - `STUB`: the code enforces the statement (by reading), but no test asserts it yet. A release note must not claim behaviour backed only by a `STUB` row. + - `ARCHIVED`: a retired row, kept with its reason. There are none yet. +- The rule carried over from the internal ledger still applies: an invariant without a test is a wish, not an invariant. + +## Contents + +- [Part A. State machines](#part-a-state-machines) + - [M1 walstore: open, recover, serve, fault](#m1-walstore-open-recover-serve-fault) + - [M2 Authority: assignment, epoch, lease](#m2-authority-assignment-epoch-lease) + - [M3 Replica role and peer state](#m3-replica-role-and-peer-state) + - [M4 Workspace HEAD holder and takeover](#m4-workspace-head-holder-and-takeover) + - [M5 The cut pipeline](#m5-the-cut-pipeline) + - [M6 Chunk lifecycle](#m6-chunk-lifecycle) +- [Part B. Invariant ledger](#part-b-invariant-ledger) +- [Part C. Change rules](#part-c-change-rules) + +--- + +## Part A. State machines + +Each machine lists its states, the allowed transitions, the guard that must hold for each transition, where the guard is enforced, and the IDs of the Part B rows that protect it. A state name in `code font` is a value in the code; the other names describe a condition and are not code types. + +### M1 walstore: open, recover, serve, fault + +The local storage engine and the durable backend in front of it. Diagrams in the core design: the per-I/O gate in [§1.1](block-design.md#11-frontends-and-the-backend-contract), and the life of one write (appended, synced, in the extent, checkpointed, reusable) in [§1.2](block-design.md#12-walstore-wal-plus-extent). + +```mermaid +stateDiagram-v2 + [*] --> Opened: OpenWALStore / CreateWALStore + Opened --> Recovering: RecoverVolume + Recovering --> Serving: Recover ok, backend operational + Recovering --> RecoveryFailed: Recover error (typed reason) + Serving --> FaultLatched: fsync or WAL append fails + FaultLatched --> Closed: Close + RecoveryFailed --> Closed: Close + Serving --> Closed: Close + Closed --> Opened: reopen +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | Opened | v3 A/B descriptors and owned-map dependencies valid, exclusive file ownership acquired; legacy formats refused; backend starts not operational | `core/storage/walstore.go` `OpenWALStoreWithOptions`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-WAL-OPGATE-001` | +| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001` | +| Recovering | Serving | v3 nonce/cursor-bound physical prefix satisfies its W/BASE gate; rollback fence and rebuilt bounds publish before reuse; `Recover` aborts/drains an open COW window before lower locks, holds the capture barrier and invalidates proofs at start/end (legacy LSN scan remains fixture-only) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `INV-WAL-SYNCED-RECOVERED-001`, `INV-WAL-REPLAY-LWW-001`, `INV-WAL-FRONTIER-GAP-001`, `INV-CUT-RECOVER-BARRIER-001` | +| Recovering | RecoveryFailed | a WAL integrity failure or an I/O error; the backend stays not operational and the host blocks local readiness with `wal_corrupt` or `io_error` | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `INV-WAL-TYPED-FAILCLOSED-001`, `INV-WAL-OPGATE-001` | +| Serving | Serving | each `Read`, `Write`, `Sync` passes the operational, chunk-fence and lineage checks; write admission samples the active writer's native pressure before waiting; a write is durable only when a covering `Sync` returns | `core/frontend/durable/storage_adapter.go` `gate`; `core/storage/walstore.go` `WALStore.Sync` | `INV-FE-LINEAGE-GATE-001`, `INV-WAL-SYNC-FRONTIER-001`, `INV-FE-FUA-SYNC-001`, `INV-FE-FLUSH-SYNC-001`, `INV-WAL-V3-ADMISSION-001` | +| Serving | Serving (checkpoint) | the flusher binds its snapshot/materialization to one recovery lifetime; extent and owned COW map are durable before the shared descriptor publisher advances checkpoint/tail; both slot tails pin reuse (C11 bitmap/superblock path remains legacy-fixture-only) | `core/storage/flusher.go` `flushOnceInternal`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `INV-WAL-CHECKPOINT-SNAPSHOT-001`, `INV-WAL-REUSE-PERSISTED-TAIL-001`, `INV-WAL-CKPT-META-FAIL-001`, `INV-CUT-BITMAP-001` | +| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `noteAppendFailure`, `syncFile` | `INV-WAL-FSYNC-STICKY-001`, `INV-WAL-APPEND-STICKY-001` | +| FaultLatched | FaultLatched | every later `Sync`, write, checkpoint and `Recover` on the same open store is refused | `core/storage/walstore.go` `stickyIOFault` | `INV-WAL-FSYNC-STICKY-001` | +| any | Closed | `Close`; a store with a latched fault does not write the final superblock | `core/storage/walstore.go` `WALStore.Close` | — | + +Production C11 file persistence was removed in row 14b: the durable provider no longer constructs a bitmap sidecar, and the historical file codec exists only in `legacy_c11_file_fixture_test.go`. `INV-CUT-BITMAP-001` retains its explicit legacy engine tests until row 14a; it does not certify the v3 disk format. Native checkpoint/capture coverage is `TestWALStoreV3_AutomaticMapCheckpoint`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, and `TestChunkLayer_OwnedMapIncrementalAfterRestart` (checkpointed and WAL-only changes survive reopen without a C11 sidecar). The production map publication/coverage rules remain `INV-WAL-V3-MAP-PUBLISH-001`; no descriptor transition, format or durability boundary changes here. The receiver session bitmap (`INV-RECV-BITMAP-CORE`) is separate and unchanged. + +Public walstore Create now selects mapped format v3/impl3 (mode C by default, mode A by create option). Open and offline readonly use A/B slot and owned-map validation; valid legacy formats are refused with `ErrUnsupportedLegacyFormat`, rather than silently retrofitted. The temporary old-engine/raw-codec test scope and every named native replacement are recorded in [the legacy inventory](format-v3-legacy-test-inventory.md). Native recovery validates nonce/cursor binding and a contiguous physical LSN prefix before applying the mode-specific W rule; an acknowledged-range integrity failure blocks startup. The provider's create geometry, auto probe, capture, HEAD restore and readonly/status controls exercise the public selector (`INV-WAL-V3-ACTIVATION-001`). Before reading v3 slots, both read/write and offline read-only open acquire an exclusive nonblocking file lock; the offline migration CLI acquires the same lock before any descriptor read or mutation (`INV-WAL-V3-OWNER-001`). Contention refuses open/migration without changing bytes; descriptor close or process exit releases ownership. This implements the existing offline-migration precondition, not a new serving state. The mapped v3 checkpoint also carries a complete-record physical tail through the covered LSN minus the configured retention window; partial batches remain retained. The existing sole publisher then performs metadata-only rollover when the fallback still pins that prefix. Reuse still requires both valid same-nonce slot tails and retirement of checkpointed dirty references under writer exclusion; idle, unchanged-checkpoint and admission paths also settle a pinned fallback. An unlocked catch-up scan revalidates the coherent checkpoint and tail before emitting anything. A failed rollover latches and grants no reuse (`INV-WAL-V3-RECLAIM-001`). + +Recovery warnings such as `wal_hole_suspected` are recorded in Serving without changing health (`INV-WAL-WARN-NO-HEALTH-001`). The open gaps of this machine (a corrupted synced record mid-history only warns; forged records in user data) are listed in the [core known issues](block-design.md#24-known-issues-and-work-in-progress) and are not ledger rows. + +### M2 Authority: assignment, epoch, lease + +blockmaster's publisher is the only component that mints epochs. Diagrams: the assignment lifecycle in [core §1.5](block-design.md#15-authority-blockmaster-assignments-epochs-leases), and the workspace lease and move in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves). + +**Assignment line, per volume.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| Unbound | Bound (epoch 1, endpoint version 1) | `IntentBind`; no slot of this volume holds a present line (checked per volume, also after a restart); to move to another slot use `IntentReassign` | `core/authority/authority.go` `applyWithWorkspaceMove`, `boundReplicaForVolume`; `core/authority/controller.go` `decideVolume` (binds only a volume with no line) | `INV-AUTH-ONE-PRIMARY-001`, `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Bound (endpoint version + 1) | `IntentRefreshEndpoint`; same epoch; a no-op when the addresses are unchanged | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| Bound | Reassigned (per-volume maximum epoch + 1) | `IntentReassign`; some earlier publication exists; an enrolled workspace volume changes only through a guarded move | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `INV-AUTH-EPOCH-MINT-001`, `INV-AUTH-ONE-PRIMARY-001` | +| any | (store write first) | with an authority store configured, every transition is written to the store before memory changes or subscribers are notified; a failed write publishes nothing, but its durable outcome may be unknown | `core/authority/authority.go` `applyWithWorkspaceMove` | `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | +| any (workspace) | Uncertain | a failed workspace authority write, including a lease extension; later changes for that volume, and renewals that would issue a new or extended grant, are refused until restart (a Revoking lease still gets its bounded drain reply) | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-AUTH-UNCERTAIN-001` | +| Bound | Deleting | a deletion reservation; the id is never created again | `core/host/master/services.go` `MarkVolumeDeleting` | `INV-VOL-ID-NO-REUSE-001` | + +**Workspace lease and move, in blockmaster.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | +| Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | +| Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | +| Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | +| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | +| Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | +| Expired | Moved (forced) | explicit force; the persisted lease horizon (at least every grant) plus the clock-skew bound and the granted or restart deadline plus the bound have both passed | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001` | +| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace` | `INV-AUTH-MOVE-JOURNAL-001` | + +### M3 Replica role and peer state + +The role a blockvolume takes from each assignment, its replica listener's admission, and the primary's view of each replica. This is the replication engine of [core §1.6](block-design.md#16-replication-and-failover) (which has the peer-state diagram) as the Kubernetes line uses it; promotion is in [Kubernetes §6](kubernetes-block-design.md#6-authority-promotion) (diagram) and the failover sequence in [Kubernetes §4](kubernetes-block-design.md#4-replication-and-failover). + +```mermaid +stateDiagram-v2 + [*] --> Unassigned: listener with a floor record, no role yet + Unassigned --> Primary: fact names self, listener fenced at e + Unassigned --> Supporting: fact names another primary, self in peers + Supporting --> Primary: promotion, fact names self at a higher epoch + Primary --> Supporting: fact names another primary, self in peers + Primary --> Excluded: fact names another primary, self not in peers + Supporting --> Excluded: fact names another primary, self not in peers + Excluded --> Supporting: later fact lists self as a peer +``` + +**Host role and listener admission.** + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| any | (no change) | local readiness blocked (recovery pending or failed): the fact is stored and replayed when readiness clears | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `INV-ROLE-READINESS-BLOCK-001` | +| any | (no change) | a role call below the current desired epoch is refused and does not clear a newer admission failure | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `INV-ROLE-STALE-REPLAY-001` | +| Unassigned, Supporting | Primary at e | the fact names this replica; the replica set is installed; the listener is fenced as primary and its floor e is persisted before the adapter is told | `core/host/volume/host.go` `applyFact`, `fenceSelfWithPeers`; `core/transport/replica.go` `FenceAsPrimary`, `raiseFloor` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001` | +| Unassigned, Primary | Supporting at e | the fact names another primary and lists this replica as a peer; the floor e is persisted first; the frontend stays gated | `core/host/volume/host.go` `applyFact`; `core/transport/replica.go` `AdmitAsReplica` | `INV-FENCE-FLOOR-DURABLE-001` | +| Primary, Supporting | Excluded | the fact names another primary and does not list this replica; ingress is closed, the other line is recorded and the frontend is unhealthy | `core/host/volume/host.go` `applyFact`, `recordOtherLine`; `core/host/volume/projection_bridge.go` `projectionWithSupersede` | `INV-ROLE-SUPERSEDED-001`, `INV-FENCE-STALE-PRIMARY-001` | +| any | role admission failed | the listener cannot be fenced or its floor cannot be persisted; the role is not adopted and the projection is not healthy | `core/host/volume/host.go` `latchRoleAdmission` | `INV-FENCE-FLOOR-DURABLE-001` | +| (every inbound frame) | — | a mutating frame is refused on a primary, below the floor, or before a role is known; the rebuild port applies the same rules; a failed apply closes the connection | `core/transport/replica.go` `acceptMutationLineage`, `admitMutation`, `EnterDualLane`, `handleConn` | `INV-FENCE-SELF-ON-PROMOTE-001`, `INV-FENCE-FLOOR-DURABLE-001`, `INV-REPL-REBUILD-PORT-FENCE-001`, `INV-REPL-APPLY-FAIL-001` | +| Supporting | promotion candidate | member, reachable, caught up, fenced at the current epoch, post-rebuild durable acknowledgement delivered; for RF=3 also a fresh probe and coverage of the required frontier: known, or proven by at least P-K+1 fresh ready peers when it is unknown | `core/engine/promotion_ready.go` `BuildPromotionReadyFact`; `core/host/master/product_loop.go` `applyPromotionEvidenceGate` | `INV-REPL-PROMOTION-READY-001`, `INV-PROMOTE-FRONTIER-001` | + +**Peer state, as the primary sees each replica** (type `ReplicaState` in `core/replication/peer.go`). A new peer starts `Healthy` (`NewReplicaPeer`). + +| From | To | Event and guard | Enforced in | Protects | +|---|---|---|---|---| +| `Healthy`, `Unknown` | `Degraded` or `CatchingUp` | ship, barrier or fence failure; or a probe that needs catch-up | `core/replication/peer.go` `ReplicaPeer.SetState`, `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary's WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001` | +| `CatchingUp` | `Healthy`, `Degraded` or `NeedsRebuild` | done-acknowledgement; failure; WAL recycled or retries exhausted | `core/replication/peer.go` `ReplicaPeer.SetState` | `INV-REPL-PEER-TRANSITIONS-001` | +| any but `NeedsRebuild` | `Healthy` | recovered | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | +| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate dual-lane session | `core/replication/peer.go` `replicaStateTransitionAllowed` | `INV-REPL-PEER-TRANSITIONS-001` | + +`ReplicaPeer.Invalidate`, called on a ship, barrier or fence error, goes through the same gate as `SetState` (`replicaStateTransitionAllowed`): `Healthy`, `Degraded` and `CatchingUp` move to `Degraded`; from `NeedsRebuild` the state is kept and the reason is still logged ([#182](https://github.com/seaweedfs/seaweed-block/issues/182)). A replicated `Sync` is judged per durability mode (`core/replication/durability.go` `EvaluateBarrierAcks`; `INV-REPL-DURABILITY-MODE-001`). + +### M4 Workspace HEAD holder and takeover + +One host at a time holds a workspace volume's HEAD in SeaweedFS. The sequence diagram of a clean and a forced move is in [agent workspace §7](agent-workspace-design.md#7-lease-takeover-and-host-moves); blockmaster's side of the lease is in M2. + +```mermaid +stateDiagram-v2 + state "Lease guard (host)" as G { + [*] --> NoLease + NoLease --> Valid: renewal reply for this volume, replica and epoch + Valid --> Valid: renewal before the local deadline + Valid --> Fenced: deadline passed, invalid reply, or revoking + Fenced --> Drained: frontend and cuts stopped + Drained --> Acked: revocation acknowledged with the HEAD gen + } + state "HEAD holder" as H { + [*] --> Attaching + Attaching --> Claiming: fresh local root + Attaching --> Holder: existing root, HEAD is this holder's + Attaching --> Refused: existing root, HEAD published by another holder + Claiming --> Holder: CAS to this epoch and holder, state active + Claiming --> HolderFenced: HEAD epoch higher, or another holder at this epoch + Holder --> Detached: Detach final cut, state detached + Holder --> HolderFenced: a superseding HEAD is seen + } +``` + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| NoLease, Valid | Valid | the reply names this `{volume, replica, epoch}`, its validity is positive and at most 30 s, and it arrives before the old deadline; the new deadline is anchored to the request start | `core/host/volume/workspace_lease.go` `Refresh` | `INV-WS-LEASE-001`, `INV-WS-FORCED-MOVE-001` | +| Valid | Fenced | the local deadline passes (checked on every projection read), the reply is invalid, or the lease is revoking; a fenced guard never reopens | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `INV-WS-LEASE-001` | +| Fenced | Drained, Acked | the stop callback succeeded; only then, and only when revoked, the acknowledgement is sent | `core/host/volume/workspace_lease.go` `drain` | `INV-WS-REVOKE-ACK-001` | +| Attaching | Refused | an existing local root whose HEAD another holder has published (`ErrChunkStaleLocalRoot`) | `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-STALE-LOCAL-ROOT-001` | +| Claiming | Holder | HEAD epoch not above the master-issued epoch, no other holder at the same epoch; the local frontier is seeded from HEAD before the CAS; I/O opens only after the claim | `core/storage/chunk_restore.go` `ClaimChunkHead`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` | `INV-WS-CLAIM-BEFORE-SERVE-001`, `INV-WS-HEAD-CAS-001` | +| Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | +| Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | +| Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | +| Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | + +### M5 The cut pipeline + +A cut publishes the local image at a quiesced, synced LSN H as the next HEAD. The steps are described in [agent workspace §5](agent-workspace-design.md#5-the-cut), and the figure in [§3](agent-workspace-design.md#3-remote-layout) shows them against the remote layout. All steps are in `core/storage/chunk_layer.go` `captureLocked` unless stated. + +```mermaid +stateDiagram-v2 + [*] --> Admit + Admit --> Refused: closed, fenced, detached, base install, reconciling, or lineage or lease invalid + Admit --> Stage: earlier unknown CAS settled + Stage --> Quiesce: at most 3 pre-copy rounds + Quiesce --> OpenWindow: Sync H and D fixed under barrier + OpenWindow --> Copy: release barrier + Copy --> Closed: all candidates done + Copy --> Aborted: error, cancellation, observed fence, recovery or close + Aborted --> Refused: drain owners, cleanup, merge candidates + Copy --> Refused: H below HEAD RemoteLSN + Closed --> Upload: drain and cleanup; intent durable first + Upload --> Manifest + Manifest --> Readmit + Readmit --> Fenced: superseding HEAD + Readmit --> CAS + CAS --> Settled: CAS ok, or a re-read shows the proposal + CAS --> Pending: outcome unknown and HEAD unchanged + CAS --> Fenced: HEAD moved to a superseding holder + CAS --> Refused: HEAD moved otherwise (conflict) + Pending --> Admit: next cut settles it first +``` + +| Step | Guard | Enforced in | Protects | +|---|---|---|---| +| Admit | not closed, fenced, detached or installing a base; `CaptureAllowed` (healthy primary, unchanged lineage, valid lease); no cut while reconciling | `core/storage/chunk_layer.go` `admit`, `captureLocked`; `core/frontend/durable/provider_chunk.go` `newChunkLayer` (`CaptureAllowed`) | `INV-CUT-RECONCILING-001`, `INV-WS-LEASE-001` | +| Settle pending | an earlier unknown CAS is resolved by re-reading HEAD before any new proposal | `core/storage/chunk_layer.go` `resolvePending` | `INV-WS-CAS-UNKNOWN-001` | +| Stage | while more than the barrier bound would be copied, pre-copy outside the barrier; new keys are covered by an intent first | `core/storage/chunk_layer.go` `stage` | `INV-CUT-INTENT-FIRST-001`, `INV-CUT-STAGED-REUSE-001` | +| 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` | +| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt; legacy bitmap/hash mode) is read into buffers; 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` | +| Upload | upload only chunks whose SHA-256 differs from HEAD, under fresh write-once keys, after a durable intent names them | `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CUT-INTENT-FIRST-001`, `INV-CHUNK-WRITE-ONCE-001` | +| Manifest | rewrite only segments whose references changed; new segments are covered by an intent | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-SEGMENT-REUSE-001`, `INV-CUT-INTENT-FIRST-001` | +| No-op cut | when nothing changed since HEAD, no CAS is sent, but HEAD is re-read; a HEAD that moved fences the holder | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001` | +| Readmit | admission is checked again right before the CAS; a superseding HEAD fences | `core/storage/chunk_layer.go` `admit`, `supersededBy` | `INV-WS-HEAD-CAS-001` | +| CAS | conditional update on `{gen, epoch}`, with `RemoteLSN = H`; refused for a lower epoch, a lower `RemoteLSN`, or a HEAD in a delete state | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001`, `INV-HEAD-DELETE-FROZEN-001` | +| Settled | drop the intents; reset the bitmap to the cut, keeping chunks dirtied after it | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` | +| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` | + +### M6 Chunk lifecycle + +HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in the SeaweedFS catalog. The HEAD-state and snapshot-name diagrams are in [agent workspace §6](agent-workspace-design.md#6-snapshots-forks-retention-gc-volume-delete). + +**HEAD states** (`active`, `detached`, `deleting`, `purging`, `deleted`, `aborted`). + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | +| `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | +| `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | +| `active`, `detached` | `deleting` | a blockmaster deletion reservation exists and HEAD is not held | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `markHeadDeleting` | `INV-VOLDEL-HELD-HEAD-001`, `INV-VOL-ID-NO-REUSE-001` | +| `deleting` | previous state | a snapshot name record exists: the delete is refused and reverted | `core/frontend/chunkstore/volume_delete.go` `snapshotsBlock`, `revertHeadDeleting` | `INV-VOLDEL-COMMIT-001` | +| `deleting` | `purging` | commit point, bound to the same delete incarnation | `core/frontend/chunkstore/volume_delete.go` `commitHeadPurging` | `INV-VOLDEL-COMMIT-001` | +| `purging` | `deleted` | chunks dropped and `VOLUME` marked deleted | `core/frontend/chunkstore/volume_delete.go` `finishHeadDeleted`, `markVolumeDeleted` | `INV-VOL-ID-NO-REUSE-001` | +| `deleting`, `purging`, `deleted` | — | no claim or cut moves HEAD; only the delete's own transitions | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-HEAD-DELETE-FROZEN-001` | +| — | `aborted` | a GC copy sweep settles a dead fork by an exclusive create of an aborted HEAD tombstone, so the fork can never publish | `core/frontend/chunkstore/catalog.go` `AbortFork`; `core/frontend/chunkstore/gc_copy.go` `SweepCopies` | — | + +**Snapshots and forks.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | 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` | + +**Intents and key bindings.** + +| From | To | Guard | Enforced in | Protects | +|---|---|---|---|---| +| — | intent live | written before the first upload of a cut, a segment or a copy | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `INV-CUT-INTENT-FIRST-001` | +| intent live | removed | the CAS outcome is known (success or a definite refusal) | `core/storage/chunk_layer.go` `captureLocked`, `dropIntents` | `INV-CUT-INTENT-FIRST-001`, `INV-WS-CAS-UNKNOWN-001` | +| intent live | expired | older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has a higher epoch | `core/frontend/chunkstore/gc.go` `Collector.run` | `INV-GC-INTENT-EXPIRY-001` | +| — | bound | exclusive create of the key; a key that exists or once existed is refused | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | +| bound | tombstoned, needle deleted | unrooted in two complete marks at least one grace period apart, older than the grace period, binding unchanged; an unreadable segment aborts the pass; the collector requires grace greater than the operation deadline | `core/frontend/chunkstore/gc.go` `Collector.run`, `NewCollector` | `INV-GC-REACHABLE-001`, `INV-GC-UNREADABLE-SEGMENT-001`, `INV-GC-GRACE-DEADLINE-001` | +| tombstoned | (never rebound) | bindings are never removed | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `INV-CHUNK-WRITE-ONCE-001` | + +--- + +## Part B. Invariant ledger + +80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. + +### B.1 Core: storage, durability and the frontend gate + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/recovery.go` `recoverWAL`; `core/storage/walstore.go` `WALStore.Recover` | `TestWALStoreAppendDuringFlushThenTornWrapKeepsSyncedRecords`, `TestWALStoreFullFlushThenTornWrapKeepsSyncedRecords` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-OPGATE-001` | A durable backend refuses `Read`, `Write` and `Sync` until `RecoverVolume` succeeds; a failed recovery leaves it refused. | M1 Opened → Serving; Recovering → RecoveryFailed | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/durable/provider.go` `RecoverVolume` | `TestT3b_DurableProvider_Open_StartsNotOperational` (`core/frontend/durable/provider_test.go`); `TestT3b_Recovery_CleanRecover_FlipsOperational` (`core/frontend/durable/recovery_test.go`); `TestWALStoreChunk_MoveBackOntoAnOldRootIsRefused` (`core/frontend/durable/provider_chunk_moveback_test.go`) | — | ACTIVE | +| `INV-WAL-REPLAY-LWW-001` | Replay applies the highest LSN per LBA, independent of the physical scan order. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALStoreRecoverLastWriterWinsAcrossScanOrder` (`core/storage/walstore_recovery_lww_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE | +| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the on-disk superblock has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_writer.go` `spaceUsed`, `tailPersisted`; `core/storage/walstore.go` `persistCheckpointReleasing` | `TestWALWriterReuseIsBoundedByTheDurableTail`, `TestWALStoreRecoverBoundsPersistFailureRefusesAppendsUntilRetry` (`core/storage/walstore_persisted_tail_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CHECKPOINT-SNAPSHOT-001` | A checkpoint never passes a synced write that is not yet in the extent. | M1 write lifecycle: InExtent → Checkpointed | `core/storage/flusher.go` `flushOnceInternal` | `TestFlusherSnapshotCutPreservesSyncedWrites` (`core/storage/flusher_snapshot_cut_test.go`); `TestWALStoreCheckpointSIGKILLCrashWindows` (`core/storage/walstore_checkpoint_crash_linux_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-FRONTIER-GAP-001` | Synced entries above an intentional LSN gap (a rebuild's frontier jump) are kept by recovery. | M1 Recovering | `core/storage/recovery.go` `recoverWAL` | `TestWALStoreRecoverKeepsSyncedEntriesAboveAnUnpersistedFrontierJump` (`core/storage/walstore_recovery_frontier_gap_test.go`) | `WALRecovery` `I1` | ACTIVE | +| `INV-WAL-CKPT-META-FAIL-001` | A failed checkpoint metadata write neither publishes the new checkpoint nor releases WAL space. | M1 write lifecycle: InExtent → Checkpointed (refused) | `core/storage/walstore.go` `persistCheckpointReleasing` | `TestFlusherCheckpointMetadataFailureDoesNotPublishOrRecycle` (`core/storage/walstore_checkpoint_safety_test.go`) | — | ACTIVE | +| `INV-WAL-FSYNC-STICKY-001` | After the first failed `fsync` of the store file (WAL, extent or superblock), the open store refuses every later `Sync`, write and checkpoint without calling `fsync` again; only a reopen and `Recover` clear it. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`, `stickyIOFault` | `TestWALStoreWALFsyncFailureIsSticky`, `TestWALStoreExtentFsyncFailureIsSticky`, `TestWALStoreCheckpointFsyncFailureIsSticky` (`core/storage/walstore_sticky_fsync_test.go`); `TestWALStoreQueuedSyncAfterAFailedFsyncIsRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-APPEND-STICKY-001` | A WAL append whose write failed latches the store fault; writers already queued behind it are refused. | M1 Serving → FaultLatched | `core/storage/walstore.go` `noteAppendFailure`, `WALStore.Write` | `TestWALStoreWritersQueuedBehindAFailedAppendAreRefused` (`core/storage/walstore_sticky_race_test.go`) | — | ACTIVE | +| `INV-WAL-SYNC-FRONTIER-001` | `Sync` never reports an uncovered write durable: it returns the global synced frontier, which is at least the caller's own write and is covered by a completed `fsync`. It may include later writes whose covering `fsync` completed before the caller resumed. | M1 write lifecycle: Appended → Synced | `core/storage/walstore.go` `WALStore.Sync` | `TestWALStore_SyncDoesNotClaimConcurrentWrite` (`core/storage/walstore_test.go`); `TestWALGenerationFirstCallerReturnOrdering` (`core/storage/walstore_sync_frontier_order_test.go`) | — | ACTIVE | +| `INV-WAL-TYPED-FAILCLOSED-001` | A corrupt replay at startup is reported as `wal_corrupt` at once and keeps local readiness blocked. | M1 Recovering → RecoveryFailed | `cmd/blockvolume/durable_startup.go` `openAndRecoverDurable`; `core/host/volume/recovery_watchdog.go` `LocalRecoveryHealthReason` | `TestDurableStartup_RealProviderCorruptReplayIsWALCorrupt` (`cmd/blockvolume/durable_startup_test.go`); `TestLocalRecoveryFailure_CorruptWALReportsWALCorruptAtOnce` (`core/host/volume/recovery_typed_reason_test.go`) | — | ACTIVE | +| `INV-WAL-WARN-NO-HEALTH-001` | Recovery warnings (for example `wal_hole_suspected`) appear in status without changing health or eligibility. | M1 Serving | `core/host/volume/status_server.go` `statusProjection` | `TestStatusServer_StatusCarriesRecoveryWarningsWithoutChangingHealth` (`core/host/volume/status_warnings_test.go`) | — | ACTIVE | +| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned mapped v3/impl3 volume with the requested chunk geometry and C default/A option. Writable/readonly open validate A/B dependencies, reject actual legacy headers without mutation, and can select a valid fallback when A is damaged. Production provider capture/HEAD restore/status use those selectors. Legacy fixture constructors cannot be called by default production code or enter its transitive storage import closure. | M1 open/create/readonly | `walstore.go` public selectors; `walstore_v3.go` `refuseLegacyWALStore`, `ProbeWALStoreV3`; `provider.go` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionRefusesLegacyWithoutMutation`, `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy`, `TestWALStoreProductionCreateOptions`, `TestLegacyFixtureIsolation`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE | +| `INV-WAL-V3-FLUSH-PROFILE-001` | Native flusher header/full-record/decode counters describe actual reads and validation; I/O failure is distinct from validation failure and only successfully materialized blocks count validated. | M1 checkpoint instrumentation | `walstore_v3.go` `readWholeRecordProfiledV3`, `readDirtyRecordV3` | `TestFlusherV3ProfileCountsRealRecordStages` | Observability; no durability transition change | ACTIVE | +| `INV-WAL-V3-CAPTURE-CANDIDATES-001` | A retained WAL entry already covered by HEAD is not dirt since HEAD. New post-HEAD WAL entries, UNKNOWN map chunks and map max-LSN above HEAD remain capture candidates. | M5 candidate selection | `chunk_layer.go` `captureCandidates` | `TestChunkLayerV3CapturedUncheckpointedWALIsCleanUntilRewritten`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites` | Conservative reachability unchanged; narrower redundant work | ACTIVE | +| `INV-WAL-V3-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid. It needs a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2 and a nonzero nonce. Its geometry must be consistent with checked arithmetic, its BASE fields must follow their per-state rules, and CheckpointLSN ≤ mapCoveredCheckpoint ≤ W must hold. Of the two slots, the valid selectable one with the higher slotGen wins. A prepared migration slot is never selected. Equal generations with different bytes, or slots that disagree on identity or geometry, are refused. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `selectSlotV3`, `nextSlotGenV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3Selection`, `TestSlotV3CounterExhaustion`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB | +| `INV-WAL-V3-RECORD-001` | An impl-3 record codec uses the fixed 62-byte prefix and 70-byte overhead, CRC32C and an explicit EntrySize. It refuses unknown types/flags, a zero nonce, invalid per-type geometry, overflowing count/LSN/cursor or LBA spans, nonzero padding, bad CRC/footer and truncation before allocating a payload. Codec success alone is not nonce/cursor/lap replay admission. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `encodeWALEntryV3`, `decodeWALEntryV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints`, `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB | +| `INV-WAL-V3-LSN-ORDER-001` | A v3 writer accepts only a first LSN above its highest consumed LSN; a batch consumes its whole validated range. Equal/lower requests return ErrWALLSNOrder before any pwrite or cursor change. Constructor coverage and a recovered kept frontier count as consumed; a fenced-away suffix does not. | M1 v3 append | `core/storage/wal_io_v3.go` `append`, `newWALWriterV3`, `restoreScanV3` | `TestWALLSNOrderV3_RefusesDuplicateAndLower`, `TestWALLSNOrderV3_BatchConsumesFullRange`, `TestWALLSNOrderV3_RestoreUsesKeptNotDroppedFrontier`, `TestWALLSNOrderV3_DescriptorFloorIsAlreadyConsumed`, `TestWALIOV3_ValidatedFrontierIntervals`, `TestWALIOV3_ConcurrentAppendsHaveUniqueCursors` | Physical LSN-strict prefix is a contract constraint; r16 model correspondence is pending | STUB | +| `INV-WAL-V3-ADMISSION-001` | Native v3 WAL pressure uses its physical writer head minus the both-slot reuse floor, never the inactive legacy writer. Existing soft/hard waits wake the flusher without holding store, descriptor or writer locks. A terminal I/O fault latched during a pressure or semaphore wait ends that wait with the original typed cause; timeout must not mask an already observed fault. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire` | `TestWALStoreV3AdmissionUsesNativeOccupancy`; `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback); `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE | +| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint releases only complete validated record ends covered by the checkpoint and outside the retention window; an installing BASE retains its install suffix. Physical recovery rebuilds the volatile boundary index only from the trusted kept scan, without restoring a disconnect cursor. Tail/head/map/checkpoint/W publish together, followed by metadata-only rollover; both slot tails still pin reuse. Failure grants no reuse and retains exact dirty retry identity. Checkpoint publication excludes writer admission through both-slot rollover and dirty-reference retirement. Idle, unchanged-checkpoint and admission settle pending rollover; catch-up revalidates tail/checkpoint before delivering its buffered scan. | M1 checkpoint / existing two-slot retirement | `wal_io_v3.go` `reclaimThroughV3`, `rememberReclaimScanV3`; `walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `descriptor_v3.go` `rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin`, `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse`, `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint`, tagged `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB | +| `INV-WAL-V3-OWNER-001` | v3 read/write open, offline readonly open and migrate-v3 acquire the same exclusive nonblocking OS file lock before reading slots or changing bytes. Contention refuses with volume locked; descriptor close releases it, allowing retry. | M1 open admission / offline migration precondition | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go`; `cmd/sw-block/migrate.go` | `TestMigrateV3RefusesAnOpenV3Volume`, `TestMigrateV3ExcludesOpenUntilCommitFinishes` (tag `swblock_format_v3_test`), `TestWALStoreV3CreatorKeepsOwnershipThroughPublication`, `TestWALStoreV3OwnerExcludesOpenAndReadOnly` | OS mutual exclusion is a caller obligation, outside the abstract crash model; existing open states unchanged | STUB | +| `INV-WAL-V3-CATCHUP-001` | A dark v3 catch-up source refuses while installing, including an empty at-head request. Requests covered by an installed BASE require rebuild (typed WALRecycled); damage in retained WAL remains an integrity failure. Before emitting any entries the scan revalidates recovery generation, nonce, BASE state/ID and install epoch, so begin/complete/retire ABA cannot publish a superseded prefix. | M1 BASE lifecycle / M3 CatchingUp (dark callers) | `core/storage/walstore_recovery.go` `ScanLBAs`, `scanLBAsV3`, `v3CatchUpEntries` | `TestCatchUpV3InstallingAtHeadRefuses`, `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`, actual catch-up sender) | Existing BASE and catch-up transitions unchanged; this physical scan/source-lifetime obligation is covered by deterministic caller tests | STUB | +| `INV-WAL-V3-BINDING-001` | The dark v3 writer stamps the selected nonce and absolute cursor, fits each append/padding inside the dual-slot reuse floor, and refuses later I/O after a pwrite failure. A dark scanner checks nonce and exact expected cursor before using Length/count, checks the full record again, skips only geometric end slack, and stops at the first untrusted record without payload resynchronization. It returns a typed scan result, never ACK or serving permission. | M1 Recovering (dark muscles only) | `core/storage/wal_io_v3.go` `append`, `scanWALV3`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_InstalledScanBeginsAtMaxTail`, `TestWALIOV3_FloorAndPwriteFailureRefuse` | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB | +| `INV-WAL-V3-MAP-PUBLISH-001` | After a dark publisher binds a validated map, every publication carries a matching immutable tuple with merged checkpoint <= C <= merged W. A prepared replacement needs a higher generation, non-regressing coverage and the same sidecar/open proof domain with unchanged epoch/mutation token. Stale candidates write no slot; W-only rollover carries the current root; unknown slot outcomes pin dependencies. | M1 (dark map publication only; checkpoint/capture caller wiring pending) | `core/storage/chunk_map_publication_v3.go`; `core/storage/descriptor_v3.go` `publishLockedWithMapV3` | `TestWALStoreV3_SeedNeverUsesLegacyDescriptorWriter`, `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`, `TestDurableProviderV3_DefaultSelectorCreatesV3` (tag `swblock_format_v3_test`), `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`; `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB | +| `INV-WAL-V3-FLUSH-LIFETIME-001` | A dark v3 flusher binds its dirty snapshot and extent materialization to the original even Recover generation. A cycle spanning Recover/reset publishes no checkpoint/map and retires no reused dirty entry. | M1 Recovering / checkpoint publication | `core/storage/flusher.go`; `walstore_map_checkpoint_v3.go`; `walstore_v3.go` `flushLifetimeValidV3` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` | Existing recovery/map proof lifetime; implementation correspondence | STUB | +| `INV-WAL-V3-MAP-BYTES-001` | A dark v3 map candidate names immutable, owned, identity- and geometry-checked pages and root. Domain-separated body digests, reserved/unused bytes, exact page counts, file bounds and non-aliasing intervals all validate before entries escape. Persistence orders pages/fsync, root/fsync, directory fsync; a persistence-transaction error yields no candidate and latches subsequent I/O; preflight and Stat errors do not latch. Append-only retention preserves both slots and pending candidates. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB | +| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor change goes through one publisher. It writes the fallback slot with slotGen+1 under `descMu`. It takes `WALStore.mu` only to snapshot and releases it before slot I/O, and fsync is the leaf. It rebases onto the authoritative descriptor: W and the checkpoint are max-merged, and identity, geometry and nonce changes are refused, as are tail regression, a map root change without a higher generation and any BASE edge outside DESIGN 8.5 (installed -> installing is refused). A failed slot write (full or partial) or fsync publishes nothing. It latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a queued store Sync cannot acknowledge through it, keeps the uncertain candidate pinned and refuses every later publication, rollover and reuse until a reopen reads the slots back. A fault latched mid-flight is refused at the success boundary. A counter above 2^64-2 is refused with `ErrCounterExhausted` before any write. When the fallback slot pins reuse, a metadata-only rollover advances the floor, and no floor is ever computed across nonces. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `publish`, `mergeDescriptorV3`, `baseTransitionAllowedV3`, `rolloverIfPinned`, `reuseFloor` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress`, `TestDescriptorV3LockOrderRecorder`, `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary`, `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned`, `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor`, `TestDescriptorV3BaseTransitionTable`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3PublicationCounterExhaustion`, `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB | +| `INV-WAL-V3-W-001` | v3 Sync acknowledges only after an fsync covers the batch. In mode C (the default) the slot carries the previous batch's acknowledged W and the batch's single fsync covers WAL and slot; in mode A the WAL fsync precedes a slot publication with W = H. Recovery refuses (`wal_corrupt`) when the contiguous prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, max trusted DurableLSN). Mode C's only unprotected acknowledged data is the newest batch, against media corruption before the next Sync or the idle refresh; `SetWMode` and the refresh close that window. Flushed entries above the published checkpoint remain retry work, so a later Sync plus cycle can advance checkpoint and map coverage together. | M1 Recovering → Serving \| RecoveryFailed; M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `refreshW`, `SetWMode`, `recoverV3`, `appendWriteV3`; `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW`, `TestWALStoreV3LegacySuperblockWritersRefuse` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`, `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt`, `TestWALStoreV3AppendWriteErrorLatchesTheStore`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap`, `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary`, `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases`, `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3InstallingScanErrorIsTypedNotReady`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model (claude05, r14 run) | STUB | +| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes exactly the logical WAL interval [E, floor+WALSize) (floor = both slots' same-nonce reuse floor) split at the physical wrap, fsyncs it through the leaf, then publishes retainedHead = E; no byte before E or outside the interval changes, so records dropped by one recovery never resurface after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.fenceV3`, `recoverV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes`, `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | `WALFormat` `NoResurrection` (claude05) | STUB | +| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused, writing nothing, unless the dirty map is empty (no entry names an old-incarnation WAL position) and every appended LSN is checkpointed (CheckpointLSN >= appended, hence = acknowledged W). It publishes the new nonce with an empty cursor space into one slot and then the other, and is successful only after both. A crash between the two opens the new incarnation; no reuse floor exists across the two nonces, and no writer binds until Recover's head publication completes the other slot. LSNs, W and the map root are unchanged. A read holds no lock across its WAL read; it validates the whole record it read (CRC, footer, type, LBA, LSN) against the resolving dirty entry and re-resolves on a mismatch, so a position reused by the new incarnation never serves another block (LSN allocation runs on across a reset; no nonce is checked). It reports WAL damage only for an unchanged entry with the same recovery generation before and after the attempt (bumped at the start and the end of every recovery and reset); a failed pread is substrate I/O. | M1 Serving → Serving (reset, dark) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3`, `halfResetV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode`; `core/storage/walstore_v3.go` open and `recoverV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RefusesTheCurrentOrAZeroNonce`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock`, `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3CrashOutcomes`, `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData`, `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash`, `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover`, `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock`, `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (claude05 r4.5, pending) | STUB | +| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only under `installMu` exclusive (draining the old ID's admitted mutations) and only when BaseLSN covers the acknowledged W (published or not yet), the checkpoint and every appended LSN (an unacknowledged record above BaseLSN would leave a hole behind BaseCursor; codex01 row 9a P1-1); otherwise it is refused, writing nothing, with `ErrInstallBaseUncovered` or `ErrInstallSupersedeUncovered`. It publishes installing (BaseLSN, BaseCursor = the writer head P, the ID) into both slots before the first BASE mutation. BASE extent writes and install-lane applies go only through the handle, under `installMu` shared: a handle lives until the next begin (an install epoch), `WriteBase` needs installing under its ID, and an install-lane apply is also admitted after the handle's own completion while installed or retired, because the session's WAL lane can outlive its BaseDone (DESIGN r17.4; `ErrInstallSuperseded` otherwise); the install lane keeps the order and gap rules. Complete validates the ID under `installMu` exclusive, fsyncs the BASE bytes and the suffix, runs the checkpoint's metadata and chunk barriers and publishes installed with retainedTail >= BaseCursor together with a fresh owned-map candidate carrying the BASE writes' UNKNOWN (codex01 row 9a P1-2) and stops serving the superseded pre-BASE records. installing -> none is refused (no abort); installed -> none retires only once the checkpoint covers BaseLSN and both slots carry a tail at or past BaseCursor; a chunk-managed store may defer it (`DeferBaseRetirementV3` at open) until its chunk layer has durably recorded local presence (`AllowBaseRetirementV3`), so the installed descriptor stays the provider's completed-image evidence; the provider's durable attach commit (`CommitChunkAttachV3`, under `installMu` exclusive: its fresh-marker removal and directory fsync, then the per-open durable-attach flag) lifts it for an installed volume, so a completed BASE never retires while a reopen could still read the volume as fresh from HEAD. | M1 Serving → Installing → Serving (dark) | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.WriteBase`, `installHandleV3.ApplyInstallEntry`, `WALStore.markBaseCompleteV3`; `core/storage/descriptor_v3.go` `baseTransitionAllowedV3`, `retireBaseV3` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots`, `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusals`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash`, `TestBaseInstallV3InstallingToNoneIsRefused`, `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3ApplyInstallEntryOrderAndGap`, `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN`, `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3BeginRefusesWithAnAttachedChunkLayer`, `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix`, `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`); `TestDescriptorV3BaseTransitionTable`; tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle`, `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession`, `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck`, `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (claude05 R17c, pending) | STUB | +| `INV-WAL-V3-INSTALL-ACK-001` | While a v3 volume is installing, the logical `Sync` returns exactly (0, `ErrBaseInstalling`), runs no batch and acknowledges no new W, rechecked at its completion. The receiver's durable progress ack is `SyncInstallLog(installID)` on the narrow `InstallLogSyncer` (not on `LogicalStorage`; named only by `core/storage` and `core/recovery`): under `installMu` shared it refuses outside an install (`ErrNotInstalling`) or for another ID (`ErrInstallIDMismatch`), freezes H, fsyncs the WAL and publishes W = max(W, H) with BaseState still installing, always mode A, and acknowledges H only if no fault latched by its final check under `WALStore.mu` (the #172 ack boundary). It attests log durability only. After the session's own completion the receiver acks through the ordinary `Sync`. A v2 store's `SyncInstallLog` is its `Sync`. | M1 Installing (dark) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`; `core/storage/walstore.go` `WALStore.Sync`; `core/recovery/receiver.go` `sendAck` | `TestInstallLogV3SyncIsGatedWhileInstalling`, `TestInstallLogV3Refusals`, `TestInstallLogV3IsModeAAndSurvivesACrash`, `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`); `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`); tagged `TestReceiverV3ProgressAckIsTheInstallLog` | `WALFormat` install-log ack (claude05) | STUB | +| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n blocks is one multi-block record (type 0x04) with LSNs first..first+n-1 and one CRC32C, so a crash keeps all of it or none; the writer consumes the whole LSN range, so the next write continues after it. Each block's dirty entry names its data offset inside the record, and every reader (the store read, the flusher, recovery's replay, the install-path replays and the dark offline reader) validates the whole record and the block's LBA, LSN and offset in it. A torn unacknowledged batch is dropped whole; a torn acknowledged one fails closed; a failed batch pwrite latches the store and is never acknowledged. The map coverage follows every block's LSN. | M1 Serving (dark) | `core/storage/walstore_v3.go` `writeBatchV3Locked`, `replayRecordV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`; `core/storage/walstore.go` `WriteBatch`; `core/storage/walstore_readonly_v3.go` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt`, `TestWALStoreV3BatchAckCoversItsLastLSN`, `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records (claude05) | STUB | +| `INV-WAL-V3-MIGRATE-001` | `sw-block migrate-v3` rewrites only the descriptor of a cleanly closed v2/impl1 volume whose WAL the exhaustive scan proves flushed; the scan and the geometry check run before any write, and a refusal leaves the volume and every sidecar byte-identical. It keeps the extent base (WALSize = old - 4096), writes an atomic operator backup, an all-UNKNOWN initial map (covered = the v2 checkpoint), the prepared slot B, slot A at phase 0 (the commit point), slot B at phase 0, and only then retires the v2 chunk bitmap; each step is durable before the next. A rerun decides from the slot bytes alone: before the commit it restarts with a full rescan; after it, it only finishes the rollover and the retirement; a prepared B with an invalid A refuses with `ErrMigrationIncomplete`, as v3 open does; it never reads or restores the backup. | offline tool | `cmd/sw-block/migrate.go`; `cmd/sw-block/internal/v2legacy`; `core/storage/migrate_v3.go` | `TestMigrateV3CleanVolume`, `TestMigrateV3RefusalsChangeNothing`, `TestMigrateV3CrashAfterEachStepIsResumable`, `TestMigrateV3OldBinaryAfterPreparation`, `TestMigrateV3OldWALOverwritesThePreparedSlot`, `TestMigrateV3NeverRestoresTheBackup` (`cmd/sw-block/migrate_test.go`); tagged `TestMigrateV3VolumeOpensAsV3`, `TestMigrateV3PreparedOnlyRefusedByV3Open` | none (tool) | STUB | +| `INV-FE-FUA-SYNC-001` | A FUA write completes only after `Sync` succeeds. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.write`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestNVMeWriteFUACompletion` (`core/frontend/nvme/fua_test.go`); `TestDispatch_WriteFUASyncsBeforeCompleting` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-FLUSH-SYNC-001` | A flush is a `Sync` of the backend, and a failed `Sync` fails the command instead of acknowledging it. The NVMe session records its mapped status and backend reason in the target log. | M1 Serving (frontend) | `core/frontend/nvme/io.go` `IOHandler.Handle`; `core/frontend/ublk/dispatch.go` `handler.serve` | `TestT3b_NVMe_Flush_DispatchesToBackend` (`core/frontend/nvme/t3b_flush_test.go`); `TestSessionFlushLogsBackendReason` (`core/frontend/nvme/flush_error_log_test.go`); `TestDispatch_FlushSyncs`, `TestDispatch_BackendFailuresAreReportedNotAcknowledged` (`core/frontend/ublk/dispatch_test.go`) | — | ACTIVE | +| `INV-FE-LINEAGE-GATE-001` | Every `Read`, `Write` and `Sync` re-checks `{volume, replica, epoch, endpoint version}` and health against the current projection; any drift returns `ErrStalePrimary`. The volume-ID comparison is code reading: no cited test varies the volume ID. | M3 Primary → Supporting \| Excluded (I/O side) | `core/frontend/durable/storage_adapter.go` `gate`, `lineageCheck` | `TestT3a_StorageBackend_FenceCheck_Epoch`, `TestT3a_StorageBackend_FenceCheck_EV`, `TestT3a_StorageBackend_FenceCheck_Replica`, `TestT3a_StorageBackend_FenceCheck_Healthy` (`core/frontend/durable/storage_adapter_test.go`); `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`) | — | ACTIVE | + +Notes: + +- `INV-WAL-V3-LSN-ORDER-001`: the writer gate prevents an out-of-order physical chain whose dropped unacked middle record could later resurrect. Raw scanner/recovery integrity verdicts and the v3 ApplyEntry superseded-no-op/refusal policy are separate caller obligations. Legacy ApplyEntry and production v2 behavior are unchanged. +- `INV-WAL-V3-FLUSH-LIFETIME-001`: Capture recoverGen under store.mu with the dirty snapshot, before WAL materialization/extent I/O. Recheck the original generation under syncMu before either mapped or historical dark checkpoint publication. Under store.mu, recheck again before local tail progress and LSN-only compare/delete; Recover uses the same store lock at both boundaries. This adds no new lock or I/O under a publication lock. The pre-proof held control materializes unacknowledged A2, damages only that WAL suffix, Recover keeps W1, then reuses the same LBA/offset/LSN for acknowledged B2. Old publication must refuse, retain B, and a fresh retry must put B in the physical extent before crash-style reopen verifies exact bytes. + +- `INV-WAL-V3-MAP-PUBLISH-001`: The open/quiesced bind validates the selected and every valid fallback map root/page dependency before installing a proof domain, with a slot snapshot recheck after I/O. A corrupt fallback refuses binding even if the selected map is intact; validation writes no slots and preserves the prior domain on failure. This is a binding seam control, not automatic create/open or capture wiring. Real Recover START and END invalidation is wired and controlled on success and WAL-integrity failure, with a durable map manually bound to the actual store publisher. The dark map-requiring actual-store opener now loads its owned sidecar and validates both slots before workers start, binds a fresh proof domain, and Close releases the map. The explicit mapped creator persists an all-UNKNOWN initial map before publishing its first slot. Earlier unmapped row5 fixtures have a separately named test-only opt-out, not a production selector. Owned-map stores now prepare a typed snapshot/proof outside publication locks and publish real checkpoint coverage through publishMapV3 under syncMu. The existing map mutex reserves candidate generations; transaction failures latch the whole store before returning. Writes invalidate proofs before append and update per-chunk max LSN under store.mu, while Recover rebuilds that volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The dark actual chunk capture now also selects owned-map UNKNOWN/max-LSN candidates after checkpoint, samples chunk mutation tokens under its barrier, and clears UNKNOWN only after definite HEAD publication with unchanged tokens. Its resulting map snapshot is published through the same proof/coverage checks; failed or unresolved cuts clear nothing, and failed local map publication keeps disk UNKNOWN conservative. Replaying an already checkpoint-covered record does not invent a fresh logical map mutation. A mismatched chunk geometry is refused before remote contact. Eviction uses the same owned-map/WAL dirt predicate, so checkpointed data awaiting capture cannot be replaced by a fill from an older HEAD. Normal impl3 capture attachment/checkpoint/status no longer loads, saves, resets or requires the legacy bitmap; v2 retains it. A provided legacy object is ignored. The immutable per-open proof discriminator permits status alongside Close without reading its mutable cleanup pointer. Legacy BASE header mutations remain refused; the descriptor install protocol now uses the dark chunk transition drain and permits completed BASE attachment (INV-WAL-V3-CHUNK-BASE-001). A private test-only provider factory now drives the actual DurableProvider/StorageBackend create, recover, write, Sync, flusher, capture and local reopen paths on mapped v3 without a legacy bitmap. The cross-package constructor wrappers exist only under swblock_format_v3_test; the normal provider selector remains legacy, and a missing owned map refuses without caching a backend. SeedChunkFrontier now dispatches to the shared v3 checkpoint publisher (row9c), without waiting on the committer under store.mu. The real provider invalid-frontier control proves preparation failure claims no HEAD and leaves the backend nonoperational. Row12a now removes the provider refusal and exercises the actual mapped FreshFromHead restore through the row9 single-publisher seed: seed/rebase precedes takeover CAS, a committed claim with a lost response is resolved by exact reread, inherited LSNs are not reused, immutable chunks fill lazily, and later capture/local reopen preserve exact bytes. An invalid inherited frontier refuses without claiming HEAD. Production selection remains v2; the dark BASE caller and readonly/status controls have dedicated rows below; production activation remains separate. WAL tail reclamation is not yet wired. Existing dark lifecycle tests drive invalidation primitives; only the two explicitly named real-store controls exercise actual Recover, ; automatic checkpoint and tagged provider controls above separately cover those real callers. The owner serializes lifecycle transitions with publication using its existing lifecycle admission. No new lock or callback is taken under descMu; validation uses immutable candidate fields and atomic proof loads. + +- `INV-WAL-V3-MAP-BYTES-001`: row 6 prepares durable pinned tuples only. Root/merged-descriptor coverage, mutation proofs and real chunk/provider replacement are row 7; no serving or checkpoint advance is authorized by the codec/store. No sidecar page reclamation is implemented, so fallback or uncertain generations remain pinned conservatively. + +- `INV-WAL-CHECKPOINT-SNAPSHOT-001`: The SIGKILL test is Linux only. +- `INV-FE-FLUSH-SYNC-001`: NVMe/TCP also asserts failed-Sync status and reason logging through the actual session dispatch, and success produces no failure log. +- `INV-WAL-V3-RESET-001`: Format bump v3, plan row 8 (DESIGN 8.6). Dark: no production path calls the reset, and it must not be activated before the reset model (r4.5) passes. No v3 tail release exists yet, so the precondition is CheckpointLSN >= W rather than an empty retained range: retained old-incarnation bytes at or below the checkpoint are preserved in the extent. The map root is unchanged by a reset, so no map page is retired. +- `INV-WAL-V3-BASE-001`: Format bump v3, plan row 9a (DESIGN r17.3.1 sections 8.1, 8.2, 8.4, 8.5, 8.7). Dark: only tests reach it. Row 9b makes the seam `BaseInstallPreparer.BeginBaseInstall(baseLSN, installID) (InstallHandle, error)`: the dual-lane `Receiver` begins at SessionStart (BaseLSN = FromLSN, a fresh random ID) and its `RebuildSession` writes, applies and completes only through the handle, propagating the `MarkBaseComplete` error; stores without the seam keep their exact pre-seam behaviour through the lazy legacy handle (parallelwal's staging is now `BaseStager.BeginBaseStage`). Since row 10b the legacy single-lane caller (`core/transport/replica.go`) is on the handle too: the first admitted `MsgRebuildBlock` (or an empty rebuild's `MsgRebuildDone`) begins one install per connection at the lineage's frontier hint under a fresh random ID, blocks go through `WriteBase`, a different hint on the connection is refused, and done completes and then Syncs, closing the connection with no `MsgBarrierResp` when either fails; a reconnect is a superseding install under the coverage rule (tagged controls in `core/transport/replica_install_format_v3_test.go`). Until the chunk layer's side of the v3 install protocol lands (codex03), a v3 begin with an attached chunk layer is refused (`errV3NotYet`), writing nothing; since row 9c the v3 `SeedChunkFrontier` publishes CheckpointLSN = W = map coverage = lsn through the one checkpoint publication (`publishCheckpointV3`: data fsync, metadata and chunk barriers, owned-map candidate, the sole slot publisher under syncMu with the lifetime check), moves the volatile frontier only after it, publishes nothing on failure, and refuses local writes, an install, an attached layer or a store without an owned map; a HEAD restore onto a dark v3 store still refuses in the provider (`errV3RestoreNotYet`) until codex03's v3 FreshFromHead restore lands; since row 11a an installing physical reopen (an installing ID this open did not begin) keeps its recovered bounds (E, R, intact or damaged) without fencing, publishing or admitting; a same-open Recover of this open's live install records none, so its still-valid handle cannot append past a cached cut that a resume would fence from (codex01 row 11b P1); it republishes the live install's trusted records in the dirty map and keeps the volatile map coverage, or latches the store when the recovered cut is short of the live writer, and a covering superseding begin after it fences [E, floor + WALSize) and fsyncs before its two-slot installing publication, anchors at P = max(E, the persisted retainedHead) without lowering retainedHead, and restarts the writer at P (forward only); since row 11b the same-ID resume after a reopen (store level; no current caller resumes, both receivers begin fresh IDs) runs under `installMu` exclusive and appends nothing until the trusted-through-W check (intact suffix and E >= the persisted retainedHead), the fence of [E, floor + WALSize) with fsync and a retainedHead = E publication all held, refusing with `ErrInstallSuffixDamaged` and writing nothing otherwise; the writer continues at E and the recovered install-lane records are replayed. A begin while installed is refused until retirement (8.5 has no installed -> installing edge). +- `INV-WAL-V3-MIGRATE-001`: Format bump v3, plan rows 13a and 13b (DESIGN 10.1). Not yet in this row: the exclusive advisory lock that v3 open will share (precondition 1; it lands with the 12b open path), and raw v2 fixtures committed under testdata (today's controls build v2 volumes with the v2 code that row 14 deletes). The minimum migrated WAL size (64 KiB and two single-block records) is provisional. +- `INV-WAL-V3-W-001`, `INV-WAL-V3-FENCE-001`: Format bump v3, plan rows 5 and 5b (DESIGN r15 sections 6.1 to 6.6). Since 5b the v3 format runs inside the real `WALStore`, through the shared committer, dirty map, flusher and leaf. It is reachable only through `createWALStoreV3ForTest`/`openWALStoreV3ForTest`. Without the row-7 map candidate the v3 checkpoint and tail do not advance. They are STUBs until activation (row 12b). The test "crash" closes the file without further writes, so the slot-before-records reordering that mode C's lagged W guards against is covered by the composed model (claude05), not by these tests. Installing recovery is row 11. +- `INV-WAL-V3-PUBLISH-001`: Format bump v3, plan row 3 (DESIGN r15 sections 4, 5 and 5.1). It is a STUB until the v3 store is wired in (rows 4 and 5) and activated (row 12b). The v2 checkpoint path (`persistCheckpointReleasing`) is unchanged and is retired in row 14a. The map coverage predicates against the root are added by row 7, and the conditions on BASE edges by rows 9 to 11. +- `INV-WAL-V3-DESCRIPTOR-001`: Format bump v3, plan row 1 (DESIGN r15 section 2). It is a STUB until the activation commit (plan row 12b): no production open or create path reaches the v3 codec before then. The map-dependency checks (root and pages present and hash-valid) are added by plan row 7. The tests decode vectors from an independent generator (`core/storage/testdata/format_v3/slot/gen_slot_vectors.py`). + +### B.2 Core: authority and epochs + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-EPOCH-MINT-001` | Only the publisher mints epochs; a reassignment takes the per-volume maximum epoch plus one, also after a restart. | M2 Bound → Reassigned | `core/authority/authority.go` `applyWithWorkspaceMove`, `maxPublishedEpochForVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestDurableAuthority_PublisherAdvancesFromReloaded` (`core/authority/authority_restart_test.go`); `TestG9F2_AssignmentRequestShapeHasNoEpochOrEndpointVersion` (`core/host/master/authority_request_bridge_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-PERSIST-BEFORE-PUBLISH-001` | With an authority store configured, an assignment is written to the store before memory or any subscriber sees it. A failed write does not publish the proposed assignment, but its durable outcome may be unknown (the write may have landed); for a workspace volume the failure latches uncertainty (`INV-AUTH-UNCERTAIN-001`). The cited test covers the non-workspace in-memory rollback. | M2 every transition | `core/authority/authority.go` `applyWithWorkspaceMove` | `TestDurableAuthority_PutFailureRollsBackInMemoryState` (`core/authority/authority_restart_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-AUTH-MOVE-JOURNAL-001` | A workspace move's epoch is issued only after its journal record is durable, and one move request id gets exactly one epoch, also across restarts. | M2 MoveReserved → MoveIssued | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `MoveWorkspace`, `sameWorkspaceRequest` | `TestWorkspaceMoveCannotIssueEpochWithoutJournal`, `TestWorkspaceCrashAfterJournalBeforeEpochResumesSameGrant` (`core/authority/workspace_test.go`) | `ControlPlane` `Idempotent`, `JournalComplete` | ACTIVE | +| `INV-AUTH-UNCERTAIN-001` | After a failed authority write for a workspace volume, the publisher refuses further authority changes for that volume until it restarts and reloads. A failed lease extension is such a write. Renewals that would issue a new or extended (non-revoking) grant for the volume are refused too: the renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`) instead of meeting it in `persistWorkspaceLocked`. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended, as before. | M2 any → Uncertain | `core/authority/authority.go` `applyWithWorkspaceMove`; `core/authority/workspace.go` `persistWorkspaceLocked`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`) | `ControlPlane` `UniqueEpoch` | ACTIVE | +| `INV-LEASE-VIEW-001` | Whenever the publisher lock is released, each volume's lease view (the renewal path's only input) equals derive(the published authority line, workspace state, uncertainty, store presence). Writers refresh it under the publisher lock then the lease lock at every change of those inputs; the deadline and the extender flag are owned by the view. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`; `core/authority/authority.go` `applyWithWorkspaceMove`, `reloadFromStore`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseViewMatchesDeriveAfterEveryWriter`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch: the persisted `Lease.ExpiresAtNS` ≥ the published horizon ≥ every grant issued since the last reload, and the published horizon only grows. A move issue that clears the lease is the ordered successor (a clean handoff, or a forced move past the barrier) and leaves this scope; if that issued successor is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further old-epoch grant is issued, so no disk expiry is claimed for it. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-WS-RENEW-NONBLOCKING-001` | A renewal of an established lease takes only the leaf lease lock and lock-free lifecycle snapshots: it never waits on the publisher lock, an authority store write or a lifecycle store mutex. Only the first grant of a lease writes synchronously. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/host/master/workspace_service.go` `workspaceVolumeForRenewal` | `TestWorkspaceRenewalDoesNotWaitForSlowStore`, `TestWorkspaceConcurrentRenewalsDoNotSerializeOnStore`, `TestWorkspaceRenewalDoesNotWaitForUnrelatedHeldWrite` (`core/authority/workspace_renewal_slowstore_test.go`); `TestWorkspaceExtenderAdmittedBeforeCloseDoesNotWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore`, `TestWorkspaceRenewalRPCDoesNotWaitForHeldReservationWrite` (`core/host/master/workspace_renewal_slowstore_test.go`) | — | ACTIVE | +| `INV-LIFECYCLE-SNAPSHOT-001` | The Volumes and deletion-reservation snapshots read by the renewal path equal the store records after every change of the records, including load, delete and a protective reservation kept in memory on an unknown write outcome; a published snapshot is never mutated. | M2 Bound → Deleting (renewal reads) | `core/lifecycle/store.go` `publishLocked`, `GetVolumeSnapshot`; `core/lifecycle/deletion_reservations.go` `publishLocked`, `ReservedSnapshot` | `TestDeletionReservationSnapshotFollowsRecords`, `TestFileStoreSnapshotFollowsRecords`, `TestLifecycleSnapshotReadsDoNotTakeStoreMutex`, `TestLifecycleSnapshotConcurrentWriters` (`core/lifecycle/renewal_snapshot_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | +| `INV-VOL-ID-NO-REUSE-001` | A deleted volume id is never created or attached again. | M2 Deleting; M6 purging → deleted | `core/host/master/services.go` `MarkVolumeDeleting`; `core/frontend/chunkstore/catalog.go` `EnsureVolume` | `TestMarkVolumeDeleting_ReservesUnknownIdsAndSurvivesDeleteAndRestart` (`core/host/master/volume_deleting_test.go`); `TestCatalog_DeleteVolumeTombstonesAndRefusesReuse` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `NoIdReuse` | ACTIVE | + +Notes: + +- `INV-AUTH-UNCERTAIN-001`: The cited test asserts the refusal after an unknown-outcome lease extension (rename landed, directory sync failed): the next renewal, a revocation and an endpoint change are all refused. The TLA+ configuration `S5_red_noUncertain` violates `UniqueEpoch` without it. +- `INV-WS-LEASE-HORIZON-001`: The forced-barrier argument (a renewal that reads its clock after the barrier has read the deadline is refused) assumes nondecreasing master time. That is an assumption of the current `WorkspaceTakeover` model, whose `Tick` and `SlowTick` actions only advance `now`; it is not a consequence of `time.Now` carrying a monotonic reading, because persisted `UnixNano` deadlines are compared as wall-clock values. The existing deadline check stays alongside the horizon. The model still renews with `exp = deadline = now + TTL`; the horizon/grant split is a pending specification update (Part C rule 2). +- `INV-WS-RENEW-NONBLOCKING-001`: The cited tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace. + +### B.3 Core: replication and replica roles + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-REPL-REBUILD-PORT-FENCE-001` | The dual-lane rebuild port applies the replica listener's admission rules: no frame on a primary, below the epoch floor, or before the role is known. | M3 listener admission | `core/transport/replica.go` `EnterDualLane` | `TestDualLaneRebuildPort_RefusesStaleSenderAfterFence`, `TestDualLaneRebuildPort_RefusesBeforeRoleKnown` (`core/transport/g6_dual_lane_fence_test.go`) | — | ACTIVE | +| `INV-REPL-APPLY-FAIL-001` | A failed `ApplyEntry` on a replica closes the connection, so no barrier acknowledges past the gap. | M3 Healthy → Degraded | `core/transport/replica.go` `handleConn` | `TestReplicaApplyFailureStopsBarrierAtTheGap` (`core/transport/replica_apply_error_test.go`); `TestReplicaApplyFailure_PrimaryDegradesRecoversAndReplaysFailedLSN` (`core/replication/component/replica_apply_failure_recovery_test.go`) | — | ACTIVE | +| `INV-REPL-INGRESS-SLOTS-001` | Replication listeners are open only while the assignment has replica slots. | M3 role → listener lifecycle | `cmd/blockvolume/replication_ingress.go` `roleLocked` | `TestBinaryReplicationIngressFollowsAssignedSlots` (`cmd/blockvolume/replication_ingress_binary_test.go`) | — | ACTIVE | +| `INV-REPL-CATCHUP-REBUILD-001` | The engine chooses catch-up when the gap is still in the primary's WAL and rebuild when it is not. | M3 Degraded → CatchingUp \| NeedsRebuild | `core/engine/apply.go` `decide` | `TestV3_Decision_CatchUp_GapWithinWAL`, `TestV3_Decision_Rebuild_GapBeyondWAL` (`core/engine/apply_test.go`) | — | ACTIVE | +| `INV-REPL-PEER-TRANSITIONS-001` | `ReplicaPeer.SetState` and `ReplicaPeer.Invalidate` apply only the transitions in the peer table; `NeedsRebuild` has no successor through either. | M3 peer state | `core/replication/peer.go` `ReplicaPeer.SetState`, `ReplicaPeer.Invalidate`, `replicaStateTransitionAllowed` | `TestReplicaStateTransition_AllowedSet`, `TestReplicaStateTransition_RejectedSet`, `TestReplicaStateTransition_NeedsRebuildIsTerminalInT4c` (`core/replication/peer_state_machine_test.go`); `TestReplicaPeer_InvalidatePreservesNeedsRebuildTerminalState` (`core/replication/invalidate_terminal_regression_test.go`); `TestReplicaPeer_InvalidateNonTerminalStatesBecomeDegraded`, `TestReplicaPeer_InvalidateOnNeedsRebuildStillLogsReason` (`core/replication/invalidate_transition_test.go`) | — | ACTIVE | +| `INV-REPL-DURABILITY-MODE-001` | Under `sync_all` a replicated `Sync` fails if any replica barrier fails; under `sync_quorum` it fails unless a majority of nodes, the primary included, are durable. | M3 barrier evaluation | `core/replication/durability.go` `EvaluateBarrierAcks` | `TestDurabilityCoordinator_Quorum_RF3_OneReplicaFailed`, `TestDurabilityCoordinator_Quorum_RF3_BothReplicasFailed`, `TestDurabilityCoordinator_SyncAll_AnyFailure_Fails` (`core/replication/durability_test.go`) | — | ACTIVE | +| `INV-REPL-PROMOTION-READY-001` | A replica reports `promotion_ready` only if it is a member, reachable, caught up, fenced at the current epoch, and has delivered its post-rebuild durable acknowledgement. | M3 Supporting → promotion candidate | `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestBuildPromotionReadyFact_RefusesPendingFence`, `TestBuildPromotionReadyFact_RefusesPostCloseAckGap`, `TestBuildPromotionReadyFact_RefusesNotCaughtUp` (`core/engine/promotion_ready_test.go`) | `WALReplica` `I3`; `ReplicationFailover` `AckedSurvive` | ACTIVE | +| `INV-ROLE-STALE-REPLAY-001` | A role call below the host's current desired epoch is refused and cannot clear a newer role-admission failure. | M3 role admission | `core/host/volume/host.go` `fenceSelfWithPeers`, `latchRoleAdmission` | `TestG1_StaleReplayDoesNotClearANewerAdmissionFailure`, `TestG1_StaleSupportingReplayDoesNotClearTheLatch` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | +| `INV-ROLE-READINESS-BLOCK-001` | While local recovery blocks readiness, `applyFact` admits neither a primary nor a supporting role, and replays the stored fact once readiness clears. | M3 Unassigned → Primary \| Supporting (guard) | `core/host/volume/host.go` `applyFact`, `replayLocalReadinessFactIfReady` | `TestHost_ApplyFact_Self_LocalReadinessBlocked_SkipsReplicationAndAdapter`, `TestHost_ApplyFact_SupportingReplica_LocalReadinessBlocked_SkipsAdapter`, `TestHost_ApplyFact_Self_ReplaysAfterLocalReadinessClearsWithReplicationFirst` (`core/host/volume/apply_fact_test.go`) | — | ACTIVE | +| `INV-ROLE-SUPERSEDED-001` | A fact naming another replica as primary, with this replica not among its peers, never reaches this host's adapter or replication, and is recorded as the other line. | M3 Primary \| Supporting → Excluded | `core/host/volume/host.go` `applyFact`, `recordOtherLine` | `TestHost_ApplyFact_Supersede_NeverCallsAdapterOrReplication` (`core/host/volume/apply_fact_test.go`); `TestHost_BuildReport_SupersededReplicaNotReadyForPrimary` (`core/host/volume/frontend_targets_test.go`) | — | ACTIVE | + +Notes: + +- `INV-REPL-INGRESS-SLOTS-001`: Binary test: builds and runs the real `blockvolume`; build tag `subprocess`, not on Windows. +- `INV-REPL-PEER-TRANSITIONS-001`: `ReplicaPeer.Invalidate` uses the same gate as `SetState`; from `NeedsRebuild` it keeps the state and still logs the reason (see Part A, M3; [#182](https://github.com/seaweedfs/seaweed-block/issues/182)). + +### B.4 Workspace: HEAD holder, lease and takeover + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-WS-HEAD-CAS-001` | Every HEAD publish is a conditional update on `{gen, epoch}`, so only one holder can publish each HEAD generation; a holder that sees a superseding HEAD fences itself. | M4 Holder → Fenced | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `supersededBy`, `captureLocked` | `TestChunkRemote_TakeoverRefusesOldHolder` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C6_FencedOnTakeover` (`core/storage/chunk_layer_contract_test.go`); `TestIntegration_ConcurrentHEADCASRealFiler` (`core/frontend/chunkstore/concurrent_cas_integration_test.go`) | `WorkspaceTakeover` `NoOldCasAfterTakeover` | ACTIVE | +| `INV-WS-HEAD-MONOTONE-001` | HEAD epoch and `RemoteLSN` never decrease. | M4, M5 CAS | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkRemote_EpochNeverLowers` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkCut_RemoteLSNNeverDecreases` (`core/storage/chunk_layer_lsn_order_test.go`); `TestHEADRefusesLSNRegressionAcrossMove` (`core/frontend/chunkstore/restore_lsn_test.go`) | `WorkspaceTakeover` `HeadMonotone` | ACTIVE | +| `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-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`) | `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-CLEAN-MOVE-001` | A clean move is granted only with a detached HEAD from the expected holder and a matching revocation acknowledgement at the current epoch. | M2 lease: Acked → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `AckWorkspaceRevocation` | `TestWorkspaceCleanMoveNeedsDetachedHEADAndRevocationAck` (`core/authority/workspace_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE | +| `INV-WS-FORCED-MOVE-001` | A forced move is granted only after the persisted lease horizon (at least every grant, `INV-WS-LEASE-HORIZON-001`) and the granted or restart deadline, each plus the clock-skew bound; the lease reported to the host is the grant, never the horizon, and excludes half of the bound. | M2 lease: Expired → Moved | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`; `core/authority/workspace_lease_view.go` `WorkspaceLeaseReply`; `core/host/master/workspace_service.go` `leaseFact` | `TestWorkspaceSkewSeparatesOldServingFromForcedGrant` (`core/host/master/workspace_skew_test.go`); `TestWorkspaceClockSkewPersistsAndProtectsRestart` (`core/authority/workspace_skew_test.go`); `TestWorkspaceForcedMoveRequiresExplicitForceAndLeaseExpiry` (`core/authority/workspace_test.go`); `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceRenewalRPCDuringHeldSameVolumeReservation` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE | + +Notes: + +- `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. + +### B.5 Workspace: the cut pipeline + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `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-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECONCILING-001` | While the dirty set is being reconciled, no cut or `MakeRemoteDurable` moves HEAD or makes a remote call. | M5 Admit → Refused (reconciling) | `core/storage/chunk_layer.go` `captureLocked`, `startReconcile` | `TestChunkReconcile_NoHeadMovesWhileReconciling` (`core/storage/chunk_layer_reconcile_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-STAGED-REUSE-001` | A chunk pre-copied outside the barrier is used only if no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window (legacy fixtures retain the full-copy barrier). | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied`, `TestChunkPrecopy_RecoverAfterStagingInvalidatesTheStage` (`core/storage/chunk_layer_precopy_test.go`) | `CutPipeline` `HeadImage` | ACTIVE | +| `INV-CUT-BITMAP-001` | The dirty bitmap never under-reports: it is durable before the checkpoint passes its WAL entries, and it is reset only after a successful CAS, keeping chunks dirtied after the cut. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/chunk_layer.go` `BeforeCheckpointAdvance`, `finishCut` | `TestChunkLayer_C11_BitmapPersistedBeforeWALRecycle`, `TestChunkLayer_C11_RolloverKeepsPostCutDirt` (`core/storage/chunk_layer_c11_test.go`) | `CutCapture` `HeadImage` | ACTIVE | +| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck; legacy fixtures keep the shared/full-copy barrier. No recovered record above H can enter a HEAD labelled H. | M5 Quiesce; M1 Recovering | `core/storage/walstore.go` `WALStore.Recover`; `chunk_cut_cow.go` `holdChunkDestructive` | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`; `TestChunkCut_RecoverWaitsForTheCaptureBarrier` (`core/storage/chunk_layer_precopy_test.go`) | — | ACTIVE | +| `INV-CUT-INTENT-FIRST-001` | Before the first upload of a cut, an intent naming every new key is durable, and it is removed only after the CAS outcome is known. | M5 Intent → Upload → CAS | `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkIntent_WrittenBeforeFirstUploadAndDeletedAfterCAS` (`core/storage/chunk_layer_intent_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE | +| `INV-CUT-SEGMENT-REUSE-001` | A cut rewrites only manifest segments whose chunk references changed, and an uploaded but unpublished segment leaves the published root unchanged. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` (`core/frontend/chunkstore/manifest_test.go`) | `CutPipeline` `SegConsistent` | ACTIVE | +| `INV-CUT-READMISS-001` | A block fetched from HEAD after a move is installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write. | M4 Holder (lazy restore) | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock`; `core/storage/walstore.go` `readFromExtent` | `TestChunkLayer_WALOnlyOverlapReadNeverReturnsUntouchedZero` (`core/storage/chunk_layer_races_test.go`); `TestWALStore_PostReadMissRechecksWALFormat` (`core/storage/walstore_read_miss_v3_test.go`; real-store v2/v3 dispatch, v3 remains dark) | — | ACTIVE | + +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). + +### B.6 Workspace: chunk lifecycle, GC and delete + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-CHUNK-WRITE-ONCE-001` | Chunk and segment keys are write-once: a key that exists or once existed is refused, and a volume writes only its own keys. | M6 key: Bound | `core/frontend/chunkstore/chunk_remote.go` `putObject` | `TestChunkRemote_KeysAreWriteOnce` (`core/frontend/chunkstore/chunk_remote_test.go`); `TestChunkLayer_C5_ChunksAreImmutable` (`core/storage/chunk_layer_contract_test.go`) | — | ACTIVE | +| `INV-GC-REACHABLE-001` | GC never deletes a chunk reachable from a HEAD, a snapshot, an attempt or a live intent, and deletes a binding only after two marks at least one grace period apart. | M6 key: Bound → Tombstoned | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_UnreachableRequiresTwoMarksAndUploadAge`, `TestGC_StalledCutRemainsReadableAfterTwoMarks`, `TestGC_SnapshotAndQualifiedForkAreRoots` (`core/frontend/chunkstore/gc_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `RetentionGCTiming` `NoLiveDelete` | ACTIVE | +| `INV-GC-INTENT-EXPIRY-001` | A capture intent expires only when it is older than the TTL, blockmaster has issued a higher epoch, and remote HEAD has moved to a higher epoch. | M6 intent: Live → Expired | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestGC_IntentExpiryNeedsTTLAuthorityAndRemoteFence` (`core/frontend/chunkstore/gc_test.go`) | `WorkspaceTakeover` `NoLiveIntentExpired`, `GCSafe` | ACTIVE | +| `INV-GC-UNREADABLE-SEGMENT-001` | An unreadable published segment aborts the whole GC pass before any deletion. | M6 GC mark | `core/frontend/chunkstore/gc.go` `Collector.run` | `TestManifest_UnreadablePublishedSegmentRefusesWholeGC` (`core/frontend/chunkstore/manifest_test.go`) | — | ACTIVE | +| `INV-GC-GRACE-DEADLINE-001` | A GC collector cannot be built unless its grace period exceeds the catalog operation deadline. | M6 GC configuration | `core/frontend/chunkstore/gc.go` `NewCollector` | — | `RetentionGCTiming` `NoLiveDelete` | STUB | +| `INV-SNAP-EXPLICIT-DELETE-001` | A published snapshot is removed only by `DeleteSnapshot` or retention for its own attempt, and never while a fork claim on it is live. | M6 snapshot: Published → Deleting | `core/frontend/chunkstore/catalog.go` `DeleteSnapshot`; `core/frontend/chunkstore/retention.go` `markDeleting` | `TestCatalog_DeleteMarksThenIdempotent` (`core/frontend/chunkstore/catalog_test.go`); `TestCatalog_ClaimBetweenCheckAndMarkWins` (`core/frontend/chunkstore/retention_review_test.go`) | `ChunkLifecycleFixed` `SnapOnlyExplicitDelete` | ACTIVE | +| `INV-VOLDEL-COMMIT-001` | A volume delete commits only when no snapshot name record exists, and after its commit point no concurrent delete can roll it back. | M6 HEAD: deleting → purging | `core/frontend/chunkstore/volume_delete.go` `DeleteVolume`, `snapshotsBlock`, `commitHeadPurging` | `TestCatalog_DeleteVolumeRefusesWhileSnapshotsExist`, `TestCatalog_ConcurrentDeleteCannotRollBackACommittedOne` (`core/frontend/chunkstore/volume_delete_test.go`) | `ChunkLifecycleFixed` `CommitClean` | ACTIVE | +| `INV-VOLDEL-HELD-HEAD-001` | A delete marks HEAD `deleting` only while no holder holds it; an attach that reaches HEAD first wins. | M6 HEAD: detached → deleting | `core/frontend/chunkstore/volume_delete.go` `markHeadDeleting`, `headHeld` | `TestCatalog_DeleteVolumeLosesToAnAttachAtTheMark` (`core/frontend/chunkstore/volume_delete_test.go`) | — | ACTIVE | +| `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 | + +Notes: + +- `INV-GC-GRACE-DEADLINE-001`: The check is in `NewCollector`; no Go test constructs a collector with a too-short grace. + +### B.7 Rows kept from the internal ledger: Kubernetes line and replica fencing + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-AUTH-ONE-PRIMARY-001` | A volume's authority line names one replica at its highest epoch, a reassignment supersedes the previous primary, and observed dual primaries make the volume `invalid`. A genesis `Bind` is refused once any slot of the volume holds a line. | M2 Unbound → Bound, Bound → Reassigned; K8s readiness | `core/authority/authority.go` `applyWithWorkspaceMove` (`IntentBind`, `boundReplicaForVolume`); `core/authority/policy.go` `VolumeAuthorityLine`; `core/authority/controller.go` `decideVolume`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG8_0_Publisher_ReassignAdvancesPerVolumeEpochAcrossReplicaSlots` (`core/authority/g8_0_authority_failover_test.go`); `TestPublisher_RunRejectsSecondSlotGenesisBind` (`core/authority/bind_volume_regression_test.go`); `TestPublisher_BindSecondSlotOfBoundVolumeRejected`, `TestPublisher_BindOtherVolumeUnaffected`, `TestPublisher_ReassignToOtherSlotStillAllowedThenBindRejected`, `TestPublisher_BindAfterRestartRejectedForAnySlot` (`core/authority/bind_volume_genesis_test.go`); `TestManagedVolumeProjection_InvalidDualPrimaryBeatsReady` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-STALE-PRIMARY-001` | Once a primary has observed a newer line for another replica, its backend refuses `Read`, `Write` and `Sync`, and replicas refuse its frames below their epoch floor. | M3 Primary → Supporting \| Excluded | `core/host/volume/projection_bridge.go` `projectionWithSupersede`; `core/frontend/durable/storage_adapter.go` `lineageCheck`; `core/transport/replica.go` `admitMutation` | `TestG8A_SupersedeFact_FencesOldPrimaryDurableBackend` (`core/host/volume/g8a_stale_fence_test.go`); `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`) | `ReplicationFailover` `NoStaleAck` | ACTIVE | +| `INV-PROMOTE-FRONTIER-001` | The RF=3 promotion gate promotes only a probed candidate that covers the required acknowledgement frontier, and blocks promotion without a fresh probe. With a known frontier the candidate's durable LSN must be at least the required LSN. With an unknown frontier under `sync_quorum` or `sync_all`, the highest-durable ready candidate is promoted only when at least P-K+1 distinct peers are probed ready and fresh in the same tick (K from `waitForSyncAcks`; RF=3: both peers under `sync_quorum`, one under `sync_all`); otherwise nothing is promoted. An unknown frontier is never read as zero; `best_effort` is unchanged. | M3 Supporting → Primary (RF=3 gate) | `core/host/master/product_loop.go` `applyPromotionEvidenceGate`, `promotionAllowedReplicas`, `unknownFrontierSurvivorsNeeded`, `freshPromotionPeers`; `core/host/master/promotion_probe.go` (`SyncAckKnown`); `core/engine/promotion_ready.go` `BuildPromotionReadyFact` | `TestMountedFailover_ProductLoopRF3PromotesCandidateCoveringSyncAckProbe`, `TestMountedFailover_ProductLoopRF3BlocksFailoverWithoutFreshPromotionProbe`, `TestMountedFailover_ProductLoopRF3UnknownRequiredLSNFallsBackToHighestDurableLSN` (`core/host/master/product_loop_test.go`); `TestProductLoop_MissingRequiredFrontierRefusesRF3Promotion` (`core/host/master/promotion_missing_frontier_regression_test.go`); `TestUnknownFrontierSurvivorsNeeded`, `TestPromotionAllowedReplicas_RequiredFrontierCoverage`, `TestWorkloadPlanProvider_RequiredFrontierKnownness`, `TestFreshPromotionPeers_UsesObservationFreshness`, `TestProductLoop_UnknownFrontierSurvivorReadyLastTickMissingNowRefused`, `TestMountedFailover_ProductLoopRF2IgnoresRF3FrontierGate` (`core/host/master/promotion_frontier_coverage_test.go`) | — | ACTIVE | +| `INV-CSI-CONSUMES-AUTHORITY-001` | CSI never imports authority code or builds assignment facts; it takes the publish target from blockmaster and refreshes it before a stage, and blockmaster mints the IDs of the events CSI reports. | M2 (read side) | `core/csi/master_backend.go` `LookupPublishTarget`; `core/csi/node.go` `refreshPublishContext`; `core/host/master/observation_service.go` `ReportClusterEvent` | `TestG15a_CSI_DoesNotImportAuthorityOrConstructAssignmentFacts` (`core/csi/boundary_guard_test.go`); `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestObservationService_ReportClusterEventAppearsInVolumeTimeline` (`core/host/master/observation_service_test.go`) | — | ACTIVE | +| `INV-K8S-NONLOOPBACK-001` | Generated multi-node Helm values enable external iSCSI, external status and loopback rejection; with rejection enabled CSI never publishes a loopback target and fails closed when only loopback targets exist. | M2 (read side) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`; `core/csi/master_backend.go` `rejectFrontendAddr` | `TestOpsGenerateHelmValuesMultiNodeExternalISCSI` (`cmd/sw-block/main_test.go`); `TestNodeLoss_ControlStatusLookup_RejectsLoopbackPublishTargetsWhenEnabled`, `TestNodeLoss_ControlStatusLookup_FailClosedWhenOnlyLoopbackTargets` (`core/csi/master_backend_test.go`) | — | ACTIVE | +| `INV-OBS-PRODUCT-EVENTS-001` | blockmaster records placement-verified, promotion-candidate-evaluation and authority-published events, and the CSI node reports `csi_reattach_observed` after a successful stage. | M3 promotion decision (observation) | `core/host/master/product_loop.go` `recordPlacementVerifiedEvents`, `recordPromotionEvaluationEvents`, `recordAuthorityPublishedEvent` | `TestMasterTimeline_RecordsPlacementVerified`, `TestMasterTimeline_RecordsPromotionCandidateEvaluation`, `TestMasterTimeline_RecordsAuthorityPublishedAfterMint` (`core/host/master/event_ring_test.go`); `TestNodeStage_ReportsCSIReattachObservedAfterSuccessfulStage` (`core/csi/node_test.go`) | — | ACTIVE | +| `INV-HELM-RF-NODECOUNT-001` | Generated Helm values fail closed when the requested replication factor exceeds the selected Ready schedulable node count. | M3 (configuration) | `cmd/sw-block/main.go` `runOpsGenerateHelmValues`, `selectHelmValuesNodes` | `TestOpsGenerateHelmValuesRejectsRFAboveSelectedNodes` (`cmd/sw-block/main_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-TRANSPARENT-001` | The read model reports transparent host-path recovery only with a multipathed, Active/Optimized, stale-fenced path, writer and reader checks, and the same pod UID. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume`, `deriveManagedVolumeStates` | `TestManagedVolumeProjection_TransparentISCSIALUARecovered`, `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-K8S-REATTACH-001` | A CSI re-stage after failover uses the fresh publish target, and the read model reports recovery by reattach only with CSI reattach observed and a verified reader. | K8s readiness model | `core/csi/node.go` `refreshPublishContext`; `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestG15e_CSIReattachUsesFreshPublishTargetAfterUnstage` (`core/csi/node_test.go`); `TestManagedVolumeProjection_NodeLossReattachRecovered` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-MANAGED-VOLUME-READMODEL-001` | Volume explanations in the observation report and explain output are rendered from the `ManagedVolume` projection. | K8s readiness model | `core/ops/managed_volume_model.go` `ProjectManagedVolume` | `TestObservationExplain_IncludesManagedVolumeProjectionAndDryRunActions`, `TestObservationReportSummary_IncludesManagedVolumeStatus` (`core/ops/observation_report_test.go`); `TestProjectManagedVolumeFromEvidence_DualPrimaryInvalid` (`core/ops/managed_volume_evidence_test.go`) | — | ACTIVE | +| `INV-CONTROL-CONTEXT-001` | Cross-layer explanations replayed from a bundle are derived from recorded facts and events. Superseded in scope by `INV-MANAGED-VOLUME-READMODEL-001`; kept for continuity. | K8s readiness model | `core/ops/observation_bundle.go` `BuildObservationFromBundle` | `TestObservationBundle_RendersNodeLossRecoveryStory`, `TestObservationBundle_ManagedVolumeUsesPrimaryFailureArtifactHints` (`core/ops/observation_bundle_test.go`) | — | ACTIVE | +| `INV-K8S-ADAPTOR-FACTS-001` | PVC, pod, node and CSI conditions enter the read model as typed facts and map to distinct blocked reasons before any recovery status is derived. | K8s readiness model | `core/ops/managed_volume_model.go` `classifyManagedVolume` | `TestManagedVolumeProjection_PVCPendingBlocked`, `TestManagedVolumeProjection_WriterFailedMountBlocked`, `TestManagedVolumeProjection_CSINodeImagePullBlocked`, `TestManagedVolumeProjection_LoopbackCrossNodeBlocked` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-HOSTPATH-FACTS-001` | The read model keeps path facts separate from the recovery claim: missing multipath blocks the transparent claim, and an NVMe ANA seam alone does not infer transparent recovery. | K8s readiness model | `core/ops/managed_volume_model.go` `deriveManagedVolumeStates`, `hasTransparentHostPathEvidence` | `TestManagedVolumeProjection_MissingMultipathBlocksTransparentClaim`, `TestManagedVolumeProjection_NVMeANASeamDoesNotInferTransparentRecovery` (`core/ops/managed_volume_model_test.go`) | — | ACTIVE | +| `INV-FENCE-SELF-ON-PROMOTE-001` | A primary at epoch e applies no inbound replication traffic (ship, recovery lane start, rebuild), and none below e; it still answers probes, and its epoch floor never goes down when it later supports another primary (fencing gap G2). | M3 Supporting → Primary | `core/transport/replica.go` `FenceAsPrimary`, `acceptMutationLineage`; `core/host/volume/host.go` `fenceSelfWithPeers` | `TestG2_PromotedHostRefusesShipFromDeposedPrimary` (`core/host/volume/g2_self_fence_test.go`); `TestG2_PrimaryListenerRefusesMutationsButAnswersProbes`, `TestG2_FloorStaysWhenThePrimaryLaterSupportsAnother` (`core/transport/g2_self_fence_test.go`) | `ReplicationFailover` `AckedSurvive`, `NoStaleAck` | ACTIVE | +| `INV-FENCE-FLOOR-DURABLE-001` | A replica never accepts mutating traffic below the highest epoch it has acknowledged or taken a role at, across restarts, and accepts none before its assignment is known; a role call whose floor cannot be made durable is not adopted and keeps the frontend unhealthy (fencing gap G1). | M3 Unassigned → Primary \| Supporting | `core/transport/replica.go` `raiseFloor`, `admitMutation`, `AdmitAsReplica`; `core/host/volume/host.go` `latchRoleAdmission` | `TestG1_RestartedReplicaRefusesShipBelowItsAcknowledgedEpoch`, `TestG1_ConcurrentRaisesNeverLowerTheRecord`, `TestG1_RoleCallsPersistBeforeReturning` (`core/transport/g1_durable_floor_test.go`); `TestG1_FailedRoleAdmissionStopsAPreviouslyHealthyFrontend` (`core/host/volume/g1_admission_latch_test.go`) | — | ACTIVE | + +Notes: + +- `INV-AUTH-ONE-PRIMARY-001`: Narrowed. The lab evidence field `post_failure_primary_count=1` is not read by any Go test. `IntentBind` is checked per volume: the Publisher refuses a genesis `Bind` (`ErrBindAlreadyBound`) once any slot of the volume holds a present line, also after a restart, when only the current slot is reloaded; `decideVolume` also binds only when the volume has no line ([#183](https://github.com/seaweedfs/seaweed-block/issues/183)). +- `INV-FENCE-STALE-PRIMARY-001`: Narrowed. A primary cut off from blockmaster that has not seen the newer line keeps admitting I/O, and under `best_effort` its local `fsync` still acknowledges (no primary lease on the Kubernetes path; see the Kubernetes known gaps). The lab counter `old_primary_stale_io_success_count=0` is lab evidence only. +- `INV-PROMOTE-FRONTIER-001`: Fixed for [#181](https://github.com/seaweedfs/seaweed-block/issues/181). `cmd/blockmaster` does not set `RequiredLSNByVolume`, so in a deployment the frontier is unknown and the survivor rule applies (an RF=3 `sync_quorum` volume with one peer unseen is not promoted automatically). Limits: blockmaster has no source for the required frontier ([#192](https://github.com/seaweedfs/seaweed-block/issues/192)); the rule covers only the acknowledgements represented by the frontiers sampled in one tick, because those probes are snapshots, not a fence, and a deposed primary can still acknowledge after a sample (no primary lease, [#195](https://github.com/seaweedfs/seaweed-block/issues/195)). See [Kubernetes design §6 and §12](kubernetes-block-design.md). RF=2 relies on `INV-REPL-PROMOTION-READY-001`. +- `INV-K8S-NONLOOPBACK-001`: Rejection is opt-in: the chart default for `network.rejectLoopbackPublishTargets` is false; the generator sets it for multi-node values. +- `INV-OBS-PRODUCT-EVENTS-001`: Each event type has a unit test; all four together in one node-loss run is lab evidence only. +- `INV-HOSTPATH-TRANSPARENT-001`: Narrowed to the classifier. It does not compare the host path target with the promoted target, and only the missing-multipath case has a negative test. The mounted-failover run is lab evidence. +- `INV-K8S-REATTACH-001`: The full node-loss run through pod recreate is lab evidence; the classifier does not check that the re-stage target equals the promoted frontend. +- `INV-MANAGED-VOLUME-READMODEL-001`: Partial. No guard test shows that other surfaces never build their own status, and `core/ops/observation_bundle.go` `applyPrimaryFailureSummary` sets a recovered status from summary keys without the classifier. +- `INV-K8S-ADAPTOR-FACTS-001`: Narrowed. The fact metadata the internal row names (source, time, generation, confidence) is neither filled in nor read by the classifier. +- `INV-HOSTPATH-FACTS-001`: Narrowed. There is no session-reachability fact, the classifier does not read the ALUA state, and the artifact path derives the multipath and Active/Optimized facts from one `transparent_failover_claimed` hint. + +**Not in the ledger.** Known gaps where the code does not yet hold the property are tracked as known issues, not as rows: the [core known issues](block-design.md#24-known-issues-and-work-in-progress), the [agent workspace known gaps](agent-workspace-design.md#14-known-gaps) and the [Kubernetes known gaps](kubernetes-block-design.md#12-known-gaps). A fix that closes one adds its row here. + +--- + + +### B.8 NVMe/TCP receive bounds + +| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status | +|---|---|---|---|---|---|---| +| `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | + ### Volume create capacity | ID | Invariant | Transition | Enforced in | Regression tests | Model | Status | |---|---|---|---|---|---|---| | `INV-VOLUME-CREATE-SIZE-001` | Creation refuses capacity above 16 TiB - 4 KiB before provisioning, allocating a WAL, or persisting a volume record. Geometry checks cannot overflow. | M6 initial create (static parameter admission) | `core/geometry/volume_size.go`; lifecycle `CreateVolume`, CSI `volumeSpecFromCreateRequest`, catalog `EnsureVolume`, storage `CreateWALStoreWithOptions` | `TestCreateVolumeRejectsBeyondUint32LBACap`, `TestCSICreateVolumeCapacityCapBeforeProvision`, `TestEnsureVolumeRejectsBeyondUint32LBACap`, `TestCreateWALStoreRefusesOversizeBeforeFilesystem` | Static geometry bound; no protocol state or transition added | ACTIVE | -## Part C. Change rules - -How a fix or a feature is calibrated against this model: - -1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. -2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). -3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. -4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. -5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. -6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. - -Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. - -### Dark v3 offline reader (row12a) - -- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. -- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. - -### Dark v3 chunk/BASE integration (row12a) - -- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. -- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. -- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. +## Part C. Change rules + +How a fix or a feature is calibrated against this model: + +1. **Name the touched IDs.** The pull request lists every Part B ID whose statement, enforcing function or test it touches, and the Part A machine and transition. A change on a protocol path that touches no ID says why. +2. **States and transitions move together.** A new or changed state, transition or guard updates, in the same pull request: the Part A table, its diagram (in the design document, or here when the design document has none), the Part B rows, and the TLA+ specification if one models that machine (with its configurations re-run and the results in `docs/spec/README.md`). +3. **An ACTIVE row never loses its test.** Renaming or moving a test updates the row. Deleting a test, or weakening it so it no longer asserts the statement, needs a replacement test in the same pull request. +4. **Every bug becomes a test and a row.** A bug found by a unit test, a review, a soak or chaos run, or a TLA+ counterexample becomes a regression test that fails before the fix and passes after it, and a new or updated Part B row naming that test. +5. **Rows are stable.** IDs are never reused or renumbered. A retired row stays with status `ARCHIVED` and a reason. A narrowed statement says what was dropped in a note. +6. **STUB rows block claims.** A release note or a design document must not claim a property backed only by a `STUB` row. Turning a `STUB` into `ACTIVE` is the test plus the status change. + +Format v3 row 4 remains dark. Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The later W/BASE/fence owner must check R < W*, fence and publish bounds before readiness or append admission; neither codec nor scan success is readiness. The installed scan begins at max(BaseCursor, retainedTail). No ACTIVE v2 machine/guard is replaced by this step. + +### Dark v3 offline reader (row12a) + +- `INV-WAL-V3-READONLY-001` (ACTIVE for the explicit dark selector only): the explicit dark reader opens store and map read-only, validates both live slot dependencies and the trusted WAL prefix, merges WAL winners above the checkpoint with extents, and never runs recovery, a fence, a worker, or publication. Installing images, corrupt acknowledged WAL/map dependencies and unfinished fresh restores refuse. WAL records are checked again at read. An absent remote chunk returns `ErrReadOnlyNotResident`, even with a local hint; offline reading does not perform remote fills. The public selector remains legacy until row12b. +- Controls: `TestWALStoreV3_ReadOnlyMergesWALAndExtentWithoutWrites`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies`, `TestWALStoreV3_ReadOnlyNeverReturnsUnfilledExtentZeros`, `TestWALStoreV3_ReadOnlyRevalidatesWALAndBindsReadonlyMetadata`, and the actual endpoint snapshot caller `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture`. Reader mutex covers the descriptor read and Close; no new lock edge or durability state transition. + +### Dark v3 chunk/BASE integration (row12a) + +- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for dark mapped v3): begin/complete first take `installMu` exclusive, then the attached layer's whole-cut `capMu` drain, then existing capture/lifecycle/leader/store/descriptor/file-sync admission. The drain is registered with Close; no lower store lock is held while it waits. A pending unknown HEAD CAS refuses begin until settled. A newly published layer invalidates an outer hooks snapshot before descriptor mutation. Unsupported attached layers still refuse. No capture path takes installMu and no checkpoint callback takes capMu. +- The release runs after lower locks, before installMu release. It derives the in-memory guard from the actual descriptor on success or failure, invalidates staging/reconciliation generations and keeps dirty coverage conservative. Installing capture has an early typed refusal. Presence becomes local before the existing completion barrier can publish installed; a failure retains installing. Completed BASE attach treats local bytes (including ZERO) as authoritative, persists presence, and captures through the owned UNKNOWN/max-LSN map without a legacy bitmap. A fresh provider marker does not authorize seeding an older HEAD over completed local BASE; the read-only installed-BASE query is revalidated by attachment admission. +- Controls: `TestChunkLayerV3_BASEIncompleteCaptureGuard`, `TestChunkLayerV3_BASEBeginDrainsWholeCut`, `TestChunkLayerV3_BASEBeginRefusesUnsettledCAS`, `TestChunkLayerV3_BASEDrainJoinsClose`, `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling`, and the three actual provider controls in `provider_format_v3_base_test.go`. The unsupported-layer refusal remains in `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`. BASE descriptor states remain unchanged. Chunk-managed providers opt into deferred retirement immediately after create/open, before Recover. Both installed local presence and the provider durable attach point are required before retirement. The provider removes its fresh marker and fsyncs its directory under the store installMu-exclusive commit, then records per-open owner readiness; the callback never re-enters the store. Layer attach alone never allows retirement. Later completed transitions require owner readiness plus saved full presence before allowing; the next ordinary publication still checks existing retirement coverage. The provider keeps the constructed layer private as chunkPending until this commit succeeds; explicit publication cannot resolve it and the scheduler starts only after commit. Failed commits retain the private layer for retry without reattaching. Held pre-marker controls require Capture/Cut/MakeRemoteDurable to return ErrNotChunkVolume with no new remote writes, intents or HEAD changes, then crash/reopen exact local bytes. Actual subprocess controls crash after presence but before marker removal (both pre-existing installed BASE and attached completion), retaining the installed discriminator and recovering exact local data. The opt-in is re-established on reopen, and unmanaged/unmapped stores retain ordinary retirement. A seed-only checkpoint is not local-image evidence. Controls `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` and `TestDurableProviderV3_SeedOnlyCheckpointStillRestoresHEAD` distinguish these cases; the presence-failure control also requires the gate remain deferred until successful retry. The external format model does not prove the chunk publication drain; the deterministic caller controls cover that seam. From b59e690969a885bb25e5520d0e5a6d3bb9e514f8 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:17:00 -0800 Subject: [PATCH 10/33] docs: align create admission table diagram and model scope with capacity bound --- seaweed-block/docs/design/agent-workspace-design.md | 5 ++++- seaweed-block/docs/design/invariants.md | 2 +- seaweed-block/docs/spec/README.md | 4 ++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 48b9ca7a58..8d418f74dc 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -183,6 +183,9 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete +**Create capacity.** New volumes larger than 16 TiB - 4 KiB (17,592,186,040,320 bytes) are refused before provisioning, WAL allocation or durable VOLUME creation. CSI, lifecycle intent, Catalog and local WAL create share the same bound. A fork inherits the existing source geometry. Existing store-open formats are unchanged. This is static admission, not a new lifecycle state. + + - **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. - **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`. @@ -203,7 +206,7 @@ HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: initial HEAD (gen 1, epoch 0) or fork HEAD + [*] --> active: create within capacity bound (gen 1, epoch 0) or inherited fork HEAD active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 2eca4bf5da..3cc0320c89 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -229,7 +229,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | new volume capacity is at most 16 TiB - 4 KiB before creation; the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index ee2a896216..762dac7cdd 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -274,3 +274,7 @@ Recover/reset snapshot recheck and saved-file readers are covered by the native `TestCutCOWV3_*` caller controls, not claimed as model proofs. The earlier thirteen-spec parse statement above predates this imported model; no new independent TLC/parse or cloud run is claimed here. + +### Static volume create capacity + +`INV-VOLUME-CREATE-SIZE-001` bounds a new volume to 16 TiB - 4 KiB. The current ControlPlane/ChunkLifecycle models abstract volume identity and create/delete ordering, not byte capacity or block geometry; this admission bound is not a TLC property. The actual CSI, lifecycle, Catalog and WAL create caller controls in `volume_size_limit_test.go` establish the bound before side effects. No modeled state or action is changed. From dcf574ffd56aa9b2d52d688fe23d9619c5f18bdc Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:21:23 -0800 Subject: [PATCH 11/33] test(chunkstore): require new forks to respect the volume capacity cap --- .../chunkstore/fork_size_limit_test.go | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go diff --git a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go new file mode 100644 index 0000000000..b64a0cfe36 --- /dev/null +++ b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go @@ -0,0 +1,60 @@ +package chunkstore + +import ( + "context" + "path" + "strings" + "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb" +) + +// A legacy catalog may already contain oversized geometry. A new fork is +// still a new volume: it must not bypass the creation cap by inheritance. +func TestForkRejectsLegacyOversizedGeometry(t *testing.T) { + for _, blocks := range []uint64{4294967295, 4294967296} { + f, b, c, _, _ := gcFixture(t) + ctx := context.Background() + v, ok, err := c.ReadVolume(ctx, "v1") + if err != nil || !ok { + t.Fatal(err) + } + v.NumBlocks = blocks + e, err := volumeEntry(v, "") + if err != nil { + t.Fatal(err) + } + if err = f.UpdateEntry(ctx, path.Join(catBase, "v1"), e, nil); err != nil { + t.Fatal(err) + } + h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) + snap, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h) + if err != nil { + t.Fatal(err) + } + if err = f.CreateEntry(ctx, catBase, &filerpb.Entry{Name: "fork", IsDirectory: true}, true); err != nil { + t.Fatal(err) + } + _, err = c.Fork(ctx, ForkRequest{Source: "v1", Snapshot: "s1", Target: "fork", RequestID: "f"}) + if blocks == 4294967295 { + if err != nil { + t.Fatalf("at-cap fork: %v", err) + } + got, ok, e := c.ReadVolume(ctx, "fork") + if e != nil || !ok || got.NumBlocks != blocks { + t.Fatalf("at-cap geometry not inherited: %+v %v", got, e) + } + continue + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("oversized fork must refuse: %v", err) + } + if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok { + t.Fatalf("oversized fork persisted target: %v %v", ok, e) + } + entry, e := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), snap.attempt) + if e != nil || len(decodeClaims(entry)) != 0 { + t.Fatalf("capacity refusal left a parent claim: %v", e) + } + } +} From f9a8b5daab22758f85e2e654477659dc89103a86 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:30:54 -0800 Subject: [PATCH 12/33] durable: detach review fold: settle every failure before resuming; one freeze budget - P1: every failed detach is settled before anything resumes, a failed drain included. A repeated detach after a successful one (or with a cancelled context) returns the first result and stays stopped, and a retry over an unresolved detach CAS stays stopped while the outcome is unknown. The StopIO failure path used to resume unconditionally. - P1: one freeze budget covers the drain, the final cut and the settlement (the cut gets three quarters, the settlement the rest); the settlement no longer adds 10 s of its own. The bound is cooperative (contexts), as documented. - P2: the resume does not restart the periodic cuts after a concurrent Close (or a replaced layer); ErrDetachOutcomeUnknown maps to outcome_unknown explicitly, before its cause. - Tests: the two P1 cases and the budget case (red on 26426dd5: resumed a detached volume, resumed over an unknown CAS, 10.4 s for a 400 ms bound); a detach CAS genuinely delayed until after the cancel then fails its precondition; the drain test now checks that the resumed write queues behind the admitted one and that recovery succeeds. - Mutants (declared, 9/9): plus a failed StopIO resuming without the settle, the settlement with time of its own, the cut taking the whole budget. Co-Authored-By: Claude Opus 5.5 --- .../core/frontend/durable/provider.go | 10 +- .../core/frontend/durable/provider_chunk.go | 37 ++++-- .../provider_chunk_detach_abort_test.go | 125 +++++++++++++++++- .../provider_chunk_detach_stop_test.go | 9 +- .../core/host/volume/chunk_control.go | 3 + 5 files changed, 163 insertions(+), 21 deletions(-) diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index d115bc07af..7453e9f7b2 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -165,10 +165,12 @@ type ProviderConfig struct { // passed since the volume's last successful cut (of any kind). Zero // disables the timer. ChunkCaptureInterval time.Duration - // DetachFreezeTimeout bounds how long DetachVolume keeps guest I/O - // stopped for its drain and final cut (the caller's context can only - // shorten it). Zero: 20 s, below the host's 30 s I/O timeout; a freeze - // past the 5 s target is logged as an alarm. + // DetachFreezeTimeout bounds how long a failing DetachVolume keeps guest + // I/O stopped before it resumes or settles: the drain and final cut get + // three quarters of it, the settlement of a failed cut the rest (the + // caller's context can only shorten the cut part). Zero: 20 s, below the + // host's 30 s I/O timeout; a freeze past the 5 s target is logged as an + // alarm. Cooperative: a syscall that never returns is not bounded. DetachFreezeTimeout time.Duration // ChunkDirtyThreshold is the bound on one cut's barrier copy, in // chunks. It never triggers a cut: the remote holds snapshots, and diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index 95add9aadc..da0da1948f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -780,25 +780,31 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st if freeze <= 0 { freeze = defaultDetachFreezeTimeout } - fctx, cancel := context.WithTimeout(ctx, freeze) - defer cancel() + // One freeze budget covers the drain, the final cut AND the settlement: + // the cut gets three quarters, the settlement what is left. The bound is + // cooperative (contexts): a syscall that never returns is not bounded here. start := time.Now() + cutCtx, cancel := context.WithDeadline(ctx, start.Add(freeze*3/4)) + defer cancel() defer func() { if d := time.Since(start); d > detachFreezeTarget { log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) } }() h.chunkDetach = true - if err := h.backend.StopIO(fctx, "chunk detach: I/O stopped until a new attach"); err != nil { - return storage.ChunkCutResult{}, 0, p.resumeAfterDetach(volumeID, h, layer, err) // nothing was cut - } - p.stopChunkLoop(h) - r, err := layer.Detach(fctx) + err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") if err == nil { - return r, h.storage.NextLSN() - 1, nil + p.stopChunkLoop(h) + var r storage.ChunkCutResult + if r, err = layer.Detach(cutCtx); err == nil { + return r, h.storage.NextLSN() - 1, nil + } } - // Settle with time of its own: the freeze bound may be what ended the cut. - sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), detachSettleTimeout) + // Every failure, a failed drain included, is settled before anything + // resumes: an earlier detach that applied, an unresolved detach CAS or a + // fenced layer must never resume serving. The settlement keeps the rest + // of the freeze budget even when the caller's context is gone. + sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze)) defer scancel() how, dr, serr := layer.SettleDetach(sctx) switch { @@ -816,17 +822,22 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st const ( defaultDetachFreezeTimeout = 20 * time.Second detachFreezeTarget = 5 * time.Second - detachSettleTimeout = 10 * time.Second ) // resumeAfterDetach undoes a detach that provably did not happen: the // periodic cuts restart, the stop is lifted, and the volume serves again. // The caller holds h.attachMu. func (p *DurableProvider) resumeAfterDetach(volumeID string, h *volHandle, layer storage.ChunkLayer, cause error) error { - h.chunkDetach = false p.mu.Lock() - p.startChunkLoop(volumeID, h, layer) + closed := p.closed || h.chunk != layer + if !closed { + p.startChunkLoop(volumeID, h, layer) + } p.mu.Unlock() + if closed { // a concurrent Close or detach of the layer owns the volume now + return fmt.Errorf("durable: detach of %s aborted while the provider closed: %w", volumeID, cause) + } + h.chunkDetach = false h.backend.SetOperational(true, "chunk detach aborted: serving resumed") log.Printf("durable: detach of volume=%s aborted, nothing published; serving resumed: %v", volumeID, cause) return fmt.Errorf("%w: %w", ErrDetachAborted, cause) diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go index 556dabe8bd..aeeb8c7a31 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -28,6 +28,11 @@ type faultRemote struct { casMode string // "", "precondition", "lost" (not applied, error), "applied-lost" (applied, error), "hold" getHeadErr error // returned by every GetHead while set getHeadFail int // the next N GetHead calls fail + getHeadHold bool // every GetHead blocks until its caller gives up + // "delayed": the CAS's reply is lost now, the CAS itself reaches the + // remote only when release closes; its own result goes to delayedErr. + release chan struct{} + delayedErr chan error } var errInjected = errors.New("injected remote fault") @@ -46,12 +51,17 @@ func (r *faultRemote) Put(ctx context.Context, key string, data []byte) error { func (r *faultRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) { r.mu.Lock() + hold := r.getHeadHold err := r.getHeadErr if err == nil && r.getHeadFail > 0 { r.getHeadFail-- err = errInjected } r.mu.Unlock() + if hold { + <-ctx.Done() + return storage.ChunkHead{}, ctx.Err() + } if err != nil { return storage.ChunkHead{}, err } @@ -71,6 +81,16 @@ func (r *faultRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVer case "hold": // held until the caller gives up: not applied <-ctx.Done() return 0, ctx.Err() + case "delayed": + r.mu.Lock() + release, out := r.release, r.delayedErr + r.mu.Unlock() + go func() { + <-release + _, err := r.MemChunkRemote.CASHead(context.Background(), expected, next) + out <- err + }() + return 0, errInjected case "applied-lost": if _, err := r.MemChunkRemote.CASHead(ctx, expected, next); err != nil { return 0, err @@ -243,8 +263,9 @@ func TestWALStoreChunk_DetachFreezeIsBoundedThenResumes(t *testing.T) { if !errors.Is(err, durable.ErrDetachAborted) || !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("detach with a hung CAS: %v; want an aborted detach at the freeze bound", err) } - if took < 300*time.Millisecond || took > 3*time.Second { - t.Fatalf("detach with a hung CAS took %v; want about the 300 ms freeze bound", took) + // The cut gets three quarters of the bound, the settlement the rest. + if took < 225*time.Millisecond || took > 300*time.Millisecond+200*time.Millisecond { + t.Fatalf("detach with a hung CAS took %v; want the cut ended at 3/4 of the 300 ms freeze bound and the total within it", took) } assertServing(t, p, b, remote) } @@ -270,3 +291,103 @@ func TestWALStoreChunk_DetachAgainstNewerEpochStaysStopped(t *testing.T) { t.Fatalf("write after a fenced detach: %v; want it refused (not ready / stale primary)", err) } } + +// P1 (review): a repeated detach after a successful one, with a cancelled +// context (its StopIO fails at once), returns the first result and never +// resumes serving. +func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T) { + _, p, b := detachFixture(t) + r1, _, err := p.DetachVolume(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + cctx, cancel := context.WithCancel(context.Background()) + cancel() + r2, _, err := p.DetachVolume(cctx, "v1") + if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached { + t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a repeated detach: %v; want ErrNotReady (never resumed)", err) + } +} + +// P1 (review): after an undecidable detach, a retry whose StopIO fails (a +// cancelled context) settles first and stays stopped while the outcome is +// still unknown. +func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) { + remote, p, b := detachFixture(t) + remote.set(func(r *faultRemote) { r.casMode = "lost"; r.getHeadErr = errInjected }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err) + } + cctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := p.DetachVolume(cctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err) + } + if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after a retry over an unknown detach: %v; want ErrNotReady", err) + } +} + +// P1 (review): one freeze budget covers the cut AND the settlement: with the +// CAS and every HEAD read hung, DetachVolume returns within the bound (here +// undecided, so the volume stays stopped). +func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) { + const freeze = 400 * time.Millisecond + remote := &faultRemote{MemChunkRemote: storage.NewMemChunkRemote()} + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), BlockSize: 4096, NumBlocks: pcBlocks, ChunkBlocks: pcChunkBlocks, + DetachFreezeTimeout: freeze, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, v1View()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + openRecovered(t, p) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err := b.Write(context.Background(), 4096, block(1)); err != nil { + t.Fatal(err) + } + remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true }) + start := time.Now() + _, _, err = p.DetachVolume(context.Background(), "v1") + took := time.Since(start) + if !errors.Is(err, durable.ErrDetachOutcomeUnknown) { + t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err) + } + if took > freeze+200*time.Millisecond { + t.Fatalf("detach took %v; the %v freeze bound must cover the settlement too", took, freeze) + } + if _, err := b.Write(context.Background(), 8192, block(2)); !errors.Is(err, frontend.ErrNotReady) { + t.Fatalf("write after an undecided detach: %v; want ErrNotReady", err) + } +} + +// P2 (review): the lost detach CAS really is in flight. It reaches the remote +// only after the cancel landed, and then fails its precondition: HEAD stays +// active. +func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) { + remote, p, b := detachFixture(t) + release, delayed := make(chan struct{}), make(chan error, 1) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + t.Cleanup(unblock) + remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed }) + if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { + t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err) + } + unblock() + if err := <-delayed; !errors.Is(err, storage.ErrChunkHeadPrecondition) { + t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", err) + } + if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached { + t.Fatal("the delayed detach CAS landed after the cancel") + } + assertServing(t, p, b, remote) +} diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index b52c96f1ec..d5d511af1f 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -152,14 +152,19 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { // detach itself). nerr := make(chan error, 1) go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() + select { + case err := <-nerr: + t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err) + case <-time.After(100 * time.Millisecond): // queued behind the admitted write, as the drain orders it + } view.unpark() acked := <-werr == nil if err := <-nerr; err != nil { t.Fatalf("new write after an aborted detach: %v; want it accepted", err) } - if _, err := p.RecoverVolume(ctx, "v1"); errors.Is(err, storage.ErrChunkLayerDetached) { - t.Fatalf("recovery after an aborted detach: %v; want the volume serving", err) + if _, err := p.RecoverVolume(ctx, "v1"); err != nil { + t.Fatalf("recovery after an aborted detach: %v; want it to succeed", err) } o := detachOutcome{} o.r, o.last, o.err = p.DetachVolume(ctx, "v1") diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index d9365811c2..97525d2391 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -235,6 +235,9 @@ func chunkErrorCode(err error) (int, string, bool) { case errors.Is(err, durable.ErrDetachAborted): // Before its cause: nothing was published and serving resumed here. return http.StatusConflict, codeDetachAborted, true + case errors.Is(err, durable.ErrDetachOutcomeUnknown): + // Before its cause: the detach may still have landed; I/O stays stopped. + return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true case errors.Is(err, storage.ErrChunkLayerFenced): return http.StatusConflict, codeFenced, false case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): From 1afc5ac00bab3170470df5e9578ecfc7aeb2d89c Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:31:34 -0800 Subject: [PATCH 13/33] test: correct fork capacity fixture lookup error binding --- .../core/frontend/chunkstore/fork_size_limit_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go index b64a0cfe36..250332b795 100644 --- a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go +++ b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go @@ -52,9 +52,9 @@ func TestForkRejectsLegacyOversizedGeometry(t *testing.T) { if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok { t.Fatalf("oversized fork persisted target: %v %v", ok, e) } - entry, e := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), snap.attempt) - if e != nil || len(decodeClaims(entry)) != 0 { - t.Fatalf("capacity refusal left a parent claim: %v", e) + entry, lookupErr := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), snap.attempt) + if lookupErr != nil || len(decodeClaims(entry)) != 0 { + t.Fatalf("capacity refusal left a parent claim: %v", lookupErr) } } } From 5892e35217e0f5c8d6aad8e893662aed4a6bf4bf Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:36:07 -0800 Subject: [PATCH 14/33] fix(chunkstore): refuse oversized inherited fork geometry before claiming --- seaweed-block/core/frontend/chunkstore/catalog.go | 3 +++ seaweed-block/docs/design/agent-workspace-design.md | 4 ++-- seaweed-block/docs/design/invariants.md | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/catalog.go b/seaweed-block/core/frontend/chunkstore/catalog.go index 2b65ff8c4a..b24d94f720 100644 --- a/seaweed-block/core/frontend/chunkstore/catalog.go +++ b/seaweed-block/core/frontend/chunkstore/catalog.go @@ -1356,6 +1356,9 @@ func (c *Catalog) claimForkParent(ctx context.Context, req ForkRequest) (Snapsho 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 { diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 8d418f74dc..3dc6e97d2d 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -183,7 +183,7 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete -**Create capacity.** New volumes larger than 16 TiB - 4 KiB (17,592,186,040,320 bytes) are refused before provisioning, WAL allocation or durable VOLUME creation. CSI, lifecycle intent, Catalog and local WAL create share the same bound. A fork inherits the existing source geometry. Existing store-open formats are unchanged. This is static admission, not a new lifecycle state. +**Create capacity.** New volumes larger than 16 TiB - 4 KiB (17,592,186,040,320 bytes) are refused before provisioning, WAL allocation or durable VOLUME creation. CSI, lifecycle intent, Catalog and local WAL create share the same bound. A fork inherits its source geometry only within the same capacity bound; refusal leaves no parent claim. Existing store-open formats are unchanged. This is static admission, not a new lifecycle state. - **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. @@ -206,7 +206,7 @@ HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: create within capacity bound (gen 1, epoch 0) or inherited fork HEAD + [*] --> active: create within capacity bound (gen 1, epoch 0) or inherited fork HEAD within capacity bound active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 3cc0320c89..8ac60f3c19 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -247,7 +247,7 @@ 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 | fork | require inherited geometry within the create capacity bound; require inherited geometry within the create capacity bound; 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` | **Intents and key bindings.** @@ -473,7 +473,7 @@ Notes: | ID | Invariant | Transition | Enforced in | Regression tests | Model | Status | |---|---|---|---|---|---|---| -| `INV-VOLUME-CREATE-SIZE-001` | Creation refuses capacity above 16 TiB - 4 KiB before provisioning, allocating a WAL, or persisting a volume record. Geometry checks cannot overflow. | M6 initial create (static parameter admission) | `core/geometry/volume_size.go`; lifecycle `CreateVolume`, CSI `volumeSpecFromCreateRequest`, catalog `EnsureVolume`, storage `CreateWALStoreWithOptions` | `TestCreateVolumeRejectsBeyondUint32LBACap`, `TestCSICreateVolumeCapacityCapBeforeProvision`, `TestEnsureVolumeRejectsBeyondUint32LBACap`, `TestCreateWALStoreRefusesOversizeBeforeFilesystem` | Static geometry bound; no protocol state or transition added | ACTIVE | +| `INV-VOLUME-CREATE-SIZE-001` | Creation refuses capacity above 16 TiB - 4 KiB before provisioning, allocating a WAL, or persisting a volume record. Geometry checks cannot overflow. | M6 initial create (static parameter admission) | `core/geometry/volume_size.go`; lifecycle `CreateVolume`, CSI `volumeSpecFromCreateRequest`, catalog `EnsureVolume`, `claimForkParent`, storage `CreateWALStoreWithOptions` | `TestCreateVolumeRejectsBeyondUint32LBACap`, `TestCSICreateVolumeCapacityCapBeforeProvision`, `TestEnsureVolumeRejectsBeyondUint32LBACap`, `TestCreateWALStoreRefusesOversizeBeforeFilesystem`, `TestForkRejectsLegacyOversizedGeometry` | Static geometry bound; no protocol state or transition added | ACTIVE | ## Part C. Change rules From f9d9efc4187753292612e7b64027bebfce904608 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:42:06 -0800 Subject: [PATCH 15/33] test(chunkstore): observe refused fork claims through snapshot deletion --- .../core/frontend/chunkstore/fork_size_limit_test.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go index 250332b795..237f018820 100644 --- a/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go +++ b/seaweed-block/core/frontend/chunkstore/fork_size_limit_test.go @@ -28,7 +28,7 @@ func TestForkRejectsLegacyOversizedGeometry(t *testing.T) { t.Fatal(err) } h := publishSource(t, f, b.fakeBlobs, "v1", map[uint64][]byte{0: chunkBytes(0x41)}) - snap, err := c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h) + _, err = c.CreateSnapshot(ctx, "v1", SnapshotRequest{Name: "s1", RequestID: "s"}, h) if err != nil { t.Fatal(err) } @@ -52,9 +52,10 @@ func TestForkRejectsLegacyOversizedGeometry(t *testing.T) { if _, ok, e := c.ReadVolume(ctx, "fork"); e != nil || ok { t.Fatalf("oversized fork persisted target: %v %v", ok, e) } - entry, lookupErr := f.LookupEntry(ctx, path.Join(catBase, "v1", snapsDir, "s1"), snap.attempt) - if lookupErr != nil || len(decodeClaims(entry)) != 0 { - t.Fatalf("capacity refusal left a parent claim: %v", lookupErr) + // Observe claim cleanup through the public retention operation: an + // uncompleted fork claim would make this snapshot undeletable. + if _, deleteErr := c.DeleteSnapshot(ctx, "v1", "s1"); deleteErr != nil { + t.Fatalf("capacity refusal blocked snapshot deletion: %v", deleteErr) } } } From ebe1b0bd13e318c70cec62d4fcd94444c87dd5e2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:50:16 -0800 Subject: [PATCH 16/33] test: include reproducible manifest scaling qualification checker --- .../scripts/check-manifest-scaling.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 seaweed-block/scripts/check-manifest-scaling.py diff --git a/seaweed-block/scripts/check-manifest-scaling.py b/seaweed-block/scripts/check-manifest-scaling.py new file mode 100644 index 0000000000..1ad129ccb7 --- /dev/null +++ b/seaweed-block/scripts/check-manifest-scaling.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Check three-sample manifest benchmark scaling; no device or host access. + +Run go test with -bench BenchmarkPrepareManifestUnchangedGroups -benchtime=20x +-count=3, save stdout, then pass that file to this checker. A 16x metadata +scale must grow less than 64x on the same serial runner. This is an explicit +qualification benchmark, not a wall-clock CI unit test. +""" +import re +import statistics +import sys +from pathlib import Path + +if len(sys.argv) != 2: + raise SystemExit("usage: check-manifest-scaling.py BENCHMARK_LOG") +samples = {256: [], 1024: [], 4096: []} +for count, ns in re.findall( + r"BenchmarkPrepareManifestUnchangedGroups/(256|1024|4096)-\d+\s+\d+\s+(\d+) ns/op", + Path(sys.argv[1]).read_text(encoding="utf-8-sig"), +): + samples[int(count)].append(int(ns)) +if any(len(values) != 3 for values in samples.values()): + raise SystemExit("need exactly three samples per group count") +medians = {count: statistics.median(values) for count, values in samples.items()} +if min(medians.values()) <= 0: + raise SystemExit("benchmark durations must be positive") +growth = medians[4096] / medians[256] +print("median_ns", medians, "growth_4096_over_256", growth, "limit", 64) +raise SystemExit(0 if growth < 64 else 1) From 89f0ca8b30fb941436c1b86d6bf4a8cdca508960 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 21:52:14 -0800 Subject: [PATCH 17/33] durable: detach review fold 2: forced failed-drain branch, recorded deadlines, handshakes, mapping order, invariants - Test-only hooks: DetachVolume's StopIO can be replaced (the repeat and retry tests now force and observe the failed-drain branch instead of racing a cancelled context against a finished drain); the detach's cut and settlement deadlines are traced (the budget test checks 3/4 of the freeze, then the bound); the backend signals an I/O passing its readiness check right before the I/O lock (the drain test's arrival handshake replaces a 100 ms non-completion window, with bounded receives). - The delayed detach CAS worker is joined, bounded, also on failure. - chunkErrorCode: the detach sentinels decide before a catalog-error cause; the table rows now discriminate that order (no storage CAS sentinel behind them). - Invariants: INV-WS-DETACH-ABORT-001 and INV-WS-DETACH-FREEZE-001, and the M4 transition Holder (detaching) -> Holder. - Mutants (declared, 10/10): plus a catalog cause deciding before the sentinels; the whole-budget cut is now caught by the deadline check too. Co-Authored-By: Claude Opus 5.5 --- .../frontend/durable/export_chunk_test.go | 21 ++++++++ .../core/frontend/durable/provider.go | 5 ++ .../core/frontend/durable/provider_chunk.go | 14 +++++- .../provider_chunk_detach_abort_test.go | 48 +++++++++++++++---- .../provider_chunk_detach_stop_test.go | 28 +++++++++-- .../core/frontend/durable/storage_adapter.go | 7 +++ .../core/host/volume/chunk_control.go | 9 ++-- .../core/host/volume/chunk_control_test.go | 5 +- seaweed-block/docs/design/invariants.md | 5 +- 9 files changed, 123 insertions(+), 19 deletions(-) diff --git a/seaweed-block/core/frontend/durable/export_chunk_test.go b/seaweed-block/core/frontend/durable/export_chunk_test.go index 83300439e8..7a499b43d7 100644 --- a/seaweed-block/core/frontend/durable/export_chunk_test.go +++ b/seaweed-block/core/frontend/durable/export_chunk_test.go @@ -1,5 +1,26 @@ package durable +import ( + "context" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend" +) + // SetTestAfterChunkResolve installs the test-only hook CutVolume runs right // after it resolves the volume's handle and layer. func SetTestAfterChunkResolve(p *DurableProvider, f func()) { p.testAfterChunkResolve = f } + +// SetTestDetachStopIO replaces DetachVolume's StopIO call (test-only). +func SetTestDetachStopIO(p *DurableProvider, f func(ctx context.Context) error) { + p.testDetachStopIO = f +} + +// SetTestDetachTrace observes DetachVolume's stages and deadlines (test-only). +func SetTestDetachTrace(p *DurableProvider, f func(stage string, deadline time.Time)) { + p.testDetachTrace = f +} + +// SetTestBeforeIOLock runs f in the backend's admission, right before the I/O +// lock (test-only). +func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).testBeforeIOLock = f } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 7453e9f7b2..88722c9f40 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -194,6 +194,11 @@ type DurableProvider struct { // testAfterChunkResolve, test-only, runs in CutVolume right after the // volume's handle and layer are resolved. testAfterChunkResolve func() + // testDetachStopIO, test-only, replaces DetachVolume's StopIO call (so a + // test can force the failed-drain branch); testDetachTrace, test-only, + // observes the detach's stages and their deadlines ("cut", "settle"). + testDetachStopIO func(ctx context.Context) error + testDetachTrace func(stage string, deadline time.Time) // testBeforeChunkFreshRetire holds the real post-presence/pre-marker boundary. testBeforeChunkFreshRetire func() error diff --git a/seaweed-block/core/frontend/durable/provider_chunk.go b/seaweed-block/core/frontend/durable/provider_chunk.go index da0da1948f..66b3158d2a 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk.go +++ b/seaweed-block/core/frontend/durable/provider_chunk.go @@ -791,8 +791,16 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st log.Printf("durable: ALARM detach of volume=%s held guest I/O for %s (target %s, bound %s)", volumeID, d.Round(time.Millisecond), detachFreezeTarget, freeze) } }() + if trace := p.testDetachTrace; trace != nil { + dl, _ := cutCtx.Deadline() + trace("cut", dl) + } h.chunkDetach = true - err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") + if stop := p.testDetachStopIO; stop != nil { + err = stop(cutCtx) + } else { + err = h.backend.StopIO(cutCtx, "chunk detach: I/O stopped until a new attach") + } if err == nil { p.stopChunkLoop(h) var r storage.ChunkCutResult @@ -806,6 +814,10 @@ func (p *DurableProvider) DetachVolume(ctx context.Context, volumeID string) (st // of the freeze budget even when the caller's context is gone. sctx, scancel := context.WithDeadline(context.WithoutCancel(ctx), start.Add(freeze)) defer scancel() + if trace := p.testDetachTrace; trace != nil { + dl, _ := sctx.Deadline() + trace("settle", dl) + } how, dr, serr := layer.SettleDetach(sctx) switch { case serr != nil: diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go index aeeb8c7a31..4584662a70 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_abort_test.go @@ -301,9 +301,12 @@ func TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes(t *testing.T if err != nil { t.Fatal(err) } - cctx, cancel := context.WithCancel(context.Background()) - cancel() - r2, _, err := p.DetachVolume(cctx, "v1") + forced := false + durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails + r2, _, err := p.DetachVolume(context.Background(), "v1") + if !forced { + t.Fatal("the failed-drain branch was not taken") + } if err != nil || r2.Head.Gen != r1.Head.Gen || r2.Head.State != storage.ChunkHeadDetached { t.Fatalf("repeated detach with a cancelled context: %+v %v; want the first result %+v", r2, err, r1) } @@ -321,9 +324,13 @@ func TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes(t *testing.T) { if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) { t.Fatalf("first detach: %v; want ErrDetachOutcomeUnknown", err) } - cctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, _, err := p.DetachVolume(cctx, "v1"); !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { + forced := false + durable.SetTestDetachStopIO(p, func(context.Context) error { forced = true; return context.Canceled }) // the drain fails + _, _, err := p.DetachVolume(context.Background(), "v1") + if !forced { + t.Fatal("the failed-drain branch was not taken") + } + if !errors.Is(err, durable.ErrDetachOutcomeUnknown) || errors.Is(err, durable.ErrDetachAborted) { t.Fatalf("retry over an unresolved detach CAS: %v; want still unknown, never aborted", err) } if _, err := b.Write(context.Background(), 12288, block(3)); !errors.Is(err, frontend.ErrNotReady) { @@ -355,9 +362,15 @@ func TestWALStoreChunk_DetachFreezeBoundCoversTheSettle(t *testing.T) { t.Fatal(err) } remote.set(func(r *faultRemote) { r.casMode = "hold"; r.getHeadHold = true }) + deadlines := map[string]time.Time{} + durable.SetTestDetachTrace(p, func(stage string, d time.Time) { deadlines[stage] = d }) start := time.Now() _, _, err = p.DetachVolume(context.Background(), "v1") took := time.Since(start) + cutAt, settleAt := deadlines["cut"].Sub(start), deadlines["settle"].Sub(start) + if cutAt < freeze*3/4-50*time.Millisecond || cutAt > freeze*3/4+50*time.Millisecond || settleAt < freeze-50*time.Millisecond || settleAt > freeze+50*time.Millisecond { + t.Fatalf("deadlines: cut %v, settle %v after the start; want three quarters of the %v freeze, then the bound", cutAt, settleAt, freeze) + } if !errors.Is(err, durable.ErrDetachOutcomeUnknown) { t.Fatalf("detach with a hung CAS and hung HEAD reads: %v; want the outcome unknown", err) } @@ -377,14 +390,31 @@ func TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel(t *testing.T) { release, delayed := make(chan struct{}), make(chan error, 1) var once sync.Once unblock := func() { once.Do(func() { close(release) }) } - t.Cleanup(unblock) + joined := false + t.Cleanup(func() { // join the delayed CAS worker, bounded + unblock() + if !joined { + select { + case <-delayed: + case <-time.After(5 * time.Second): + t.Error("delayed CAS worker not joined") + } + } + }) remote.set(func(r *faultRemote) { r.casMode = "delayed"; r.release, r.delayedErr = release, delayed }) if _, _, err := p.DetachVolume(context.Background(), "v1"); !errors.Is(err, durable.ErrDetachAborted) { t.Fatalf("detach with a delayed CAS: %v; want ErrDetachAborted after the cancel", err) } unblock() - if err := <-delayed; !errors.Is(err, storage.ErrChunkHeadPrecondition) { - t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", err) + var derr error + select { + case derr = <-delayed: + joined = true + case <-time.After(5 * time.Second): + t.Fatal("the delayed detach CAS did not complete after its release") + } + if !errors.Is(derr, storage.ErrChunkHeadPrecondition) { + t.Fatalf("the delayed detach CAS after the cancel: %v; want a precondition failure", derr) } if head, _ := remote.MemChunkRemote.GetHead(context.Background()); head.State == storage.ChunkHeadDetached { t.Fatal("the delayed detach CAS landed after the cancel") diff --git a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go index d5d511af1f..0dda1b07f1 100644 --- a/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go +++ b/seaweed-block/core/frontend/durable/provider_chunk_detach_stop_test.go @@ -150,17 +150,39 @@ func TestWALStoreChunk_DetachDrainTimeoutAbortsAndResumes(t *testing.T) { // the aborted stop orders new I/O after the I/O admitted before it, so // this write completes once that admitted write does (never on the // detach itself). + arrived := make(chan struct{}) + var arriveOnce sync.Once + durable.SetTestBeforeIOLock(b, func() { arriveOnce.Do(func() { close(arrived) }) }) nerr := make(chan error, 1) go func() { _, err := b.Write(ctx, 8192, block(6)); nerr <- err }() + bounded := func(what string, ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(5 * time.Second): + t.Fatalf("%s did not happen within 5s", what) + } + } + bounded("the new write passing the operational gate (serving resumed)", arrived) select { case err := <-nerr: t.Fatalf("new write completed (%v) ahead of the write admitted before the stop", err) - case <-time.After(100 * time.Millisecond): // queued behind the admitted write, as the drain orders it + default: // queued behind the admitted write at the I/O lock, as the drain orders it } view.unpark() - acked := <-werr == nil - if err := <-nerr; err != nil { + recv := func(what string, ch <-chan error) error { + t.Helper() + select { + case err := <-ch: + return err + case <-time.After(5 * time.Second): + t.Fatalf("%s did not complete within 5s", what) + return nil + } + } + acked := recv("the admitted write", werr) == nil + if err := recv("the new write", nerr); err != nil { t.Fatalf("new write after an aborted detach: %v; want it accepted", err) } if _, err := p.RecoverVolume(ctx, "v1"); err != nil { diff --git a/seaweed-block/core/frontend/durable/storage_adapter.go b/seaweed-block/core/frontend/durable/storage_adapter.go index 30e3c05bbd..e2fcea011f 100644 --- a/seaweed-block/core/frontend/durable/storage_adapter.go +++ b/seaweed-block/core/frontend/durable/storage_adapter.go @@ -146,6 +146,10 @@ const maxFullBlockBatchBlocks = 64 // StorageBackend adapts a LogicalStorage into frontend.Backend. type StorageBackend struct { + // testBeforeIOLock, test-only, runs in admit after the readiness check, + // right before the I/O lock (an arrival handshake for queued I/O). + testBeforeIOLock func() + storage storage.LogicalStorage view frontend.ProjectionView id frontend.Identity @@ -582,6 +586,9 @@ func (b *StorageBackend) admit() (func(), error) { if err := b.readyCheck(); err != nil { return nil, err } + if hook := b.testBeforeIOLock; hook != nil { + hook() + } b.ioMu.RLock() if err := b.gate(); err != nil { b.ioMu.RUnlock() diff --git a/seaweed-block/core/host/volume/chunk_control.go b/seaweed-block/core/host/volume/chunk_control.go index 97525d2391..a0053962cb 100644 --- a/seaweed-block/core/host/volume/chunk_control.go +++ b/seaweed-block/core/host/volume/chunk_control.go @@ -230,14 +230,15 @@ func writeChunkFailure(w http.ResponseWriter, err error) { func chunkErrorCode(err error) (int, string, bool) { var ce *chunkstore.CatalogError switch { - case errors.As(err, &ce): - return catalogStatus(ce.Code), ce.Code, ce.Retryable case errors.Is(err, durable.ErrDetachAborted): - // Before its cause: nothing was published and serving resumed here. + // Before any cause (a catalog error included): nothing was + // published and serving resumed here. return http.StatusConflict, codeDetachAborted, true case errors.Is(err, durable.ErrDetachOutcomeUnknown): - // Before its cause: the detach may still have landed; I/O stays stopped. + // Before any cause: the detach may still have landed; I/O stays stopped. return http.StatusServiceUnavailable, chunkstore.CodeOutcomeUnknown, true + case errors.As(err, &ce): + return catalogStatus(ce.Code), ce.Code, ce.Retryable case errors.Is(err, storage.ErrChunkLayerFenced): return http.StatusConflict, codeFenced, false case errors.Is(err, storage.ErrChunkCASOutcomeUnknown): diff --git a/seaweed-block/core/host/volume/chunk_control_test.go b/seaweed-block/core/host/volume/chunk_control_test.go index 60e9c7f302..6c8c76722d 100644 --- a/seaweed-block/core/host/volume/chunk_control_test.go +++ b/seaweed-block/core/host/volume/chunk_control_test.go @@ -223,7 +223,10 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) { {fmt.Errorf("x: %w", storage.ErrChunkLayerClosed), "closing", 503, false}, {fmt.Errorf("x: %w", storage.ErrChunkLayerDetached), "closing", 409, false}, {fmt.Errorf("%w: %w", durable.ErrDetachAborted, storage.ErrChunkRemoteUnavailable), "detach_aborted", 409, true}, - {fmt.Errorf("%w: %w (settle: %w)", durable.ErrDetachOutcomeUnknown, storage.ErrChunkCASOutcomeUnknown, storage.ErrChunkRemoteUnavailable), "outcome_unknown", 503, true}, + // The detach sentinels decide even over a catalog-error cause (which + // alone maps to its own code), and without the storage CAS sentinel. + {fmt.Errorf("%w: %w", durable.ErrDetachAborted, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "detach_aborted", 409, true}, + {fmt.Errorf("%w: %w", durable.ErrDetachOutcomeUnknown, &chunkstore.CatalogError{Code: chunkstore.CodeSnapshotExists, Message: "m"}), "outcome_unknown", 503, true}, {fmt.Errorf("%w: %w: cut LSN 1, HEAD remote_lsn 10", storage.ErrChunkCaptureRefused, storage.ErrChunkLSNBehind), "lsn_behind", 409, false}, {&chunkstore.CatalogError{Code: chunkstore.CodeInvalidLabel, Message: "m"}, "invalid_label", 400, false}, {fmt.Errorf("x: %w", durable.ErrNotChunkVolume), "not_chunk_volume", 409, false}, diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index b032a37af0..7ab2bda3af 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -91,6 +91,8 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | +| `INV-WS-DETACH-ABORT-001` | A failed detach resumes serving only when it provably did not publish (before its CAS, a refused CAS, or an unresolved detach CAS cancelled at the same base). An applied, fenced or undecided detach keeps I/O stopped, also on a repeated detach or a retry: every failure is settled before any resume. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `TestWALStoreChunk_FailedDetachUploadResumes`, `TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes`, `TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel`, `TestWALStoreChunk_LostDetachCASAppliedFoundBySettle`, `TestWALStoreChunk_UndecidableDetachStaysStopped`, `TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes`, `TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | +| `INV-WS-DETACH-FREEZE-001` | One freeze budget (`DetachFreezeTimeout`, default 20 s) bounds a failing detach's drain, final cut and settlement together: the cut gets three quarters, the settlement the rest. Cooperative: contexts only. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume` | `TestWALStoreChunk_DetachFreezeIsBoundedThenResumes`, `TestWALStoreChunk_DetachFreezeBoundCoversTheSettle` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | @@ -174,6 +176,7 @@ stateDiagram-v2 | Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | +| Holder (detaching) | Holder | a failed detach that provably did not publish resumes serving: nothing reached its CAS, the CAS was refused, or an unresolved detach CAS was cancelled by a CAS at the same base | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `INV-WS-DETACH-ABORT-001`, `INV-WS-DETACH-FREEZE-001` | | Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | @@ -264,7 +267,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th ## Part B. Invariant ledger -80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 new. +82 rows: 71 ACTIVE, 11 STUB; 15 kept from the internal ledger, 67 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. From 0a35653775e03433027f2407c6dcade82988a90f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:09:41 -0800 Subject: [PATCH 18/33] docs: keep the detach invariant rows off the public PR (archived on the share) Co-Authored-By: Claude Opus 5.5 --- seaweed-block/docs/design/invariants.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 7ab2bda3af..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -91,8 +91,6 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a | none | Granted | `RenewWorkspaceLease` from the current holder at the current epoch; no move pending; the first grant is written synchronously and persists the durable horizon now + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001` | | Granted | Granted | renew from memory (the lease view, leaf lock only) before the durable horizon and the granted deadline; the grant is min(now + TTL, horizon), refused with an error when it would leave no host validity (grant − skew/2 ≤ now); an extender, an ordinary writer under the publisher lock, raises the horizon to trigger + 1.5·TTL | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `extendWorkspaceLease` | `INV-WS-LEASE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001` | | Granted | Revoking | `BeginWorkspaceRevocation` for the matching lease; a renew now returns the revoking lease with the granted expiry, min(horizon, deadline), without extending it | `core/authority/workspace.go` `BeginWorkspaceRevocation`; `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply` | `INV-WS-CLEAN-MOVE-001` | -| `INV-WS-DETACH-ABORT-001` | A failed detach resumes serving only when it provably did not publish (before its CAS, a refused CAS, or an unresolved detach CAS cancelled at the same base). An applied, fenced or undecided detach keeps I/O stopped, also on a repeated detach or a retry: every failure is settled before any resume. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `TestWALStoreChunk_FailedDetachUploadResumes`, `TestWALStoreChunk_LostDetachCASNotAppliedIsCancelledAndResumes`, `TestWALStoreChunk_DelayedDetachCASCannotLandAfterTheCancel`, `TestWALStoreChunk_LostDetachCASAppliedFoundBySettle`, `TestWALStoreChunk_UndecidableDetachStaysStopped`, `TestWALStoreChunk_RepeatDetachWithCancelledContextNeverResumes`, `TestWALStoreChunk_RetryAfterUndecidableDetachNeverResumes` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | -| `INV-WS-DETACH-FREEZE-001` | One freeze budget (`DetachFreezeTimeout`, default 20 s) bounds a failing detach's drain, final cut and settlement together: the cut gets three quarters, the settlement the rest. Cooperative: contexts only. | M4 Holder (detaching) → Holder | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume` | `TestWALStoreChunk_DetachFreezeIsBoundedThenResumes`, `TestWALStoreChunk_DetachFreezeBoundCoversTheSettle` (`core/frontend/durable/provider_chunk_detach_abort_test.go`) | - | ACTIVE | | Revoking | Acked | `AckWorkspaceRevocation` from the holder at the current epoch, a nonzero HEAD generation, the lease still valid; a different second acknowledgement is refused | `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-REVOKE-ACK-001` | | Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation | `core/authority/workspace.go` `prepareWorkspaceMoveLocked` | `INV-WS-CLEAN-MOVE-001` | | Granted or Revoking | Expired | the durable horizon or the granted deadline passes | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`; `core/authority/workspace.go` `AckWorkspaceRevocation` | `INV-WS-FORCED-MOVE-001` | @@ -176,7 +174,6 @@ stateDiagram-v2 | Claiming | Holder, or not installed | unknown CAS outcome: success only if a re-read shows the exact proposal; never a blind replay | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CAS-UNKNOWN-001` | | Holder | Holder | every publish is a cut (M5) | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | Holder | Detached | `Detach` publishes the final cut with state `detached` in one CAS | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach`, `captureLocked` | `INV-WS-CLEAN-MOVE-001` | -| Holder (detaching) | Holder | a failed detach that provably did not publish resumes serving: nothing reached its CAS, the CAS was refused, or an unresolved detach CAS was cancelled by a CAS at the same base | `core/frontend/durable/provider_chunk.go` `DurableProvider.DetachVolume`; `core/storage/chunk_layer.go` `chunkLayerImpl.SettleDetach` | `INV-WS-DETACH-ABORT-001`, `INV-WS-DETACH-FREEZE-001` | | Holder | HolderFenced | a HEAD with a higher epoch, or another holder at the same epoch | `core/storage/chunk_layer.go` `supersededBy`; `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001` | | Holder | (lazy read) | a block missing locally is fetched from HEAD and installed only if it does not overwrite a newer local extent version; a newer WAL-only write still wins on reads, and HEAD's value may be installed beneath it as the backing value, which is correct if a crash loses that unsynced write | `core/storage/chunk_layer.go` `OnReadMiss`, `installFetchedBlock` | `INV-CUT-READMISS-001` | @@ -267,7 +264,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th ## Part B. Invariant ledger -82 rows: 71 ACTIVE, 11 STUB; 15 kept from the internal ledger, 67 new. +80 rows: 69 ACTIVE, 11 STUB; 15 kept from the internal ledger, 65 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. From bdeb3faf5e9cdbfd07e8c53ca8c6c3f6a545a04d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:29:44 -0800 Subject: [PATCH 19/33] docs(geometry): state the block-size assumption behind the byte cap --- seaweed-block/core/geometry/volume_size.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/seaweed-block/core/geometry/volume_size.go b/seaweed-block/core/geometry/volume_size.go index 0d317ede02..0d7aaeea92 100644 --- a/seaweed-block/core/geometry/volume_size.go +++ b/seaweed-block/core/geometry/volume_size.go @@ -4,6 +4,8 @@ package geometry import "fmt" // MaxVolumeBytes is the uint32-LBA limit with the supported 4-KiB IO unit. +// This byte cap assumes that IO unit: support for another block size must +// enforce min(MaxVolumeBytes, (2^32-1)*blockSize) at creation as well. const MaxVolumeBytes uint64 = (16 << 40) - 4096 // ValidateVolumeSize rejects an unsupported capacity before any allocation or From 6de4d89a98cd3953bcd05510ba967f8e56cfeda4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:57:06 -0800 Subject: [PATCH 20/33] chore: keep public PR changes to implementation and tests --- seaweed-block/docs/design/invariants.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index d2e60e38ba..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -469,12 +469,6 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | -### Manifest preparation scan cost - -| ID | Invariant | Transition | Enforced in | Regression/qualification | Model | Status | -|---|---|---|---|---|---|---| -| `INV-CUT-MANIFEST-SCAN-001` | PrepareManifest partitions base references once; each segment compares only its own base group. Unchanged segment identities remain reusable. | M5 Manifest | `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `BenchmarkPrepareManifestUnchangedGroups`; `TestManifest_ReusesUnchangedRangeAndCrashKeepsOldRoot` | Algorithmic cost; no state/transition change to `CutPipeline` | ACTIVE | - ## Part C. Change rules How a fix or a feature is calibrated against this model: From 254f6ba7ee126ffc30d7516fade213e083e6692e Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 22:57:12 -0800 Subject: [PATCH 21/33] chore: keep public PR changes to implementation and tests --- seaweed-block/docs/design/agent-workspace-design.md | 5 +---- seaweed-block/docs/design/invariants.md | 10 ++-------- seaweed-block/docs/spec/README.md | 4 ---- 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/seaweed-block/docs/design/agent-workspace-design.md b/seaweed-block/docs/design/agent-workspace-design.md index 3dc6e97d2d..48b9ca7a58 100644 --- a/seaweed-block/docs/design/agent-workspace-design.md +++ b/seaweed-block/docs/design/agent-workspace-design.md @@ -183,9 +183,6 @@ stateDiagram-v2 ## 6. Snapshots, forks, retention, GC, volume delete -**Create capacity.** New volumes larger than 16 TiB - 4 KiB (17,592,186,040,320 bytes) are refused before provisioning, WAL allocation or durable VOLUME creation. CSI, lifecycle intent, Catalog and local WAL create share the same bound. A fork inherits its source geometry only within the same capacity bound; refusal leaves no parent claim. Existing store-open formats are unchanged. This is static admission, not a new lifecycle state. - - - **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. - **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`. @@ -206,7 +203,7 @@ HEAD states: ```mermaid stateDiagram-v2 - [*] --> active: create within capacity bound (gen 1, epoch 0) or inherited fork HEAD within capacity bound + [*] --> active: initial HEAD (gen 1, epoch 0) or fork HEAD active --> active: holder's cut CAS (gen+1) active --> detached: Detach final cut detached --> active: takeover CAS (higher epoch, new holder) diff --git a/seaweed-block/docs/design/invariants.md b/seaweed-block/docs/design/invariants.md index 8ac60f3c19..b032a37af0 100644 --- a/seaweed-block/docs/design/invariants.md +++ b/seaweed-block/docs/design/invariants.md @@ -229,7 +229,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th | From | To | Guard | Enforced in | Protects | |---|---|---|---|---| -| — | `active` (gen 1, epoch 0) | new volume capacity is at most 16 TiB - 4 KiB before creation; the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | +| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork` | `INV-WS-HEAD-CAS-001` | | `active` | `active` | a holder's cut or a takeover CAS (M4, M5) | `core/frontend/chunkstore/chunk_remote.go` `CASHead` | `INV-WS-HEAD-CAS-001`, `INV-WS-HEAD-MONOTONE-001` | | `active` | `detached` | `Detach` final cut | `core/storage/chunk_layer.go` `chunkLayerImpl.Detach` | `INV-WS-CLEAN-MOVE-001` | | `detached` | `active` | takeover CAS by a new holder at a higher epoch | `core/storage/chunk_restore.go` `ClaimChunkHead` | `INV-WS-CLAIM-BEFORE-SERVE-001` | @@ -247,7 +247,7 @@ 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 | require inherited geometry within the create capacity bound; require inherited geometry within the create capacity bound; 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 | 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` | **Intents and key bindings.** @@ -469,12 +469,6 @@ Notes: |---|---|---|---|---|---|---| | `INV-NVME-H2C-RANGE-001` | An H2CData range exceeding the expected transfer size is refused before slicing, including a uint32 offset-plus-length overflow; an exact-bound payload is preserved. | Frontend H2C receive validation; no storage state transition | `core/frontend/nvme/session.go` `recvH2CData` | `TestRecvH2CDataRangeBounds` (`core/frontend/nvme/h2c_bounds_test.go`) | — | ACTIVE | -### Volume create capacity - -| ID | Invariant | Transition | Enforced in | Regression tests | Model | Status | -|---|---|---|---|---|---|---| -| `INV-VOLUME-CREATE-SIZE-001` | Creation refuses capacity above 16 TiB - 4 KiB before provisioning, allocating a WAL, or persisting a volume record. Geometry checks cannot overflow. | M6 initial create (static parameter admission) | `core/geometry/volume_size.go`; lifecycle `CreateVolume`, CSI `volumeSpecFromCreateRequest`, catalog `EnsureVolume`, `claimForkParent`, storage `CreateWALStoreWithOptions` | `TestCreateVolumeRejectsBeyondUint32LBACap`, `TestCSICreateVolumeCapacityCapBeforeProvision`, `TestEnsureVolumeRejectsBeyondUint32LBACap`, `TestCreateWALStoreRefusesOversizeBeforeFilesystem`, `TestForkRejectsLegacyOversizedGeometry` | Static geometry bound; no protocol state or transition added | ACTIVE | - ## Part C. Change rules How a fix or a feature is calibrated against this model: diff --git a/seaweed-block/docs/spec/README.md b/seaweed-block/docs/spec/README.md index 762dac7cdd..ee2a896216 100644 --- a/seaweed-block/docs/spec/README.md +++ b/seaweed-block/docs/spec/README.md @@ -274,7 +274,3 @@ Recover/reset snapshot recheck and saved-file readers are covered by the native `TestCutCOWV3_*` caller controls, not claimed as model proofs. The earlier thirteen-spec parse statement above predates this imported model; no new independent TLC/parse or cloud run is claimed here. - -### Static volume create capacity - -`INV-VOLUME-CREATE-SIZE-001` bounds a new volume to 16 TiB - 4 KiB. The current ControlPlane/ChunkLifecycle models abstract volume identity and create/delete ordering, not byte capacity or block geometry; this admission bound is not a TLC property. The actual CSI, lifecycle, Catalog and WAL create caller controls in `volume_size_limit_test.go` establish the bound before side effects. No modeled state or action is changed. From 01a118036f75d73175166015de8e8a2cc6335f9b Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:00:20 -0800 Subject: [PATCH 22/33] authority: read the lease view under leaseMu in the renewal refusal (#242) The no-host-validity refusal in RenewWorkspaceLease formatted its error from lv.d.horizon after releasing leaseMu, while the extender (refreshLeaseViewLocked) rewrites the view under leaseMu: a data race. The horizon is now read before the unlock. Test: TestWorkspaceLeaseRefusalReadsTheViewUnderTheLock drives the refusal while the view is republished concurrently; under -race it fails on main (workspace_lease_view.go:174) and passes here. Co-Authored-By: Claude Opus 5.5 --- .../workspace_lease_refusal_race_test.go | 61 +++++++++++++++++++ .../core/authority/workspace_lease_view.go | 3 +- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 seaweed-block/core/authority/workspace_lease_refusal_race_test.go diff --git a/seaweed-block/core/authority/workspace_lease_refusal_race_test.go b/seaweed-block/core/authority/workspace_lease_refusal_race_test.go new file mode 100644 index 0000000000..295989d9cd --- /dev/null +++ b/seaweed-block/core/authority/workspace_lease_refusal_race_test.go @@ -0,0 +1,61 @@ +package authority + +import ( + "context" + "strings" + "sync" + "testing" + "time" +) + +// #242: a renewal refused for lack of host validity formats its error from +// the lease view; that read must happen under leaseMu, because the extender +// (refreshLeaseViewLocked) rewrites the view under leaseMu at any time. +// Run with -race: renewals that take the refusal run while another goroutine +// rewrites the view, as the extender does. +func TestWorkspaceLeaseRefusalReadsTheViewUnderTheLock(t *testing.T) { + disk, _ := newTempStore(t) + c := newTestClock() + p := newLeasePublisher(t, disk, 3*time.Second, c) + bindAndGrant(t, p, "v", "r") + // Force the no-host-validity refusal: the horizon just ahead, a skew + // bound far larger than what is left of it; the granted deadline later. + p.leaseMu.Lock() + lv := p.leaseViews["v"] + lv.d.horizon = c.now().Add(time.Millisecond).UnixNano() + lv.d.maxSkewNS = int64(time.Hour) + lv.deadline = c.now().Add(time.Hour) + p.leaseMu.Unlock() + + const rounds = 200 + var wg sync.WaitGroup + wg.Add(2) + go func() { // the extender's republish: a write of the view under leaseMu + defer wg.Done() + for i := 0; i < rounds; i++ { + p.leaseMu.Lock() + d := lv.d + lv.d = d + p.leaseMu.Unlock() + } + }() + errs := make(chan error, 1) + go func() { + defer wg.Done() + for i := 0; i < rounds; i++ { + if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil || !strings.Contains(err.Error(), "leaves no host validity") { + select { + case errs <- err: + default: + } + return + } + } + }() + wg.Wait() + select { + case err := <-errs: + t.Fatalf("renewal with no host validity: %v; want the refusal", err) + default: + } +} diff --git a/seaweed-block/core/authority/workspace_lease_view.go b/seaweed-block/core/authority/workspace_lease_view.go index bed676e893..6cfc82d8a5 100644 --- a/seaweed-block/core/authority/workspace_lease_view.go +++ b/seaweed-block/core/authority/workspace_lease_view.go @@ -170,8 +170,9 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri // bound, leaseFact) would make the host fence on an invalid reply and lose // its remaining validity; refuse with an error instead. if grant-lv.d.maxSkewNS/2 <= now.UnixNano() { + horizon := lv.d.horizon // the view is leaseMu's: read it before the unlock (#242) p.leaseMu.Unlock() - return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, lv.d.horizon).UTC().Format(time.RFC3339Nano)) + return WorkspaceLease{}, fmt.Errorf("workspace lease: durable horizon %s leaves no host validity", time.Unix(0, horizon).UTC().Format(time.RFC3339Nano)) } if g := time.Unix(0, grant); g.After(lv.deadline) { lv.deadline = g From c4a37fd4a0866e21a1cb1e9322749b3534a47541 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:07:15 -0800 Subject: [PATCH 23/33] test: cover create admission callers and legacy retry --- .../blockvolume/volume_size_admission_test.go | 27 +++++++++++++ .../durable/volume_size_admission_test.go | 38 +++++++++++++++++++ .../core/lifecycle/legacy_size_retry_test.go | 35 +++++++++++++++++ .../parallelwal/volume_size_limit_test.go | 23 +++++++++++ .../smartwal/volume_size_limit_test.go | 23 +++++++++++ 5 files changed, 146 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/volume_size_admission_test.go create mode 100644 seaweed-block/core/frontend/durable/volume_size_admission_test.go create mode 100644 seaweed-block/core/lifecycle/legacy_size_retry_test.go create mode 100644 seaweed-block/core/storage/parallelwal/volume_size_limit_test.go create mode 100644 seaweed-block/core/storage/smartwal/volume_size_limit_test.go diff --git a/seaweed-block/cmd/blockvolume/volume_size_admission_test.go b/seaweed-block/cmd/blockvolume/volume_size_admission_test.go new file mode 100644 index 0000000000..495e326770 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/volume_size_admission_test.go @@ -0,0 +1,27 @@ +package main + +import ( + "strconv" + "strings" + "testing" +) + +func TestDurableCreateFlagsValidateOriginalGeometry(t *testing.T) { + if strconv.IntSize < 64 { + t.Skip("64-bit CLI uint overflow case") + } + for _, blocks := range []string{"4294967297", "18446744073709551615"} { + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks="+blocks) + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "durable-blocks") { + t.Fatalf("blocks %s: %v", blocks, err) + } + } + args := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-blocks=4294967295", "--durable-blocksize=4096") + if _, err := parseFlags(args); err != nil { + t.Fatal(err) + } + args = append(args, "--durable-blocksize=8192") + if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("oversize geometry: %v", err) + } +} diff --git a/seaweed-block/core/frontend/durable/volume_size_admission_test.go b/seaweed-block/core/frontend/durable/volume_size_admission_test.go new file mode 100644 index 0000000000..32e1b149f7 --- /dev/null +++ b/seaweed-block/core/frontend/durable/volume_size_admission_test.go @@ -0,0 +1,38 @@ +package durable_test + +import ( + "context" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestProviderCreateCapacityPrecedesFreshMarker(t *testing.T) { + root := t.TempDir() + id := frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1} + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: ^uint32(0), BlockSize: 8192, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return storage.NewMemChunkRemote(), nil }}, newStubView(healthyProj(id))) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + // Invalid parent guarantees no giant allocation even when admission is removed. + parent := filepath.Join(root, "v1.bin.chunkfresh") + if err := os.Mkdir(parent, 0700); err != nil { + t.Fatal(err) + } + _, err = p.Open(context.Background(), "v1") + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("want capacity before marker, got %v", err) + } + entries, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "v1.bin.chunkfresh" { + t.Fatalf("refused create wrote files: %v", entries) + } +} diff --git a/seaweed-block/core/lifecycle/legacy_size_retry_test.go b/seaweed-block/core/lifecycle/legacy_size_retry_test.go new file mode 100644 index 0000000000..133310042d --- /dev/null +++ b/seaweed-block/core/lifecycle/legacy_size_retry_test.go @@ -0,0 +1,35 @@ +package lifecycle + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestLegacyOversizeIdenticalCreateRetry(t *testing.T) { + dir := t.TempDir() + spec := VolumeSpec{VolumeID: "legacy", SizeBytes: 17592186044416, ReplicationFactor: 1} + data, err := json.Marshal(VolumeRecord{Spec: spec}) + if err != nil { + t.Fatal(err) + } + if err = os.WriteFile(filepath.Join(dir, "legacy.json"), data, 0600); err != nil { + t.Fatal(err) + } + s, err := OpenFileStore(dir) + if err != nil { + t.Fatal(err) + } + got, err := s.CreateVolume(spec) + if err != nil { + t.Fatalf("existing identical intent must remain retryable: %v", err) + } + if got.Spec.SizeBytes != spec.SizeBytes { + t.Fatal("existing size changed") + } + spec.VolumeID = "new-oversize" + if _, err = s.CreateVolume(spec); err == nil { + t.Fatal("new oversize admitted") + } +} diff --git a/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go b/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go new file mode 100644 index 0000000000..13efe63057 --- /dev/null +++ b/seaweed-block/core/storage/parallelwal/volume_size_limit_test.go @@ -0,0 +1,23 @@ +package parallelwal + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCreateCapacityBeforeFilesystem(t *testing.T) { + parent := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil { + t.Fatal(err) + } + s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) + if s != nil { + s.Close() + t.Fatal("created oversized image") + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("capacity must precede filesystem: %v", err) + } +} diff --git a/seaweed-block/core/storage/smartwal/volume_size_limit_test.go b/seaweed-block/core/storage/smartwal/volume_size_limit_test.go new file mode 100644 index 0000000000..406ecb4710 --- /dev/null +++ b/seaweed-block/core/storage/smartwal/volume_size_limit_test.go @@ -0,0 +1,23 @@ +package smartwal + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestCreateCapacityBeforeFilesystem(t *testing.T) { + parent := filepath.Join(t.TempDir(), "file") + if err := os.WriteFile(parent, []byte("unchanged"), 0600); err != nil { + t.Fatal(err) + } + s, err := CreateStore(filepath.Join(parent, "volume"), ^uint32(0), 8192) + if s != nil { + s.Close() + t.Fatal("created oversized image") + } + if err == nil || !strings.Contains(err.Error(), "16 TiB - 4 KiB") { + t.Fatalf("capacity must precede filesystem: %v", err) + } +} From 9e809120f4a8df1264d71baa8e69532528f97e37 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:08:47 -0800 Subject: [PATCH 24/33] fix: admit original geometry before every durable create --- seaweed-block/cmd/blockvolume/main.go | 6 ++++++ seaweed-block/core/frontend/durable/provider.go | 5 +++++ seaweed-block/core/geometry/volume_size.go | 15 +++++++++++++++ seaweed-block/core/lifecycle/store.go | 6 +++--- seaweed-block/core/storage/parallelwal/store.go | 4 ++++ seaweed-block/core/storage/smartwal/store.go | 4 ++++ 6 files changed, 37 insertions(+), 3 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 96935591bd..198216a2c1 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -9,6 +9,7 @@ import ( "errors" "flag" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "net" "os" "os/exec" @@ -270,6 +271,11 @@ func parseFlags(args []string) (flags, error) { return flags{}, fmt.Errorf("--durable-wal-recovery-test-disable-flusher requires --durable-impl=walstore") } } + if f.durableRoot != "" { + if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil { + return flags{}, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err) + } + } if f.iscsiCHAPUser == "" { f.iscsiCHAPUser = os.Getenv("SW_BLOCK_ISCSI_CHAP_USERNAME") } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 1b9f8e565f..0f1c1cb6ef 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -28,6 +28,7 @@ import ( "context" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "io" "log" "os" @@ -596,6 +597,10 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { } return h, nil } + // Existing storage ignores create geometry; admission precedes all fresh sidecars. + if err := geometry.ValidateBlockGeometry(uint64(p.cfg.NumBlocks), uint64(p.cfg.BlockSize)); err != nil { + return nil, err + } if p.cfg.Impl == ImplWALStoreChunk { // Durable before the volume file exists: a crash anywhere between // here and the first successful attach leaves a fresh volume. diff --git a/seaweed-block/core/geometry/volume_size.go b/seaweed-block/core/geometry/volume_size.go index 0d7aaeea92..a1e941e327 100644 --- a/seaweed-block/core/geometry/volume_size.go +++ b/seaweed-block/core/geometry/volume_size.go @@ -16,3 +16,18 @@ func ValidateVolumeSize(size uint64) error { } return nil } + +// ValidateBlockGeometry checks the original values before narrowing or I/O. +func ValidateBlockGeometry(blocks, blockSize uint64) error { + if blocks > uint64(^uint32(0)) { + return fmt.Errorf("block count %d exceeds uint32", blocks) + } + if blockSize == 0 || blockSize > uint64(^uint32(0)) { + return fmt.Errorf("invalid block size %d", blockSize) + } + // Division prevents an oversized product from wrapping before admission. + if blocks > MaxVolumeBytes/blockSize { + return fmt.Errorf("volume geometry %d x %d exceeds maximum %d bytes (16 TiB - 4 KiB; uint32 LBA)", blocks, blockSize, MaxVolumeBytes) + } + return nil +} diff --git a/seaweed-block/core/lifecycle/store.go b/seaweed-block/core/lifecycle/store.go index 5e3c4fea32..89b1e6ae66 100644 --- a/seaweed-block/core/lifecycle/store.go +++ b/seaweed-block/core/lifecycle/store.go @@ -108,9 +108,6 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { if err := validateSpec(spec); err != nil { return VolumeRecord{}, err } - if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil { - return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err) - } s.mu.Lock() defer s.mu.Unlock() if existing, ok := s.records[spec.VolumeID]; ok { @@ -129,6 +126,9 @@ func (s *FileStore) CreateVolume(spec VolumeSpec) (VolumeRecord, error) { } return existing, nil } + if err := geometry.ValidateVolumeSize(spec.SizeBytes); err != nil { + return VolumeRecord{}, fmt.Errorf("%w: %w", ErrInvalidVolumeSpec, err) + } rec := VolumeRecord{Spec: spec} if err := s.putLocked(rec); err != nil { return VolumeRecord{}, err diff --git a/seaweed-block/core/storage/parallelwal/store.go b/seaweed-block/core/storage/parallelwal/store.go index f27add8f3c..c604f7263c 100644 --- a/seaweed-block/core/storage/parallelwal/store.go +++ b/seaweed-block/core/storage/parallelwal/store.go @@ -7,6 +7,7 @@ import ( "bytes" "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "io" "os" "path/filepath" @@ -134,6 +135,9 @@ func CreateStore(path string, numBlocks uint32, blockSize int) (*Store, error) { func CreateStoreWithConfig(path string, cfg Config) (*Store, error) { cfg = normalizeConfig(cfg) + if err := geometry.ValidateBlockGeometry(uint64(cfg.NumBlocks), uint64(cfg.BlockSize)); err != nil { + return nil, err + } h, err := headerForConfig(cfg) if err != nil { return nil, err diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index 56673d9993..2332b66d95 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -3,6 +3,7 @@ package smartwal import ( "errors" "fmt" + "github.com/seaweedfs/seaweed-block/core/geometry" "hash/crc32" "log" "os" @@ -90,6 +91,9 @@ func CreateStoreWithSlots(path string, numBlocks uint32, blockSize int, walSlots if blockSize == 0 { blockSize = storage.DefaultBlockSize } + if err := geometry.ValidateBlockGeometry(uint64(numBlocks), uint64(blockSize)); err != nil { + return nil, err + } if walSlots == 0 { walSlots = defaultWALSlots } From a9a2cfa9366297c3263688715c77d1d3a517f50f Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:10:20 -0800 Subject: [PATCH 25/33] style: group create-admission imports --- seaweed-block/cmd/blockvolume/main.go | 2 +- seaweed-block/core/frontend/durable/provider.go | 2 +- .../core/frontend/durable/volume_size_admission_test.go | 9 +++++---- seaweed-block/core/storage/parallelwal/store.go | 2 +- seaweed-block/core/storage/smartwal/store.go | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index 198216a2c1..c21b8ae94c 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -9,7 +9,6 @@ import ( "errors" "flag" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "net" "os" "os/exec" @@ -28,6 +27,7 @@ import ( "github.com/seaweedfs/seaweed-block/core/frontend/nvme" "github.com/seaweedfs/seaweed-block/core/frontend/nvmerdma" "github.com/seaweedfs/seaweed-block/core/frontend/ublk" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/host/volume" "github.com/seaweedfs/seaweed-block/core/recovery" "github.com/seaweedfs/seaweed-block/core/replication" diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index 0f1c1cb6ef..b08c345d4d 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -28,7 +28,6 @@ import ( "context" "errors" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "io" "log" "os" @@ -39,6 +38,7 @@ import ( "time" "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" "github.com/seaweedfs/seaweed-block/core/storage/parallelwal" "github.com/seaweedfs/seaweed-block/core/storage/smartwal" diff --git a/seaweed-block/core/frontend/durable/volume_size_admission_test.go b/seaweed-block/core/frontend/durable/volume_size_admission_test.go index 32e1b149f7..5120e2951b 100644 --- a/seaweed-block/core/frontend/durable/volume_size_admission_test.go +++ b/seaweed-block/core/frontend/durable/volume_size_admission_test.go @@ -2,13 +2,14 @@ package durable_test import ( "context" - "github.com/seaweedfs/seaweed-block/core/frontend" - "github.com/seaweedfs/seaweed-block/core/frontend/durable" - "github.com/seaweedfs/seaweed-block/core/storage" "os" "path/filepath" "strings" "testing" + + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" ) func TestProviderCreateCapacityPrecedesFreshMarker(t *testing.T) { @@ -19,7 +20,7 @@ func TestProviderCreateCapacityPrecedesFreshMarker(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { p.Close() }) - // Invalid parent guarantees no giant allocation even when admission is removed. + // A blocked marker path prevents a giant allocation even without admission. parent := filepath.Join(root, "v1.bin.chunkfresh") if err := os.Mkdir(parent, 0700); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/storage/parallelwal/store.go b/seaweed-block/core/storage/parallelwal/store.go index c604f7263c..863b8795ac 100644 --- a/seaweed-block/core/storage/parallelwal/store.go +++ b/seaweed-block/core/storage/parallelwal/store.go @@ -7,7 +7,6 @@ import ( "bytes" "errors" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "io" "os" "path/filepath" @@ -15,6 +14,7 @@ import ( "sync" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" ) diff --git a/seaweed-block/core/storage/smartwal/store.go b/seaweed-block/core/storage/smartwal/store.go index 2332b66d95..e054fa170e 100644 --- a/seaweed-block/core/storage/smartwal/store.go +++ b/seaweed-block/core/storage/smartwal/store.go @@ -3,7 +3,6 @@ package smartwal import ( "errors" "fmt" - "github.com/seaweedfs/seaweed-block/core/geometry" "hash/crc32" "log" "os" @@ -12,6 +11,7 @@ import ( "sync/atomic" "time" + "github.com/seaweedfs/seaweed-block/core/geometry" "github.com/seaweedfs/seaweed-block/core/storage" ) From 1e5fe198e366bc87a73aa0d6b9d4bd4d130403e9 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:36:38 -0800 Subject: [PATCH 26/33] test: preserve existing-volume create-geometry compatibility --- .../existing_geometry_compat_test.go | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go diff --git a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go new file mode 100644 index 0000000000..d4515923c9 --- /dev/null +++ b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go @@ -0,0 +1,64 @@ +package main + +import ( + "bytes" + "context" + "path/filepath" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/storage" +) + +func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) { + root := t.TempDir() + s, err := storage.CreateWALStore(filepath.Join(root, "v1.bin"), 16, 4096) + if err != nil { + t.Fatal(err) + } + want := bytes.Repeat([]byte{0x73}, 4096) + if _, err = s.Write(0, want); err != nil { + s.Close() + t.Fatal(err) + } + if _, err = s.Sync(); err != nil { + s.Close() + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967295", "--durable-blocksize=8192") + f, err := parseFlags(args) + if err != nil { + t.Fatalf("existing storage must ignore create-only geometry: %v", err) + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: uint32(f.durableBlocks), BlockSize: int(f.durableBlockSize)}, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + result, _, err := openAndRecoverDurable(p, &spyHost{}, "v1", 5*time.Second) + if err != nil || result != durableStartupReady { + t.Fatalf("existing recovery: %v %v", result, err) + } + st, err := p.EnsureStorage("v1") + if err != nil { + t.Fatal(err) + } + if st.NumBlocks() != 16 || st.BlockSize() != 4096 { + t.Fatalf("existing geometry changed: %d x %d", st.NumBlocks(), st.BlockSize()) + } + got := make([]byte, 4096) + b, err := p.Open(context.Background(), "v1") + if err != nil { + t.Fatal(err) + } + if _, err = b.Read(context.Background(), 0, got); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatal("existing bytes changed") + } +} From d102a1c1a302088ae03dd6843f5dba01fca70649 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:37:14 -0800 Subject: [PATCH 27/33] fix: admit geometry only when creating durable storage --- seaweed-block/cmd/blockvolume/main.go | 31 ++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/main.go b/seaweed-block/cmd/blockvolume/main.go index c21b8ae94c..df27929c40 100644 --- a/seaweed-block/cmd/blockvolume/main.go +++ b/seaweed-block/cmd/blockvolume/main.go @@ -272,8 +272,8 @@ func parseFlags(args []string) (flags, error) { } } if f.durableRoot != "" { - if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil { - return flags{}, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err) + if _, _, err := durableCreateGeometry(f); err != nil { + return flags{}, err } } if f.iscsiCHAPUser == "" { @@ -529,6 +529,22 @@ type nvmeReadyLine struct { SubsysNQN string `json:"subsys_nqn"` } +// durableCreateGeometry leaves existing volumes in open-only mode. If the +// observed file disappears before Open, NumBlocks=0 prevents a replacement +// from being created using narrowed or otherwise ignored CLI values. +func durableCreateGeometry(f flags) (uint32, int, error) { + path := filepath.Join(f.durableRoot, f.volumeID+".bin") + if _, err := os.Stat(path); err == nil { + return 0, 0, nil + } else if !os.IsNotExist(err) { + return 0, 0, fmt.Errorf("durable volume geometry: %w", err) + } + if err := geometry.ValidateBlockGeometry(uint64(f.durableBlocks), uint64(f.durableBlockSize)); err != nil { + return 0, 0, fmt.Errorf("--durable-blocks/--durable-blocksize: %w", err) + } + return uint32(f.durableBlocks), int(f.durableBlockSize), nil +} + func run(f flags) int { readyCh := make(chan adapter.AssignmentInfo, 16) @@ -597,11 +613,12 @@ func run(f flags) int { var durableProv *durable.DurableProvider var workspaceRemoteFor func(string) (storage.ChunkRemote, error) if f.durableRoot != "" { + blocks, blockSize, geometryErr := durableCreateGeometry(f) cfg := durable.ProviderConfig{ Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, - BlockSize: int(f.durableBlockSize), - NumBlocks: uint32(f.durableBlocks), + BlockSize: blockSize, + NumBlocks: blocks, WALRetentionLSNs: f.walRetentionLSNs, WALMultiBlockRecords: f.durableWALMultiBlockRecords, WALRecoveryTestDisableFlusher: f.durableWALRecoveryTestDisableFlusher, @@ -621,7 +638,11 @@ func run(f flags) int { defer chunk.close() } } - dp, err := durable.NewDurableProvider(cfg, h.ProjectionView()) + var dp *durable.DurableProvider + err := geometryErr + if err == nil { + dp, err = durable.NewDurableProvider(cfg, h.ProjectionView()) + } if chunkErr != nil { err = chunkErr } From 4055e403eaab9a0d36fa76fa4ddda9fa604664a4 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:38:06 -0800 Subject: [PATCH 28/33] test: cover open-only geometry and disappearance race --- .../existing_geometry_compat_test.go | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go index d4515923c9..d87189a0bb 100644 --- a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go +++ b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go @@ -3,6 +3,7 @@ package main import ( "bytes" "context" + "os" "path/filepath" "testing" "time" @@ -34,7 +35,14 @@ func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) { if err != nil { t.Fatalf("existing storage must ignore create-only geometry: %v", err) } - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: uint32(f.durableBlocks), BlockSize: int(f.durableBlockSize)}, healthyView{}) + blocks, blockSize, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("existing file must select open-only mode") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplName(f.durableImpl), StorageRoot: f.durableRoot, NumBlocks: blocks, BlockSize: blockSize}, healthyView{}) if err != nil { t.Fatal(err) } @@ -62,3 +70,43 @@ func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) { t.Fatal("existing bytes changed") } } + +func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "v1.bin") + s, err := storage.CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967297")) + if err != nil { + t.Fatal(err) + } + blocks, bs, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("not open-only") + } + if err = os.Remove(path); err != nil { + t.Fatal(err) + } + if _, _, err = durableCreateGeometry(f); err == nil { + t.Fatal("fresh recheck accepted original overflowing count") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, NumBlocks: blocks, BlockSize: bs}, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err = p.EnsureStorage("v1"); err == nil { + t.Fatal("created replacement from ignored flags") + } + if _, err = os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("replacement file exists: %v", err) + } +} From 9f46fb8d7d543067409576f36e52ef048f6ba036 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Wed, 18 Nov 2026 23:41:12 -0800 Subject: [PATCH 29/33] test: workspace-lease family waits by progress, not wall-clock bounds (#227) - core/host/master TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore: each lease write is held until a renewal succeeded during the hold (slowness by progress), three held writes must complete, a sampler records any fence; replaces the 2.5 s sleeps and the 10 s watch. A renewal that waited for the store would let the guard lapse and fail the test at once. - TestWorkspaceHeldRenewalBoundary, TestWorkspaceMoveRestoresLazilyAndFencesOldHost: the test context has no wall-clock bound (3 s / 10 s); each step completes or the go test timeout reports the hang. The guard's own RPC timeout stays. - core/authority TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose: wait for the held extension write and for renewals under it by progress (were 5 s / 2 s bounds); joins after release unchanged. - waitExtenders joins the finite extenders without a 10 s bound. Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 25 ++--- .../master/workspace_renewal_boundary_test.go | 4 +- .../workspace_renewal_slowstore_test.go | 93 +++++++++++++------ .../host/master/workspace_restore_test.go | 5 +- 4 files changed, 81 insertions(+), 46 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index ee90181d43..2f9425b76c 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -83,15 +83,12 @@ func bindAndGrant(t *testing.T, p *Publisher, volume, replica string) WorkspaceL // waitExtenders joins every admitted extender (tests only; no concurrent // admission while waiting). +// waitExtenders joins every admitted extender. No wall-clock bound (#227): +// extenders are finite (each makes at most one store write), so the join is +// the progress condition; a hang is reported by the go test timeout. func waitExtenders(t *testing.T, p *Publisher) { t.Helper() - done := make(chan struct{}) - go func() { p.extWG.Wait(); close(done) }() - select { - case <-done: - case <-time.After(10 * time.Second): - t.Fatal("extenders did not finish") - } + p.extWG.Wait() } // assertLeaseViewMatches checks INV-LEASE-VIEW-001: with p.mu held, every @@ -731,17 +728,15 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } // Handshake 1: the first extension write is held inside the store. - select { - case <-heldEntered: - case <-time.After(5 * time.Second): - t.Fatal("no horizon-extension write reached the store within 5 s") - } + <-heldEntered // progress, no timer (#227): renewers keep triggering extensions // Handshake 2: renewals keep succeeding while it is held. var atHold [n]int64 for _, i := range eligible { atHold[i] = grants[i].Load() } - for wait := time.Now().Add(2 * time.Second); ; time.Sleep(5 * time.Millisecond) { + // Progress, no timer (#227): every eligible volume gains a grant while the + // extension write is held. Renewals that waited for it would never return. + for { all := true for _, i := range eligible { if grants[i].Load() <= atHold[i] { @@ -751,9 +746,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { if all { break } - if time.Now().After(wait) { - t.Fatal("renewals did not succeed while an extension write was held") - } + time.Sleep(5 * time.Millisecond) } // Writers and Close start while the extension write is held. writersStarted = true diff --git a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go index b128642338..4cf6c385c3 100644 --- a/seaweed-block/core/host/master/workspace_renewal_boundary_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_boundary_test.go @@ -69,7 +69,9 @@ func TestWorkspaceHeldRenewalBoundary(t *testing.T) { if err != nil { t.Fatal(err) } - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + // No wall-clock bound on the test context (#227): the held client + // is released by the test; only the guard's own RPC timeout remains. + ctx, cancel := context.WithCancel(context.Background()) defer cancel() if err := g.Refresh(ctx); err != nil { t.Fatal(err) diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go index 8f86648d5a..36c7d9cac4 100644 --- a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -14,17 +14,41 @@ import ( "google.golang.org/grpc" ) -// slowGuardStore delays every workspace-lease Put once armed (issue #205). +// slowGuardStore holds every workspace-lease Put, once armed, until a lease +// renewal has succeeded after the Put entered (issue #205): a slow store write, +// with the slowness defined by progress instead of a fixed sleep. type slowGuardStore struct { authority.AuthorityStore - delayNS atomic.Int64 - puts atomic.Int64 // delayed (armed) lease writes: proves the stall was exercised + armed atomic.Bool + renewals atomic.Int64 // successful renewals seen by the client + kick chan struct{} // a renewal succeeded (buffered 1) + stop chan struct{} // closed at cleanup: frees any held Put + held atomic.Int64 // lease writes that were held and then completed +} + +func newSlowGuardStore(s authority.AuthorityStore) *slowGuardStore { + return &slowGuardStore{AuthorityStore: s, kick: make(chan struct{}, 1), stop: make(chan struct{})} +} + +func (s *slowGuardStore) renewed() { + s.renewals.Add(1) + select { + case s.kick <- struct{}{}: + default: + } } func (s *slowGuardStore) Put(r authority.DurableRecord) error { - if d := time.Duration(s.delayNS.Load()); d > 0 && r.Workspace != nil && r.Workspace.Lease != nil { - s.puts.Add(1) - time.Sleep(d) + if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil { + base := s.renewals.Load() + for s.renewals.Load() <= base { + select { + case <-s.kick: + case <-s.stop: + return s.AuthorityStore.Put(r) + } + } + defer s.held.Add(1) } return s.AuthorityStore.Put(r) } @@ -35,6 +59,7 @@ func (s *slowGuardStore) Put(r authority.DurableRecord) error { type deadlineLeaseClient struct { p *authority.Publisher inflight *sync.WaitGroup + slow *slowGuardStore // optional: told about each successful renewal } func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) { @@ -55,6 +80,9 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro }() select { case r := <-done: + if r.err == nil && c.slow != nil { + c.slow.renewed() + } return r.fact, r.err case <-ctx.Done(): return nil, ctx.Err() @@ -74,10 +102,11 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { if err != nil { t.Fatal(err) } - slow := &slowGuardStore{AuthorityStore: disk} + slow := newSlowGuardStore(disk) var inflight sync.WaitGroup t.Cleanup(func() { - slow.delayNS.Store(0) + slow.armed.Store(false) + close(slow.stop) inflight.Wait() if err := disk.Close(); err != nil { t.Error(err) @@ -89,7 +118,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { seedSkewPublisher(t, p, dir) var stops atomic.Int32 g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, - deadlineLeaseClient{p: p, inflight: &inflight}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, + deadlineLeaseClient{p: p, inflight: &inflight, slow: slow}, &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r", Epoch: 1}, func(context.Context) (uint64, error) { stops.Add(1); return 7, nil }, nil) if err != nil { t.Fatal(err) @@ -99,29 +128,39 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { go func() { runDone <- g.Run(ctx) }() t.Cleanup(func() { cancel() - select { - case <-runDone: - case <-time.After(10 * time.Second): - t.Error("guard did not settle") - } + <-runDone // Run returns on cancel; the go test timeout bounds a hang }) - for wait := time.Now().Add(3 * time.Second); !g.Projection().Healthy; time.Sleep(20 * time.Millisecond) { - if time.Now().After(wait) { - t.Fatal("first grant did not arrive") + for !g.Projection().Healthy { // progress: the first grant + time.Sleep(20 * time.Millisecond) + } + + // Every lease write is now held until a renewal succeeded during its hold, + // so a renewal that waited for the store would deadlock this test. The + // sampler records any fence while armed; three held writes must complete. + var fenced atomic.Bool + sampled := make(chan struct{}) + slow.armed.Store(true) + go func() { + defer close(sampled) + for slow.armed.Load() { + if !g.Projection().Healthy || stops.Load() != 0 { + fenced.Store(true) + } + time.Sleep(20 * time.Millisecond) } - } - slow.delayNS.Store(int64(2500 * time.Millisecond)) - start := time.Now() - for time.Since(start) < 10*time.Second { - if !g.Projection().Healthy || stops.Load() != 0 { - t.Fatalf("guard fenced %s after the store slowed to 2.5 s per write (stop calls %d)", time.Since(start).Round(time.Millisecond), stops.Load()) + }() + for slow.held.Load() < 3 { + if fenced.Load() { + break } - time.Sleep(50 * time.Millisecond) + time.Sleep(20 * time.Millisecond) } - if slow.puts.Load() == 0 { - t.Fatal("no lease write went through the 2.5 s stall: the test did not exercise it") + slow.armed.Store(false) + <-sampled + if fenced.Load() || !g.Projection().Healthy || stops.Load() != 0 { + t.Fatalf("guard fenced while lease writes were held behind renewals (held=%d renewals=%d stops=%d)", slow.held.Load(), slow.renewals.Load(), stops.Load()) } - t.Logf("guard stayed healthy for 10 s; %d lease writes took 2.5 s each", slow.puts.Load()) + t.Logf("guard stayed healthy through %d held lease writes (%d renewals)", slow.held.Load(), slow.renewals.Load()) } // A durable deletion-reservation write of an unrelated volume must not block diff --git a/seaweed-block/core/host/master/workspace_restore_test.go b/seaweed-block/core/host/master/workspace_restore_test.go index ac7ddbd188..95282bf1c2 100644 --- a/seaweed-block/core/host/master/workspace_restore_test.go +++ b/seaweed-block/core/host/master/workspace_restore_test.go @@ -6,7 +6,6 @@ import ( "reflect" "sync/atomic" "testing" - "time" "github.com/seaweedfs/seaweed-block/core/authority" "github.com/seaweedfs/seaweed-block/core/frontend" @@ -33,7 +32,9 @@ func (r *restoreRemote) Get(ctx context.Context, key string) ([]byte, error) { // Keep the old projection stale to model delayed assignment delivery; a HEAD // takeover must independently refuse its cut and then stop its frontend I/O. func TestWorkspaceMoveRestoresLazilyAndFencesOldHost(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + // No wall-clock bound (#227): each step completes or the go test timeout + // reports the hang; a 10 s context failed the HEAD claim under load. + ctx, cancel := context.WithCancel(context.Background()) defer cancel() m := newTestMaster(t, t.TempDir()) defer closeTestMaster(t, m) From 7116f6dbf881aaa43bf29b7a35a14bce30769ed2 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:02:05 -0800 Subject: [PATCH 30/33] test: #247 review fold: release before join; credit only renewals started under the hold - master slow store: each held Put takes a generation; a renewal is credited with the generation it read before its call, so a reply computed before the hold never releases it. slow.release() runs as the first cleanup, so a held Put cannot block the publisher/extender joins after a failure. - authority WritersExtendersClose: only grants of calls that started after the extension write was held count (flag set before the hold blocks). Co-Authored-By: Claude Opus 5.5 --- .../authority/workspace_lease_horizon_test.go | 18 +++++--- .../workspace_renewal_slowstore_test.go | 44 ++++++++++++++----- 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/seaweed-block/core/authority/workspace_lease_horizon_test.go b/seaweed-block/core/authority/workspace_lease_horizon_test.go index 2f9425b76c..128cfc0291 100644 --- a/seaweed-block/core/authority/workspace_lease_horizon_test.go +++ b/seaweed-block/core/authority/workspace_lease_horizon_test.go @@ -619,6 +619,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { var holdOnce, releaseOnce sync.Once releaseHold := func() { releaseOnce.Do(func() { close(heldRelease) }) } var classifying atomic.Bool + var holding atomic.Bool // set when the extension write is held, before it blocks hs.setBefore(func(r DurableRecord) error { time.Sleep(5 * time.Millisecond) // a slow store if !classifying.Load() || r.Workspace == nil || r.Workspace.Lease == nil { @@ -637,6 +638,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { first := false holdOnce.Do(func() { first = true }) if first { + holding.Store(true) // before the hold: a renewal started after this saw it close(heldEntered) <-heldRelease } @@ -665,6 +667,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { classifying.Store(true) var grants [n]atomic.Int64 + var underHold [n]atomic.Int64 // grants of calls that started while the extension write was held var maxGrant [n]atomic.Int64 var slowest atomic.Int64 stop := make(chan struct{}) @@ -711,6 +714,7 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { return default: } + fresh := holding.Load() // the call starts while the extension write is held start := time.Now() l, err := p.RenewWorkspaceLease(ctx, vol(i), "r", 1) if d := int64(time.Since(start)); d > slowest.Load() { @@ -718,6 +722,9 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { } if err == nil && !l.Revoking { grants[i].Add(1) + if fresh { + underHold[i].Add(1) + } if l.ExpiresAtNS > maxGrant[i].Load() { maxGrant[i].Store(l.ExpiresAtNS) } @@ -730,16 +737,13 @@ func TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose(t *testing.T) { // Handshake 1: the first extension write is held inside the store. <-heldEntered // progress, no timer (#227): renewers keep triggering extensions // Handshake 2: renewals keep succeeding while it is held. - var atHold [n]int64 - for _, i := range eligible { - atHold[i] = grants[i].Load() - } - // Progress, no timer (#227): every eligible volume gains a grant while the - // extension write is held. Renewals that waited for it would never return. + // Progress, no timer (#227): every eligible volume gains a grant from a call + // that STARTED while the extension write was held (a reply computed before + // the hold does not count). Renewals that waited for it would never return. for { all := true for _, i := range eligible { - if grants[i].Load() <= atHold[i] { + if underHold[i].Load() == 0 { all = false } } diff --git a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go index 36c7d9cac4..a00a3d48ca 100644 --- a/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go +++ b/seaweed-block/core/host/master/workspace_renewal_slowstore_test.go @@ -15,23 +15,42 @@ import ( ) // slowGuardStore holds every workspace-lease Put, once armed, until a lease -// renewal has succeeded after the Put entered (issue #205): a slow store write, -// with the slowness defined by progress instead of a fixed sleep. +// renewal that STARTED after the Put entered has succeeded (issue #205): a slow +// store write, with the slowness defined by progress instead of a fixed sleep. +// Each held Put takes a generation; a renewal is credited with the generation +// it observed before its call, so a reply computed before the hold never +// releases it. type slowGuardStore struct { authority.AuthorityStore armed atomic.Bool + gen atomic.Int64 // generation of the latest held Put + credited atomic.Int64 // highest generation a fresh renewal was started under renewals atomic.Int64 // successful renewals seen by the client kick chan struct{} // a renewal succeeded (buffered 1) - stop chan struct{} // closed at cleanup: frees any held Put - held atomic.Int64 // lease writes that were held and then completed + stop chan struct{} // closed by release(): frees any held Put + stopOnce sync.Once + held atomic.Int64 // lease writes that were held and then completed } func newSlowGuardStore(s authority.AuthorityStore) *slowGuardStore { return &slowGuardStore{AuthorityStore: s, kick: make(chan struct{}, 1), stop: make(chan struct{})} } -func (s *slowGuardStore) renewed() { +// release disarms and frees every held Put; idempotent. +func (s *slowGuardStore) release() { + s.armed.Store(false) + s.stopOnce.Do(func() { close(s.stop) }) +} + +// renewed credits a successful renewal that started under generation g. +func (s *slowGuardStore) renewed(g int64) { s.renewals.Add(1) + for { + c := s.credited.Load() + if g <= c || s.credited.CompareAndSwap(c, g) { + break + } + } select { case s.kick <- struct{}{}: default: @@ -40,8 +59,8 @@ func (s *slowGuardStore) renewed() { func (s *slowGuardStore) Put(r authority.DurableRecord) error { if s.armed.Load() && r.Workspace != nil && r.Workspace.Lease != nil { - base := s.renewals.Load() - for s.renewals.Load() <= base { + g := s.gen.Add(1) + for s.credited.Load() < g { select { case <-s.kick: case <-s.stop: @@ -67,6 +86,10 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro fact *control.WorkspaceLeaseFact err error } + var g int64 + if c.slow != nil { + g = c.slow.gen.Load() // a reply can only release holds that entered before this call + } done := make(chan result, 1) c.inflight.Add(1) go func() { @@ -81,7 +104,7 @@ func (c deadlineLeaseClient) RenewWorkspaceLease(ctx context.Context, id *contro select { case r := <-done: if r.err == nil && c.slow != nil { - c.slow.renewed() + c.slow.renewed(g) } return r.fact, r.err case <-ctx.Done(): @@ -105,8 +128,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { slow := newSlowGuardStore(disk) var inflight sync.WaitGroup t.Cleanup(func() { - slow.armed.Store(false) - close(slow.stop) + slow.release() inflight.Wait() if err := disk.Close(); err != nil { t.Error(err) @@ -115,6 +137,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { dir := &skewDirective{asks: make(chan authority.AssignmentAsk, 1)} p := authority.NewPublisher(dir, authority.WithStore(slow), authority.WithWorkspaceLeaseConfig(6*time.Second, nil)) t.Cleanup(p.CloseWorkspaceExtenders) // join extenders before the store closes + t.Cleanup(slow.release) // runs before the join above: frees a held Put first seedSkewPublisher(t, p, dir) var stops atomic.Int32 g, err := volume.NewWorkspaceLeaseGuard(workspaceRPCView{frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}}, @@ -130,6 +153,7 @@ func TestWorkspaceLeaseGuardSurvivesSlowAuthorityStore(t *testing.T) { cancel() <-runDone // Run returns on cancel; the go test timeout bounds a hang }) + t.Cleanup(slow.release) // first of all cleanups: a held Put never blocks the joins for !g.Projection().Healthy { // progress: the first grant time.Sleep(20 * time.Millisecond) } From 608046e6cba86e563b336ec61205e9b3675445d3 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 00:33:10 -0800 Subject: [PATCH 31/33] fix: refuse missing open-only volumes before fresh sidecars --- .../existing_geometry_compat_test.go | 88 +++++++++++-------- .../core/frontend/durable/provider.go | 3 + 2 files changed, 56 insertions(+), 35 deletions(-) diff --git a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go index d87189a0bb..332bb0b8ff 100644 --- a/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go +++ b/seaweed-block/cmd/blockvolume/existing_geometry_compat_test.go @@ -3,8 +3,10 @@ package main import ( "bytes" "context" + "errors" "os" "path/filepath" + "strconv" "testing" "time" @@ -72,41 +74,57 @@ func TestExistingDurableVolumeIgnoresCreateGeometry(t *testing.T) { } func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing.T) { - root := t.TempDir() - path := filepath.Join(root, "v1.bin") - s, err := storage.CreateWALStore(path, 16, 4096) - if err != nil { - t.Fatal(err) + if strconv.IntSize < 64 { + t.Skip("64-bit CLI uint overflow case") } - if err = s.Close(); err != nil { - t.Fatal(err) - } - f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl=walstore", "--durable-blocks=4294967297")) - if err != nil { - t.Fatal(err) - } - blocks, bs, err := durableCreateGeometry(f) - if err != nil { - t.Fatal(err) - } - if blocks != 0 { - t.Fatal("not open-only") - } - if err = os.Remove(path); err != nil { - t.Fatal(err) - } - if _, _, err = durableCreateGeometry(f); err == nil { - t.Fatal("fresh recheck accepted original overflowing count") - } - p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStore, StorageRoot: root, NumBlocks: blocks, BlockSize: bs}, healthyView{}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { p.Close() }) - if _, err = p.EnsureStorage("v1"); err == nil { - t.Fatal("created replacement from ignored flags") - } - if _, err = os.Stat(path); !os.IsNotExist(err) { - t.Fatalf("replacement file exists: %v", err) + for _, impl := range []durable.ImplName{durable.ImplWALStore, durable.ImplWALStoreChunk} { + t.Run(string(impl), func(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "v1.bin") + s, err := storage.CreateWALStore(path, 16, 4096) + if err != nil { + t.Fatal(err) + } + if err = s.Close(); err != nil { + t.Fatal(err) + } + args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl="+string(impl), "--durable-blocks=4294967297") + if impl == durable.ImplWALStoreChunk { + args = append(args, "--chunk-filer=127.0.0.1:18888") + } + f, err := parseFlags(args) + if err != nil { + t.Fatal(err) + } + blocks, bs, err := durableCreateGeometry(f) + if err != nil { + t.Fatal(err) + } + if blocks != 0 { + t.Fatal("not open-only") + } + if err = os.Remove(path); err != nil { + t.Fatal(err) + } + if _, _, err = durableCreateGeometry(f); err == nil { + t.Fatal("fresh recheck accepted original overflowing count") + } + p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: impl, StorageRoot: root, NumBlocks: blocks, BlockSize: bs, ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { + return nil, errors.New("unexpected remote access for missing open-only volume") + }}, healthyView{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { p.Close() }) + if _, err = p.EnsureStorage("v1"); err == nil { + t.Fatal("created replacement from ignored flags") + } + if _, err = os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("replacement file exists: %v", err) + } + if _, err = os.Stat(path + ".chunkfresh"); !os.IsNotExist(err) { + t.Fatalf("open-only refusal left a fresh marker: %v", err) + } + }) } } diff --git a/seaweed-block/core/frontend/durable/provider.go b/seaweed-block/core/frontend/durable/provider.go index b08c345d4d..f2d3ac7f2b 100644 --- a/seaweed-block/core/frontend/durable/provider.go +++ b/seaweed-block/core/frontend/durable/provider.go @@ -598,6 +598,9 @@ func (p *DurableProvider) openOrCreate(volumeID string) (*volHandle, error) { return h, nil } // Existing storage ignores create geometry; admission precedes all fresh sidecars. + if p.cfg.NumBlocks == 0 { + return nil, fmt.Errorf("durable: NumBlocks=0; cannot create storage for %s (use open-existing mode)", volumeID) + } if err := geometry.ValidateBlockGeometry(uint64(p.cfg.NumBlocks), uint64(p.cfg.BlockSize)); err != nil { return nil, err } From 898c0fd046e92c8fcc08ebe906840c2741038478 Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:11:19 -0800 Subject: [PATCH 32/33] master: test the exited-holder recovery path (forced move, then delete) A holder that exits never detaches or ACKs, so its live authority keeps a volume delete refused. The existing path recovers it: after the lease horizon plus skew a forced move grants epoch+1 on another host, which claims HEAD, serves the last cut and writes past it, then detaches with a clean ACK, after which the delete is admitted and later renewals and moves are refused. Real master runtime and providers, in-memory remote. Co-Authored-By: Claude Opus 5.5 --- .../master/workspace_exited_holder_test.go | 215 ++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 seaweed-block/core/host/master/workspace_exited_holder_test.go diff --git a/seaweed-block/core/host/master/workspace_exited_holder_test.go b/seaweed-block/core/host/master/workspace_exited_holder_test.go new file mode 100644 index 0000000000..f3061b39f0 --- /dev/null +++ b/seaweed-block/core/host/master/workspace_exited_holder_test.go @@ -0,0 +1,215 @@ +package master + +import ( + "bytes" + "context" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweed-block/core/authority" + "github.com/seaweedfs/seaweed-block/core/frontend" + "github.com/seaweedfs/seaweed-block/core/frontend/durable" + "github.com/seaweedfs/seaweed-block/core/lifecycle" + control "github.com/seaweedfs/seaweed-block/core/rpc/control" + "github.com/seaweedfs/seaweed-block/core/storage" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// A holder that exited never detaches or ACKs, so its live authority blocks +// a volume delete. The existing path recovers the volume: after the lease +// horizon plus skew a forced move grants epoch+1 on another host, that +// host claims HEAD and serves the last cut, then detaches with a clean ACK, +// and the delete is admitted. Real master runtime, real providers, the +// in-memory ChunkRemote (read by the master through a HEAD reader). +func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + remote := storage.NewMemChunkRemote() + reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) { + h, err := remote.GetHead(ctx) + if err != nil { + return authority.WorkspaceHead{}, err + } + return authority.WorkspaceHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, Detached: h.State == storage.ChunkHeadDetached}, nil + } + const skew = 100 * time.Millisecond + m, err := New(Config{WorkspaceMaxClockSkew: skew, Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true, WorkspaceHeadReader: reader}) + if err != nil { + t.Fatal(err) + } + m.Start() + defer closeTestMaster(t, m) + conn, err := grpc.NewClient(m.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + ws, lc := control.NewWorkspaceServiceClient(conn), control.NewLifecycleServiceClient(conn) + + // vol-a placed on node-a as r1; node-b is a prepared target. + for _, server := range []string{"node-a", "node-b"} { + if _, err = m.Lifecycle().Nodes.RegisterNode(lifecycle.NodeRegistration{ServerID: server, DataAddr: "127.0.0.1:9200", CtrlAddr: "127.0.0.1:9100"}); err != nil { + t.Fatal(err) + } + } + if _, err = lc.CreateVolume(ctx, &control.CreateVolumeRequest{VolumeId: "vol-a", SizeBytes: 1 << 20, ReplicationFactor: 1}); err != nil { + t.Fatal(err) + } + src := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-a", DataAddr: "127.0.0.1:19200", CtrlAddr: "127.0.0.1:19100"} + dst := &control.WorkspaceBinding{VolumeId: "vol-a", ServerId: "node-b", DataAddr: "127.0.0.1:29200", CtrlAddr: "127.0.0.1:29100"} + for _, b := range []*control.WorkspaceBinding{src, dst} { + if _, err = ws.RegisterWorkspaceBinding(ctx, b); err != nil { + t.Fatal(err) + } + } + if _, err = ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "vol-a", ServerId: "node-a", ReplicaId: "r1"}); err != nil { + t.Fatal(err) + } + if _, err = control.NewObservationServiceClient(conn).ReportHeartbeat(ctx, &control.HeartbeatReport{ServerId: "node-a", SentAt: timestamppb.Now(), Reachable: true, Eligible: true, + Slots: []*control.HeartbeatSlot{{VolumeId: "vol-a", ReplicaId: "r1", DataAddr: src.DataAddr, CtrlAddr: src.CtrlAddr}}}); err != nil { + t.Fatal(err) + } + if _, err = m.RunLifecycleProductTick(); err != nil { + t.Fatal(err) + } + oldLine := waitAuthorityLine(t, m.Publisher(), "vol-a") + oldID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: oldLine.ReplicaID, Epoch: oldLine.Epoch} + if _, err = ws.RenewWorkspaceLease(ctx, oldID); err != nil { + t.Fatal(err) + } + + open := func(host string, line authority.AuthorityBasis) (*durable.DurableProvider, frontend.Backend) { + t.Helper() + p, err := durable.NewDurableProvider(durable.ProviderConfig{ + Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, + ChunkHolder: host + "/" + line.ReplicaID, + ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil }, + }, restoreProjection{frontend.Projection{VolumeID: "vol-a", ReplicaID: line.ReplicaID, Epoch: line.Epoch, EndpointVersion: line.EndpointVersion, Healthy: true}}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = p.Close() }) + if _, err := p.EnsureStorage("vol-a"); err != nil { + t.Fatal(err) + } + if _, err := p.RecoverVolume(ctx, "vol-a"); err != nil { + t.Fatalf("%s recovery: %v", host, err) + } + b, err := p.Open(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + return p, b + } + + // The holder writes, cuts, then exits without detaching or ACKing. + oldProvider, oldBackend := open("node-a", oldLine) + want := bytes.Repeat([]byte{0xE1}, 4096) + if n, err := oldBackend.Write(ctx, 8*4096, want); err != nil || n != len(want) { + t.Fatal(n, err) + } + if err := oldBackend.Sync(ctx); err != nil { + t.Fatal(err) + } + cut, err := oldProvider.CaptureVolume(ctx, "vol-a") + if err != nil { + t.Fatal(err) + } + if err := oldProvider.Close(); err != nil { + t.Fatal(err) + } + head, err := remote.GetHead(ctx) + if err != nil || head.RemoteLSN != cut || head.State == storage.ChunkHeadDetached { + t.Fatalf("HEAD after the holder exited: %+v %v", head, err) + } + + // The exited holder's live authority blocks the delete and a clean move. + if _, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-early"}); err == nil || !strings.Contains(err.Error(), "live authority requires clean revocation ACK") { + t.Fatalf("delete under the exited holder's live authority: %v; want the clean revocation ACK refusal", err) + } + move := &control.WorkspaceMove{RequestId: "clean-1", VolumeId: "vol-a", ExpectedReplicaId: "r1", ExpectedEpoch: oldLine.Epoch, TargetReplicaId: "r1", + TargetServerId: "node-b", TargetDataAddr: dst.DataAddr, TargetCtrlAddr: dst.CtrlAddr, Kind: "clean"} + if _, err := ws.MoveWorkspace(ctx, move); err == nil { + t.Fatal("clean move granted without the holder's detach and ACK") + } + move.RequestId, move.Kind, move.Force = "forced-1", "forced", true + if _, err := ws.MoveWorkspace(ctx, move); err == nil { + t.Fatal("forced move granted before the lease horizon plus skew") + } + + // After the durable lease horizon plus skew, the forced move is granted. + horizon := int64(0) + if st := m.Publisher().WorkspaceState("vol-a"); st != nil && st.Lease != nil { + horizon = st.Lease.ExpiresAtNS + } + if horizon == 0 { + t.Fatal("no lease horizon recorded") + } + select { + case <-time.After(time.Until(time.Unix(0, horizon)) + skew + 20*time.Millisecond): + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } + grant, err := ws.MoveWorkspace(ctx, move) + if err != nil { + t.Fatal("forced move after the horizon:", err) + } + newLine, ok := m.Publisher().VolumeAuthorityLine("vol-a") + if !grant.Issued || grant.NewEpoch != oldLine.Epoch+1 || !ok || newLine.Epoch != grant.NewEpoch || grant.HeadGen != head.Gen || grant.RemoteLsn != cut { + t.Fatalf("forced grant %+v line %+v; want epoch %d bound to HEAD gen %d lsn %d", grant, newLine, oldLine.Epoch+1, head.Gen, cut) + } + if _, err := ws.RenewWorkspaceLease(ctx, oldID); err == nil { + t.Fatal("the exited holder's authority renewed after the forced move") + } + + // The new host claims HEAD, serves the last cut and continues past it. + newProvider, newBackend := open("node-b", newLine) + claimed, err := remote.GetHead(ctx) + if err != nil || claimed.Epoch != newLine.Epoch || claimed.Holder != "node-b/r1" || claimed.RemoteLSN != cut || claimed.State == storage.ChunkHeadDetached { + t.Fatalf("HEAD after the new host's recovery: %+v %v", claimed, err) + } + got := make([]byte, len(want)) + if n, err := newBackend.Read(ctx, 8*4096, got); err != nil || n != len(got) || !bytes.Equal(got, want) { + t.Fatalf("new host read of the last cut: n=%d err=%v", n, err) + } + if n, err := newBackend.Write(ctx, 0, bytes.Repeat([]byte{0xE2}, 4096)); err != nil || n != 4096 { + t.Fatal(n, err) + } + if err := newBackend.Sync(ctx); err != nil { + t.Fatal(err) + } + if newCut, err := newProvider.CaptureVolume(ctx, "vol-a"); err != nil || newCut <= cut { + t.Fatalf("new host cut %d err %v; want past %d", newCut, err, cut) + } + + // The new holder detaches cleanly and ACKs; the delete is then admitted. + newID := &control.WorkspaceIdentity{VolumeId: "vol-a", ReplicaId: newLine.ReplicaID, Epoch: newLine.Epoch} + if _, err := ws.RenewWorkspaceLease(ctx, newID); err != nil { + t.Fatal(err) + } + if _, err := ws.RevokeWorkspace(ctx, newID); err != nil { + t.Fatal(err) + } + detached, _, err := newProvider.DetachVolume(ctx, "vol-a") + if err != nil || detached.Head.State != storage.ChunkHeadDetached { + t.Fatalf("detach: %+v %v", detached.Head, err) + } + if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: newID, HeadGen: detached.Head.Gen}); err != nil { + t.Fatal(err) + } + res, err := lc.MarkVolumeDeleting(ctx, &control.MarkVolumeDeletingRequest{VolumeId: "vol-a", Token: "del-1"}) + if err != nil || !res.GetKnown() || res.GetState() != lifecycle.ReservationAdmitted { + t.Fatalf("delete after the clean ACK: %+v %v", res, err) + } + if _, err := ws.RenewWorkspaceLease(ctx, newID); err == nil { + t.Fatal("authority renewed after the delete was admitted") + } + move.RequestId, move.ExpectedEpoch = "forced-2", newLine.Epoch + // The RPC refuses first; publication admission refuses it again behind it. + if _, err := ws.MoveWorkspace(ctx, move); err == nil || !strings.Contains(err.Error(), "workspace: volume is being deleted") { + t.Fatalf("move after the delete was admitted: %v; want the RPC's deletion refusal", err) + } +} From 966384d2a803ff8e1940cf2918a26fd9798aaf6d Mon Sep 17 00:00:00 2001 From: pingqiu Date: Thu, 19 Nov 2026 01:23:19 -0800 Subject: [PATCH 33/33] master: give the exited-holder test room after the lease horizon The test waits out the real ~45 s horizon; a 60 s budget left ~15 s for the takeover, cut, detach and delete, which load and -race exceeded. Co-Authored-By: Claude Opus 5.5 --- .../core/host/master/workspace_exited_holder_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/seaweed-block/core/host/master/workspace_exited_holder_test.go b/seaweed-block/core/host/master/workspace_exited_holder_test.go index f3061b39f0..7e066b6f6b 100644 --- a/seaweed-block/core/host/master/workspace_exited_holder_test.go +++ b/seaweed-block/core/host/master/workspace_exited_holder_test.go @@ -25,7 +25,9 @@ import ( // and the delete is admitted. Real master runtime, real providers, the // in-memory ChunkRemote (read by the master through a HEAD reader). func TestWorkspaceExitedHolderForcedMoveThenCleanDelete(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + // The real lease horizon (1.5 x the 30 s TTL) plus skew takes ~45 s of + // this budget; the rest must cover the work after it under load and -race. + ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second) defer cancel() remote := storage.NewMemChunkRemote() reader := func(ctx context.Context, _ string) (authority.WorkspaceHead, error) {