Merge remote-tracking branch 'origin/main' into feat/host-urgent-pending

# Conflicts:
#	docs/design/invariants.md
This commit is contained in:
pingqiu committed 2026-11-22 01:32:40 -08:00
commit bd1c8bdb1d
41 files changed
+2285 -95

No files matched your search

@@ -0,0 +1,38 @@
package main
import (
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
)
// The capture floor is durable.MinCaptureInterval: 5 minutes by default,
// so 60 s is refused; a program that sets it to 30 s before parsing flags
// accepts 30 s and refuses 29 s. The refusal names the floor in force.
func TestCaptureIntervalFloor(t *testing.T) {
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1")
parse := func(iv string) error {
_, err := parseFlags(append(append([]string{}, base...), "--chunk-capture-interval="+iv))
return err
}
if durable.MinCaptureInterval != 5*time.Minute {
t.Fatalf("default floor %s, want 5m", durable.MinCaptureInterval)
}
if err := parse("60s"); err == nil || !strings.Contains(err.Error(), "at least 5m0s") {
t.Fatalf("60 s under the default floor: %v", err)
}
if err := parse("5m"); err != nil {
t.Fatalf("5m refused: %v", err)
}
old := durable.MinCaptureInterval
durable.MinCaptureInterval = 30 * time.Second
defer func() { durable.MinCaptureInterval = old }()
if err := parse("30s"); err != nil {
t.Fatalf("30 s under a 30 s floor: %v", err)
}
if err := parse("29s"); err == nil || !strings.Contains(err.Error(), "at least 30s") {
t.Fatalf("29 s under a 30 s floor: %v", err)
}
}
@@ -88,8 +88,8 @@ func validateChunkFlags(f flags) error {
if c.maintenanceInterval < 0 {
return errors.New("--chunk-maintenance-interval must not be negative")
}
if c.captureInterval > 0 && c.captureInterval < 5*time.Minute {
return errors.New("--chunk-capture-interval must be 0 or at least 5m")
if c.captureInterval > 0 && c.captureInterval < durable.MinCaptureInterval {
return fmt.Errorf("--chunk-capture-interval must be 0 or at least %s", durable.MinCaptureInterval)
}
if c.captureInterval < 0 {
return fmt.Errorf("--chunk-capture-interval=%s must not be negative", c.captureInterval)
@@ -52,6 +52,7 @@ func TestWALStoreChunkFlags(t *testing.T) {
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"),
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"),
"below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"),
"60 s in an OSS build": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=60s"),
"negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"),
"negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"),
"chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"),
+1 -1
View File
@@ -203,7 +203,7 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.chunk.replication, "chunk-replication", "", "walstore-chunk: replication for chunk needles (empty = filer default / storage rule)")
fs.Bool("chunk-detach-plain-supported", false, "capability: supports idle plain=true on /chunk/detach (no-op flag)")
fs.BoolVar(&f.chunk.detachPrecopy, "chunk-detach-precopy", false, "walstore-chunk: not supported in this release; blockvolume refuses to start when it is set")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least 5m)")
fs.DurationVar(&f.chunk.captureInterval, "chunk-capture-interval", defaultChunkCaptureInterval, "walstore-chunk: periodic HEAD capture interval (default 0: off; when set, at least "+durable.MinCaptureInterval.String()+")")
f.chunk.snapshotSchedule = defaultSnapshotSchedule
fs.Var(&f.chunk.snapshotSchedule, "chunk-snapshot-schedule", "walstore-chunk: scheduled snapshots, daily:N or weekly:N (once per period at a per-volume offset, the newest N kept) or off")
fs.DurationVar(&f.chunk.maintenanceInterval, "chunk-maintenance-interval", defaultChunkMaintenanceInterval, "walstore-chunk: retention and optional GC pass interval; 0 disables")
+14 -4
View File
@@ -259,14 +259,15 @@ func chunkSnapshot(args []string, stdout, stderr io.Writer) int {
func chunkDetach(args []string, stdout, stderr io.Writer) int {
fs := chunkFlagSet("detach", stderr)
var (
volumeID, statusAddr string
timeout time.Duration
frozen, allowOverBudget bool
freezeStartedAtNs int64
volumeID, statusAddr string
timeout time.Duration
plain, frozen, allowOverBudget bool
freezeStartedAtNs int64
)
fs.StringVar(&volumeID, "volume", "", "volume id")
fs.StringVar(&statusAddr, "status-addr", "", "blockvolume status address or URL (with --chunk-control-endpoint)")
fs.DurationVar(&timeout, "timeout", 120*time.Second, "operation bound (capped at the server's OpDeadline)")
fs.BoolVar(&plain, "plain", false, "seal an idle volume without pre-copy; prints JSON headGen as sealed HEAD generation on stderr")
fs.BoolVar(&frozen, "frozen", false, "not supported in this release: the server refuses a frozen detach (frozen_detach_unsupported)")
fs.Int64Var(&freezeStartedAtNs, "freeze-started-at-ns", 0, "not supported in this release; only valid with --frozen")
fs.BoolVar(&allowOverBudget, "allow-over-budget", false, "not supported in this release; only valid with --frozen")
@@ -276,10 +277,19 @@ func chunkDetach(args []string, stdout, stderr io.Writer) int {
if volumeID == "" || statusAddr == "" {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--volume and --status-addr are required", false)
}
// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: an idle seal has
// its own finite caller bound and cannot encode frozen policy fields.
if plain && (timeout <= 0 || frozen || freezeStartedAtNs != 0 || allowOverBudget || fs.NArg() != 0) {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--plain requires positive --timeout, no extra arguments and no frozen options", false)
}
if (frozen && freezeStartedAtNs <= 0) || (!frozen && (freezeStartedAtNs != 0 || allowOverBudget)) {
return chunkFail("detach", stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, "--frozen requires --freeze-started-at-ns; --allow-over-budget requires --frozen", false)
}
body := map[string]any{"volumeID": volumeID}
if plain {
body["plain"] = true
return chunkPlainDetachPost(statusAddr, volumeID, timeout, body, stdout, stderr)
}
if frozen {
body["frozen"] = true
body["freezeStartedAtNs"] = freezeStartedAtNs
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"time"
"github.com/seaweedfs/seaweed-block/core/ops"
)
// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001. Keep stdout JSON
// unchanged; the separate human readout identifies the seal to the operator.
func chunkPlainDetachPost(addr, volume string, timeout time.Duration, body map[string]any, stdout, stderr io.Writer) int {
var out bytes.Buffer
code := chunkPost("detach", addr, "/chunk/detach", timeout, body, &out, stderr)
if code != ops.VolumeStatusExitOK {
if err := writeAll(stdout, out.Bytes()); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err)
}
return code
}
var seal struct {
VolumeID string `json:"volumeID"`
HeadGen uint64 `json:"headGen"`
}
if err := json.Unmarshal(out.Bytes(), &seal); err != nil || seal.VolumeID != volume || seal.HeadGen == 0 {
return chunkFail("detach", stdout, stderr, chunkExitFailed, codeInternalCLI, "plain detach outcome unknown: reply has no matching volume and sealed HEAD generation", false)
}
if err := writeAll(stdout, out.Bytes()); err != nil {
fmt.Fprintf(stderr, "sw-block ops chunk detach: write result: %v\n", err)
return chunkExitFailed
}
fmt.Fprintf(stderr, "sealed HEAD generation: %d\n", seal.HeadGen)
return ops.VolumeStatusExitOK
}
@@ -0,0 +1,52 @@
package main
import (
"net/http"
"strings"
"testing"
)
// M5 PlainStop -> Quiesce, INV-CUT-PLAIN-DETACH-001: encode the existing
// idle seal request; preserve JSON stdout for existing operator tooling.
func TestOpsChunkPlainDetachSendsTheExistingRequest(t *testing.T) {
const reply = `{"volumeID":"vol","headGen":11}`
srv, got := chunkServer(t, http.StatusOK, reply)
code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL, "--timeout", "2s")
if code != 0 || out != reply || !strings.Contains(errOut, "sealed HEAD generation: 11\n") {
t.Fatalf("exit=%d stdout=%q stderr=%q", code, out, errOut)
}
if len(*got) != 1 || (*got)[0].path != "/chunk/detach" || (*got)[0].body["plain"] != true || (*got)[0].body["volumeID"] != "vol" || (*got)[0].body["timeoutMs"] != float64(2000) {
t.Fatalf("plain request=%+v", *got)
}
for _, key := range []string{"frozen", "freezeStartedAtNs", "allowOverBudget"} {
if _, ok := (*got)[0].body[key]; ok {
t.Fatalf("plain request contains %s", key)
}
}
}
func TestOpsChunkPlainDetachRefusesInvalidMixBeforeHTTP(t *testing.T) {
srv, got := chunkServer(t, http.StatusOK, `{}`)
for _, extra := range [][]string{
{"--frozen", "--freeze-started-at-ns", "1"}, {"--freeze-started-at-ns", "1"}, {"--allow-over-budget"},
{"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"},
} {
args := append([]string{"detach", "--plain", "--volume", "vol", "--status-addr", srv.URL}, extra...)
if code, _, _ := runChunk(args...); code != 2 || len(*got) != 0 {
t.Fatalf("%v: exit=%d requests=%d", extra, code, len(*got))
}
}
}
func TestOpsChunkPlainDetachPreservesTypedFailure(t *testing.T) {
for _, reason := range []string{"busy", "fenced", "outcome_unknown"} {
t.Run(reason, func(t *testing.T) {
reply := `{"code":"` + reason + `","message":"seal refused","retryable":true}`
srv, got := chunkServer(t, http.StatusConflict, reply)
code, out, errOut := runChunk("detach", "--plain", "--volume", "vol", "--status-addr", srv.URL)
if code != 1 || out != reply || len(*got) != 1 || strings.Contains(errOut, "sealed HEAD generation:") {
t.Fatalf("exit=%d stdout=%q stderr=%q requests=%d", code, out, errOut, len(*got))
}
})
}
}
+23 -1
View File
@@ -25,6 +25,11 @@ const (
)
const workspaceUsage = `usage:
sw-block ops workspace show --master ADDR --volume V [--timeout 30s]
sw-block ops workspace revoke --master ADDR --volume V --replica R --epoch E
(--sealed-gen G | --without-seal) [--timeout 30s]
sw-block ops workspace move --clean --master ADDR --volume V --replica R --epoch E
--target-host H --target-data A --target-ctrl A --request-id ID [--timeout 30s]
sw-block ops workspace force-move --master ADDR --volume V --target-host H --target-data A --target-ctrl A
--request-id ID --confirm-forced V@EPOCH [--dry-run] [--timeout 30s]
sw-block ops workspace lost-range --master ADDR --volume V [--request-id ID] [--timeout 30s]
@@ -35,7 +40,18 @@ starting the volume on the target host is the next step, done separately. The
blockmaster admits it only once the holder's lease horizon and its granted or
restart deadline, each plus the clock-skew bound, have passed; before that it is
refused and this command says when it becomes admissible. There is NO bypass
flag. Clean (detached) moves are not offered here.
flag.
Planned hand-over order: stop the writer; ops chunk detach --plain; revoke
--sealed-gen G; show until the recorded ACK names the same replica, epoch and
HEAD generation G; move --clean; start blockvolume on the target separately.
Revoke only requests revocation: it does not prove an ACK. --sealed-gen is
an operator assertion, not checked against storage by this CLI. --without-seal
deliberately abandons the unpublished tail and may require a forced move.
The clean target may be the source host once sealed (requires server support).
On an unknown move outcome, rerun with the SAME --request-id.
Show is read-only. Lease state uses the master's reported host validity at
query time, not a comparison with this machine's clock; it is not a grant.
--confirm-forced must be exactly <volume>@<expected epoch>, retyped: the epoch
is the holder's epoch the move is sent against, and the master refuses it when
@@ -65,6 +81,12 @@ func runOpsWorkspace(args []string, stdout, stderr io.Writer) int {
return wsExitRefusedLocally
}
switch args[0] {
case "show":
return runWorkspaceShow(args[1:], stdout, stderr)
case "move":
return runWorkspaceCleanMove(args[1:], stdout, stderr)
case "revoke":
return runWorkspaceRevoke(args[1:], stdout, stderr)
case "force-move":
return runWorkspaceForceMove(args[1:], stdout, stderr)
case "lost-range":
@@ -0,0 +1,60 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
// M2 Acked -> Moved (clean), INV-WS-CLEAN-MOVE-001: encode only; do not
// synthesize a seal/ACK, release a lease or start the target here.
func runWorkspaceCleanMove(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block ops workspace move", flag.ContinueOnError)
fs.SetOutput(stderr)
var q control.WorkspaceMove
var master string
var clean bool
var timeout time.Duration
fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port")
fs.StringVar(&q.VolumeId, "volume", "", "volume id")
fs.StringVar(&q.ExpectedReplicaId, "replica", "", "current logical replica id")
fs.Uint64Var(&q.ExpectedEpoch, "epoch", 0, "current holder epoch")
fs.StringVar(&q.RequestId, "request-id", "", "operator-supplied move id; reuse on unknown outcome")
fs.StringVar(&q.TargetServerId, "target-host", "", "target node; may be the source host once sealed (requires server support)")
fs.StringVar(&q.TargetDataAddr, "target-data", "", "target data address host:port")
fs.StringVar(&q.TargetCtrlAddr, "target-ctrl", "", "target control address host:port")
fs.BoolVar(&clean, "clean", false, "required: move using the detached HEAD and matching recorded host ACK")
fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC")
if err := fs.Parse(args); err != nil {
return wsExitRefusedLocally
}
if fs.NArg() != 0 || !clean || master == "" || q.VolumeId == "" || q.ExpectedReplicaId == "" || q.ExpectedEpoch == 0 || q.RequestId == "" || q.TargetServerId == "" || q.TargetDataAddr == "" || q.TargetCtrlAddr == "" || timeout <= 0 {
fmt.Fprintln(stderr, "workspace move: refused locally; --clean, --master, --volume, --replica, positive --epoch/--timeout, --request-id and target host/data/ctrl are required")
return wsExitRefusedLocally
}
q.Kind, q.TargetReplicaId = "clean", q.ExpectedReplicaId
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace move: refused locally, nothing sent: %v\n", err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
g, err := c.CleanMove(ctx, &q)
if err != nil {
fmt.Fprintf(stderr, "workspace move: %v\n", err)
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintf(stderr, "workspace move: outcome unknown; rerun with the SAME --request-id %s\n", q.RequestId)
}
return workspaceExit(wsclient.OutcomeOf(err))
}
fmt.Fprintf(stdout, "clean move issued: volume %s request %s: %s@%d -> %s@%d on %s (sealed HEAD gen %d, remote LSN %d)\n", g.GetVolumeId(), g.GetRequestId(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetNewHost(), g.GetHeadGen(), g.GetRemoteLsn())
fmt.Fprintf(stdout, "next: start volume %s on %s (this command moved authority only)\n", g.GetVolumeId(), g.GetNewHost())
return wsExitOK
}
@@ -0,0 +1,100 @@
package main
import (
"strings"
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func cleanMoveArgs(addr string, extra ...string) []string {
return append([]string{"ops", "workspace", "move", "--clean", "--master", addr, "--volume", "vol", "--replica", "r1", "--epoch", "3", "--request-id", "clean-1", "--target-host", "node-b", "--target-data", "10.0.0.2:3260", "--target-ctrl", "10.0.0.2:9100"}, extra...)
}
func cleanGrant(q *control.WorkspaceMove) *control.WorkspaceGrant {
g := wsGrant(q)
g.Kind, g.LostRange = "clean", nil
return g
}
// Existing M2 Acked -> Moved (clean), INV-WS-CLEAN-MOVE-001.
func TestWorkspaceCleanMoveSendsOnlyTheExplicitCleanRequest(t *testing.T) {
f := &fakeWorkspace{move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
if q.GetKind() != "clean" || q.GetForce() || q.GetVolumeId() != "vol" || q.GetRequestId() != "clean-1" || q.GetExpectedReplicaId() != "r1" || q.GetExpectedEpoch() != 3 || q.GetTargetReplicaId() != "r1" || q.GetTargetServerId() != "node-b" || q.GetTargetDataAddr() != "10.0.0.2:3260" || q.GetTargetCtrlAddr() != "10.0.0.2:9100" {
t.Errorf("clean request=%+v", q)
}
return cleanGrant(q), nil
}}
addr, _ := startFakeWorkspace(t, f)
for i := 0; i < 2; i++ {
code, out, errOut := runCLI(cleanMoveArgs(addr))
if code != wsExitOK || !strings.Contains(out, "clean move issued") || !strings.Contains(out, "clean-1") || !strings.Contains(out, "start") || strings.Contains(out, "no loss") {
t.Fatalf("exit=%d out=%q err=%q", code, out, errOut)
}
}
if f.total() != 2 || f.n("MoveWorkspace") != 2 {
t.Fatalf("unexpected orchestration calls=%d", f.total())
}
}
func TestWorkspaceCleanMoveRefusesBadInputBeforeDial(t *testing.T) {
f := &fakeWorkspace{}
addr, dials := startFakeWorkspace(t, f)
for _, extra := range [][]string{{"--clean=false"}, {"--master", ""}, {"--volume", ""}, {"--replica", ""}, {"--epoch", "0"}, {"--request-id", ""}, {"--target-host", ""}, {"--target-data", ""}, {"--target-ctrl", ""}, {"--timeout", "0s"}, {"--force"}, {"unexpected"}} {
if code, _, _ := runCLI(cleanMoveArgs(addr, extra...)); code != wsExitRefusedLocally || *dials != 0 || f.total() != 0 {
t.Fatalf("%v: exit=%d dials=%d calls=%d", extra, code, *dials, f.total())
}
}
}
func TestWorkspaceCleanMoveRejectsMismatchedGrant(t *testing.T) {
for _, tc := range []struct {
name string
edit func(*control.WorkspaceGrant)
}{
{"unissued", func(g *control.WorkspaceGrant) { g.Issued = false }},
{"forced", func(g *control.WorkspaceGrant) { g.Kind = "forced" }},
{"request", func(g *control.WorkspaceGrant) { g.RequestId = "other" }},
{"volume", func(g *control.WorkspaceGrant) { g.VolumeId = "other" }},
{"replica", func(g *control.WorkspaceGrant) { g.OldReplicaId = "other" }},
{"old_epoch", func(g *control.WorkspaceGrant) { g.OldEpoch++ }},
{"target_replica", func(g *control.WorkspaceGrant) { g.NewReplicaId = "other" }},
{"target_host", func(g *control.WorkspaceGrant) { g.NewHost = "other" }},
{"new_epoch", func(g *control.WorkspaceGrant) { g.NewEpoch = g.OldEpoch }},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeWorkspace{move: func(q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
g := cleanGrant(q)
tc.edit(g)
return g, nil
}}
addr, _ := startFakeWorkspace(t, f)
code, out, errOut := runCLI(cleanMoveArgs(addr))
if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "SAME --request-id clean-1") {
t.Fatalf("exit=%d out=%q err=%q", code, out, errOut)
}
})
}
}
func TestWorkspaceCleanMovePreservesRefusalAndUnknown(t *testing.T) {
for _, tc := range []struct {
name string
err error
want int
}{
{"unsealed_or_no_ack", status.Error(codes.FailedPrecondition, "HEAD not sealed or acknowledgement missing"), wsExitRefused},
{"lost_reply", status.Error(codes.Unavailable, "reply lost"), wsExitUnknown},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeWorkspace{move: func(*control.WorkspaceMove) (*control.WorkspaceGrant, error) { return nil, tc.err }}
addr, _ := startFakeWorkspace(t, f)
code, out, errOut := runCLI(cleanMoveArgs(addr))
if code != tc.want || out != "" || (tc.want == wsExitUnknown && !strings.Contains(errOut, "SAME --request-id clean-1")) {
t.Fatalf("exit=%d out=%q err=%q", code, out, errOut)
}
})
}
}
@@ -0,0 +1,67 @@
package main
import (
"context"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/authority"
"github.com/seaweedfs/seaweed-block/core/host/master"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// Existing M2 Granted -> Revoking -> Acked -> Moved (clean),
// INV-WS-CLEAN-MOVE-001: real RPC admission still requires the host ACK.
// HEAD reading is supplied by the existing master seam; no lab is involved.
func TestWorkspacePlannedHandoffAgainstRealMaster(t *testing.T) {
h, stop := startDeleteMaster(t, master.Config{
Listen: "127.0.0.1:0", AuthorityStoreDir: t.TempDir(), LifecycleStoreDir: t.TempDir(), WorkspaceRPC: true,
WorkspaceHeadReader: func(context.Context, string) (authority.WorkspaceHead, error) {
return authority.WorkspaceHead{Gen: 9, Epoch: 1, Holder: "node-a/r1", RemoteLSN: 42, Detached: true}, nil
},
})
defer stop()
seedForcedVolume(t, h)
show := []string{"ops", "workspace", "show", "--master", h.Addr(), "--volume", "vol-f"}
if code, out, errOut := runCLI(show); code != 0 || !strings.Contains(out, "holder: r1@1") || !strings.Contains(out, "recorded ACK: none") {
t.Fatalf("initial show: exit=%d out=%q err=%q", code, out, errOut)
}
revoke := []string{"ops", "workspace", "revoke", "--master", h.Addr(), "--volume", "vol-f", "--replica", "r1", "--epoch", "1", "--sealed-gen", "9"}
if code, out, errOut := runCLI(revoke); code != 0 {
t.Fatalf("revoke: exit=%d out=%q err=%q", code, out, errOut)
}
move := []string{"ops", "workspace", "move", "--clean", "--master", h.Addr(), "--volume", "vol-f", "--replica", "r1", "--epoch", "1", "--request-id", "clean-actual", "--target-host", "node-b", "--target-data", "127.0.0.1:29200", "--target-ctrl", "127.0.0.1:29100"}
if code, _, errOut := runCLI(move); code != wsExitRefused {
t.Fatalf("move without host ACK: exit=%d err=%q", code, errOut)
}
conn, err := grpc.NewClient(h.Addr(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// This is the separate host event, never synthesized by the CLI.
_, err = control.NewWorkspaceServiceClient(conn).AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "vol-f", ReplicaId: "r1", Epoch: 1}, HeadGen: 9})
if err != nil {
t.Fatal(err)
}
if code, out, errOut := runCLI(show); code != 0 || !strings.Contains(out, "recorded ACK: r1@1 HEAD generation 9") {
t.Fatalf("ACK show: exit=%d out=%q err=%q", code, out, errOut)
}
var first string
for i := 0; i < 2; i++ {
code, out, errOut := runCLI(move)
if code != 0 || !strings.Contains(out, "clean move issued") || !strings.Contains(out, "r1@1 -> r1@2 on node-b") {
t.Fatalf("clean move: exit=%d out=%q err=%q", code, out, errOut)
}
if i == 0 {
first = out
} else if out != first {
t.Fatalf("same-id replay changed grant: %q versus %q", out, first)
}
}
}
@@ -0,0 +1,67 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
// M2 Granted -> Revoking, INV-WS-CLEAN-MOVE-001. The seal choice is an
// operator statement only; no HEAD lookup or ACK is synthesized here.
func runWorkspaceRevoke(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block ops workspace revoke", flag.ContinueOnError)
fs.SetOutput(stderr)
var id control.WorkspaceIdentity
var master string
var sealedGen uint64
var withoutSeal bool
var timeout time.Duration
fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port")
fs.StringVar(&id.VolumeId, "volume", "", "volume id")
fs.StringVar(&id.ReplicaId, "replica", "", "current logical replica id")
fs.Uint64Var(&id.Epoch, "epoch", 0, "current holder epoch")
fs.Uint64Var(&sealedGen, "sealed-gen", 0, "HEAD generation printed by detach --plain; operator assertion, not verified here")
fs.BoolVar(&withoutSeal, "without-seal", false, "explicitly abandon the unpublished tail; a clean move may not be possible")
fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the RPC")
if err := fs.Parse(args); err != nil {
return wsExitRefusedLocally
}
sealProvided := false
fs.Visit(func(f *flag.Flag) {
if f.Name == "sealed-gen" {
sealProvided = true
}
})
if fs.NArg() != 0 || master == "" || id.VolumeId == "" || id.ReplicaId == "" || id.Epoch == 0 || timeout <= 0 || sealProvided == withoutSeal || (sealProvided && sealedGen == 0) {
fmt.Fprintln(stderr, "workspace revoke: refused locally; require --master, --volume, --replica, positive --epoch/--timeout and exactly one of positive --sealed-gen or --without-seal")
return wsExitRefusedLocally
}
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace revoke: refused locally, nothing sent: %v\n", err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
lease, err := c.Revoke(ctx, &id)
if err != nil {
fmt.Fprintf(stderr, "workspace revoke: %v\n", err)
if wsclient.OutcomeOf(err) == wsclient.OutcomeUnknown {
fmt.Fprintln(stderr, "workspace revoke: outcome unknown; inspect workspace show before proceeding")
}
return workspaceExit(wsclient.OutcomeOf(err))
}
fmt.Fprintf(stdout, "revocation requested: volume %s holder %s@%d expiry_ns %d\n", id.VolumeId, id.ReplicaId, id.Epoch, lease.GetExpiresAtNs())
if withoutSeal {
fmt.Fprintln(stdout, "operator statement: abandoning unpublished tail (--without-seal)")
} else {
fmt.Fprintf(stdout, "operator-stated sealed HEAD generation: %d (not verified); workspace show must report ACK at this generation before move --clean\n", sealedGen)
}
return wsExitOK
}
@@ -0,0 +1,129 @@
package main
import (
"context"
"strings"
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Other RPC methods are deliberately absent: revoke must not orchestrate a
// query, detach, acknowledgement or move on the operator's behalf.
type revokeCLIRecorder struct {
control.WorkspaceServiceClient
requests []*control.WorkspaceIdentity
reply *control.WorkspaceLeaseFact
err error
}
func (r *revokeCLIRecorder) RevokeWorkspace(_ context.Context, q *control.WorkspaceIdentity, _ ...grpc.CallOption) (*control.WorkspaceLeaseFact, error) {
r.requests = append(r.requests, q)
return r.reply, r.err
}
func installRevokeRecorder(t *testing.T, r *revokeCLIRecorder) *int {
t.Helper()
dials := 0
old := workspaceDial
workspaceDial = func(string) (*wsclient.Client, error) {
dials++
return wsclient.New(r), nil
}
t.Cleanup(func() { workspaceDial = old })
return &dials
}
func revokeArgs(extra ...string) []string {
return append([]string{"ops", "workspace", "revoke", "--master", "127.0.0.1:19090", "--volume", "vol", "--replica", "r1", "--epoch", "3", "--sealed-gen", "9"}, extra...)
}
// G1 / existing M2 Granted -> Revoking, INV-WS-CLEAN-MOVE-001.
// A successful request is not a host ACK or proof of a detached HEAD.
func TestWorkspaceRevokeSendsOnlyTheExplicitIdentity(t *testing.T) {
r := &revokeCLIRecorder{reply: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ExpiresAtNs: 12345, Revoking: true}}
dials := installRevokeRecorder(t, r)
code, out, errOut := runCLI(revokeArgs())
if code != wsExitOK || *dials != 1 || len(r.requests) != 1 {
t.Fatalf("exit=%d dials=%d requests=%d stdout=%q stderr=%q", code, *dials, len(r.requests), out, errOut)
}
q := r.requests[0]
if q.GetVolumeId() != "vol" || q.GetReplicaId() != "r1" || q.GetEpoch() != 3 {
t.Fatalf("identity=%+v", q)
}
if !strings.Contains(out, "revocation requested") || !strings.Contains(out, "vol") || !strings.Contains(out, "r1@3") || !strings.Contains(out, "9") {
t.Fatalf("request outcome must name its identity and remain distinct from ACK: %q", out)
}
}
func TestWorkspaceRevokeRejectsInvalidInputsBeforeDial(t *testing.T) {
r := &revokeCLIRecorder{}
dials := installRevokeRecorder(t, r)
for _, extra := range [][]string{
{"--master", ""}, {"--volume", ""}, {"--replica", ""}, {"--epoch", "0"}, {"--epoch", "-1"},
{"--timeout", "0s"}, {"--timeout", "-1s"}, {"unexpected"},
{"--sealed-gen", "0"}, {"--without-seal"},
{"--sealed-gen", "0", "--without-seal"},
} {
code, _, _ := runCLI(revokeArgs(extra...))
if code != wsExitRefusedLocally || *dials != 0 || len(r.requests) != 0 {
t.Fatalf("%v: exit=%d dials=%d requests=%d", extra, code, *dials, len(r.requests))
}
}
}
func TestWorkspaceRevokeRequiresAnExplicitSealChoice(t *testing.T) {
r := &revokeCLIRecorder{reply: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, Revoking: true}}
dials := installRevokeRecorder(t, r)
args := revokeArgs()
args = args[:len(args)-2] // omit --sealed-gen entirely
if code, _, _ := runCLI(args); code != wsExitRefusedLocally || *dials != 0 {
t.Fatalf("missing seal choice: exit=%d dials=%d", code, *dials)
}
code, out, errOut := runCLI(append(args, "--without-seal"))
if code != wsExitOK || !strings.Contains(out, "abandoning unpublished tail") || len(r.requests) != 1 {
t.Fatalf("explicit lossy choice: exit=%d requests=%d out=%q err=%q", code, len(r.requests), out, errOut)
}
}
func TestWorkspaceRevokeDoesNotTrustAnUnmatchedReply(t *testing.T) {
for _, tc := range []struct {
name string
reply *control.WorkspaceLeaseFact
}{
{"missing", nil},
{"volume", &control.WorkspaceLeaseFact{VolumeId: "other", ReplicaId: "r1", Epoch: 3, Revoking: true}},
{"replica", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r2", Epoch: 3, Revoking: true}},
{"epoch", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 4, Revoking: true}},
{"not_revoking", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}},
} {
t.Run(tc.name, func(t *testing.T) {
r := &revokeCLIRecorder{reply: tc.reply}
installRevokeRecorder(t, r)
code, out, errOut := runCLI(revokeArgs())
if code != wsExitUnknown || out != "" || len(r.requests) != 1 || !strings.Contains(errOut, "unknown") {
t.Fatalf("exit=%d requests=%d stdout=%q stderr=%q", code, len(r.requests), out, errOut)
}
})
}
}
func TestWorkspaceRevokePreservesRPCOutcome(t *testing.T) {
for _, tc := range []struct {
code codes.Code
want int
}{{codes.FailedPrecondition, wsExitRefused}, {codes.Unavailable, wsExitUnknown}, {codes.DeadlineExceeded, wsExitUnknown}} {
t.Run(tc.code.String(), func(t *testing.T) {
r := &revokeCLIRecorder{err: status.Error(tc.code, "recorded revoke result")}
installRevokeRecorder(t, r)
code, out, errOut := runCLI(revokeArgs())
if code != tc.want || out != "" || len(r.requests) != 1 || !strings.Contains(errOut, "recorded revoke result") {
t.Fatalf("exit=%d want=%d requests=%d stdout=%q stderr=%q", code, tc.want, len(r.requests), out, errOut)
}
})
}
}
@@ -0,0 +1,76 @@
package main
import (
"context"
"flag"
"fmt"
"io"
"time"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
)
// Read-only M2 Granted -> Revoking -> Acked -> Moved (clean) facts,
// INV-WS-CLEAN-MOVE-001. Do not synthesize an ACK or resolve a physical host.
func runWorkspaceShow(args []string, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("sw-block ops workspace show", flag.ContinueOnError)
fs.SetOutput(stderr)
var master, volume string
var timeout time.Duration
fs.StringVar(&master, "master", "", "blockmaster gRPC address host:port")
fs.StringVar(&volume, "volume", "", "volume id")
fs.DurationVar(&timeout, "timeout", wsDefaultTimeout, "bound for the read-only RPC")
if err := fs.Parse(args); err != nil {
return wsExitRefusedLocally
}
if fs.NArg() != 0 || master == "" || volume == "" || timeout <= 0 {
fmt.Fprintln(stderr, "workspace show: --master, --volume and positive --timeout required; nothing sent")
return wsExitRefusedLocally
}
c, err := workspaceDial(master)
if err != nil {
fmt.Fprintf(stderr, "workspace show: refused locally, nothing sent: %v\n", err)
return wsExitRefusedLocally
}
defer c.Close()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
view, err := c.Show(ctx, volume)
if err != nil {
fmt.Fprintf(stderr, "workspace show: %v\n", err)
return workspaceExit(wsclient.OutcomeOf(err))
}
printWorkspaceView(stdout, volume, view)
return wsExitOK
}
func printWorkspaceView(out io.Writer, volume string, view *control.WorkspaceStatus) {
fmt.Fprintf(out, "volume: %s (query snapshot, not authority to serve)\n", volume)
lease := view.GetLease()
if lease == nil {
fmt.Fprintln(out, "replica: none\nepoch: none\nlease state: none\nholder: none")
} else {
state := "granted"
if lease.GetValidForNs() <= 0 {
state = "expired"
} else if lease.GetRevoking() {
state = "revoking"
}
fmt.Fprintf(out, "replica: %s\nepoch: %d\nlease state: %s\nholder: %s@%d (logical replica)\nlease expiry_ns: %d; host validity_ns at query: %d\n", lease.GetReplicaId(), lease.GetEpoch(), state, lease.GetReplicaId(), lease.GetEpoch(), lease.GetExpiresAtNs(), lease.GetValidForNs())
}
ack := view.GetRevocationAck()
if ack == nil {
fmt.Fprintln(out, "recorded ACK: none")
} else {
id := ack.GetIdentity()
fmt.Fprintf(out, "recorded ACK: %s@%d HEAD generation %d\n", id.GetReplicaId(), id.GetEpoch(), ack.GetHeadGen())
}
fmt.Fprintln(out, "host: unknown (not recorded by the master); issued moves and bindings below are separate facts")
for _, g := range view.GetMoves() {
fmt.Fprintf(out, "move: request=%s kind=%s issued=%t %s/%s@%d -> %s/%s@%d HEAD generation %d remote LSN %d\n", g.GetRequestId(), g.GetKind(), g.GetIssued(), g.GetOldHost(), g.GetOldReplicaId(), g.GetOldEpoch(), g.GetNewHost(), g.GetNewReplicaId(), g.GetNewEpoch(), g.GetHeadGen(), g.GetRemoteLsn())
}
for _, b := range view.GetBindings() {
fmt.Fprintf(out, "binding: host=%s data=%s ctrl=%s retired=%t\n", b.GetServerId(), b.GetDataAddr(), b.GetCtrlAddr(), b.GetRetired())
}
}
@@ -0,0 +1,114 @@
package main
import (
"context"
"strings"
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"github.com/seaweedfs/seaweed-block/core/rpc/wsclient"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type workspaceShowRecorder struct {
control.WorkspaceServiceClient
requests []*control.WorkspaceVolume
reply *control.WorkspaceStatus
err error
}
func (r *workspaceShowRecorder) QueryWorkspace(_ context.Context, q *control.WorkspaceVolume, _ ...grpc.CallOption) (*control.WorkspaceStatus, error) {
r.requests = append(r.requests, q)
return r.reply, r.err
}
func installShowRecorder(t *testing.T, r *workspaceShowRecorder) *int {
t.Helper()
dials := 0
old := workspaceDial
workspaceDial = func(string) (*wsclient.Client, error) { dials++; return wsclient.New(r), nil }
t.Cleanup(func() { workspaceDial = old })
return &dials
}
// Query-only view of M2 Granted -> Revoking -> Acked -> Moved (clean),
// INV-WS-CLEAN-MOVE-001. A recorded ACK must remain distinct from a request.
func TestWorkspaceShowPrintsTheRecordedLeaseACKAndMoves(t *testing.T) {
r := &workspaceShowRecorder{reply: &control.WorkspaceStatus{
Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ValidForNs: 1000000000, Revoking: true},
RevocationAck: &control.WorkspaceRevocationAck{Identity: &control.WorkspaceIdentity{VolumeId: "vol", ReplicaId: "r1", Epoch: 3}, HeadGen: 9},
Moves: []*control.WorkspaceGrant{{VolumeId: "vol", RequestId: "old-move", Kind: "clean", OldEpoch: 2, NewEpoch: 3, OldReplicaId: "r1", NewReplicaId: "r1", OldHost: "node-a", NewHost: "node-b", HeadGen: 8, Issued: true}},
}}
dials := installShowRecorder(t, r)
code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"})
if code != 0 || *dials != 1 || len(r.requests) != 1 || r.requests[0].GetVolumeId() != "vol" {
t.Fatalf("exit=%d dials=%d requests=%v out=%q err=%q", code, *dials, r.requests, out, errOut)
}
for _, want := range []string{"holder: r1@3", "lease state: revoking", "recorded ACK: r1@3 HEAD generation 9", "old-move", "node-a", "node-b", "issued=true"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in %q", want, out)
}
}
}
func TestWorkspaceShowUsesTheMastersLeaseValidity(t *testing.T) {
for _, tc := range []struct {
name string
lease *control.WorkspaceLeaseFact
want string
}{
{"granted", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ValidForNs: 1}, "lease state: granted"},
{"expired", &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ExpiresAtNs: 9223372036854775807}, "lease state: expired"},
{"absent", nil, "holder: none"},
} {
t.Run(tc.name, func(t *testing.T) {
r := &workspaceShowRecorder{reply: &control.WorkspaceStatus{Lease: tc.lease}}
installShowRecorder(t, r)
code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"})
if code != 0 || !strings.Contains(out, tc.want) || !strings.Contains(out, "recorded ACK: none") {
t.Fatalf("exit=%d out=%q err=%q", code, out, errOut)
}
})
}
}
func TestWorkspaceShowOrdersOperatorIdentityWithoutInventingAHost(t *testing.T) {
r := &workspaceShowRecorder{reply: &control.WorkspaceStatus{
Lease: &control.WorkspaceLeaseFact{VolumeId: "vol", ReplicaId: "r1", Epoch: 3, ValidForNs: 1},
}}
installShowRecorder(t, r)
code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"})
if code != 0 {
t.Fatalf("exit=%d err=%q", code, errOut)
}
last := -1
for _, field := range []string{"volume: vol", "replica: r1\n", "epoch: 3\n", "lease state: granted", "recorded ACK: none"} {
at := strings.Index(out, field)
if at <= last {
t.Fatalf("missing or out-of-order %q in %q", field, out)
}
last = at
}
if !strings.Contains(out, "host: unknown (not recorded by the master)") {
t.Fatalf("physical host must remain unknown: %q", out)
}
}
func TestWorkspaceShowRefusesBadUsageAndClassifiesRPCFailure(t *testing.T) {
r := &workspaceShowRecorder{err: status.Error(codes.Unavailable, "query unavailable")}
dials := installShowRecorder(t, r)
for _, args := range [][]string{
{"--volume", "vol"}, {"--master", "master:19090"},
{"--master", "master:19090", "--volume", "vol", "--timeout", "0s"},
} {
if code, _, _ := runCLI(append([]string{"ops", "workspace", "show"}, args...)); code != wsExitRefusedLocally || *dials != 0 {
t.Fatalf("%v: exit=%d dials=%d", args, code, *dials)
}
}
code, out, errOut := runCLI([]string{"ops", "workspace", "show", "--master", "master:19090", "--volume", "vol"})
if code != wsExitUnknown || out != "" || !strings.Contains(errOut, "query unavailable") || len(r.requests) != 1 {
t.Fatalf("exit=%d out=%q err=%q requests=%d", code, out, errOut, len(r.requests))
}
}
+3 -2
View File
@@ -153,12 +153,13 @@ func (p *Publisher) RecordWorkspaceDeletion(ctx context.Context, volume string,
}
func validateWorkspaceMoveRequest(req WorkspaceMoveRequest) error {
// v1 moves a replica between hosts without changing its logical slot.
// INV-WS-SAME-HOST-CLEAN-MOVE-001: clean moves may reuse the host,
// but every move preserves its logical replica slot.
// Refuse before locking or persisting a reservation/authority epoch.
if req.ExpectedReplicaID != req.TargetReplicaID {
return fmt.Errorf("workspace move: v1 requires the same logical replica id")
}
if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || req.ExpectedHost == req.TargetHost || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" ||
if req.RequestID == "" || req.VolumeID == "" || req.ExpectedHost == "" || req.TargetHost == "" || (req.ExpectedHost == req.TargetHost && (req.Kind != "clean" || req.Force)) || req.ExpectedReplicaID == "" || req.ExpectedEpoch == 0 || req.TargetReplicaID == "" ||
req.TargetDataAddr == "" || req.TargetCtrlAddr == "" || (req.Kind != "clean" && req.Kind != "forced") || req.Force != (req.Kind == "forced") {
return fmt.Errorf("workspace move: invalid request")
}
@@ -177,8 +177,8 @@ func (p *Publisher) PublishedAuthorityLines() map[string]PublishedLine {
// RenewWorkspaceLease answers a live holder from memory: it takes only the
// leaf leaseMu, does no I/O and never waits on p.mu or the store. The grant
// is min(now+TTL, durable horizon); a background extender (an ordinary p.mu
// writer) pushes the horizon ahead. Only the first grant of a lease writes
// synchronously (firstWorkspaceGrant).
// writer) pushes the horizon ahead. A first grant and an expired re-grant
// after the shared move barrier write synchronously.
func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
if err := ctx.Err(); err != nil {
return WorkspaceLease{}, err
@@ -214,7 +214,7 @@ func (p *Publisher) RenewWorkspaceLease(ctx context.Context, volume, holder stri
}
if now.UnixNano() >= lv.d.horizon || !now.Before(lv.deadline) {
unlock()
return WorkspaceLease{}, fmt.Errorf("workspace lease expired or revoking")
return p.regrantWorkspaceLease(ctx, volume, holder, epoch)
}
// Where the synchronous write used to refuse (persistWorkspaceLocked):
// a renewal never bypasses uncertainty (INV-AUTH-UNCERTAIN-001).
@@ -310,9 +310,49 @@ func (p *Publisher) firstWorkspaceGrant(ctx context.Context, volume, holder stri
return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil
}
// INV-WS-LEASE-REGRANT-001: serialize an expired re-grant with move issue,
// reusing the forced-move barrier so the old process's validity is past.
// The live renewal path releases leaseMu before entering this writer.
func (p *Publisher) regrantWorkspaceLease(ctx context.Context, volume, holder string, epoch uint64) (WorkspaceLease, error) {
// INV-WS-RENEW-NONBLOCKING-001: a held writer refuses this attempt;
// a returning process can retry after that writer has settled.
if !p.mu.TryLock() {
return WorkspaceLease{}, fmt.Errorf("workspace lease: authority writer busy; retry")
}
defer p.mu.Unlock()
if err := ctx.Err(); err != nil {
return WorkspaceLease{}, err
}
_, line, ok := p.workspaceLineLocked(volume)
s := cloneWorkspace(p.workspace[volume])
if !ok || line.info.ReplicaID != holder || line.info.Epoch != epoch || s == nil || s.Lease == nil ||
s.Lease.ReplicaID != holder || s.Lease.Epoch != epoch {
return WorkspaceLease{}, fmt.Errorf("workspace lease: stale authority")
}
if s.Lease.Revoking || s.Ack != nil || (len(s.Moves) > 0 && !s.Moves[len(s.Moves)-1].Issued) {
return WorkspaceLease{}, fmt.Errorf("workspace lease: revocation or move pending")
}
if p.store == nil || p.workspaceUncertain[volume] {
return WorkspaceLease{}, fmt.Errorf("workspace durable store unavailable or uncertain")
}
_, now, err := p.forcedMoveBarrierLocked(volume, s.Lease)
if err != nil {
return WorkspaceLease{}, err
}
lease, grant := p.newWorkspaceLease(holder, epoch, now)
lease.ExpiresAtNS = max(lease.ExpiresAtNS, s.Lease.ExpiresAtNS)
lease.MaxClockSkewNS = int64(p.workspaceSkew(s.Lease))
s.Lease = lease
if err := p.persistWorkspaceLocked(volume, s); err != nil {
return WorkspaceLease{}, err
}
p.setLeaseDeadlineLocked(volume, grant, true)
return WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: grant.UnixNano(), MaxClockSkewNS: lease.MaxClockSkewNS}, nil
}
// newWorkspaceLease starts a lease at now: the durable horizon is
// now+1.5*TTL and the grant (the deadline) now+TTL. Both a first grant and a
// move issue start a lease this way.
// now+1.5*TTL and the grant (the deadline) now+TTL. A first grant, expired
// re-grant and move issue start a lease this way.
func (p *Publisher) newWorkspaceLease(holder string, epoch uint64, now time.Time) (*WorkspaceLease, time.Time) {
return &WorkspaceLease{ReplicaID: holder, Epoch: epoch, ExpiresAtNS: now.Add(p.workspaceTTL + p.workspaceTTL/2).UnixNano(), MaxClockSkewNS: int64(p.workspaceSkew(nil))}, now.Add(p.workspaceTTL)
}
@@ -0,0 +1,154 @@
package authority
import (
"bytes"
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type regrantStorageView struct{}
func (regrantStorageView) Projection() frontend.Projection {
return frontend.Projection{VolumeID: "v", ReplicaID: "r", Epoch: 1, Healthy: true}
}
// These component controls obtain the real authority re-grant before opening
// the returning file-backed provider. They do not model a second live process.
func TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut(t *testing.T) {
testWorkspaceRegrantStorage(t, false, false)
}
func TestWorkspaceLeaseRegrantCannotUnsealSameEpoch(t *testing.T) {
testWorkspaceRegrantStorage(t, true, false)
}
func TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD(t *testing.T) {
testWorkspaceRegrantStorage(t, false, true)
}
func testWorkspaceRegrantStorage(t *testing.T, sealed, fresh bool) {
t.Helper()
ctx := context.Background()
disk, _ := newTempStore(t)
clock := newTestClock()
p := newLeasePublisher(t, disk, time.Second, clock)
bindAndGrant(t, p, "v", "r")
remote := storage.NewMemChunkRemote()
root := t.TempDir()
open := func() *durable.DurableProvider {
t.Helper()
provider, err := durable.NewDurableProvider(durable.ProviderConfig{
Impl: durable.ImplWALStoreChunk, StorageRoot: root, NumBlocks: 64,
BlockSize: 4096, ChunkBlocks: 4,
ChunkRemoteFor: func(string) (storage.ChunkRemote, error) { return remote, nil },
}, regrantStorageView{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = provider.Close() })
if _, err := provider.EnsureStorage("v"); err != nil {
t.Fatal(err)
}
return provider
}
first := open()
if _, err := first.RecoverVolume(ctx, "v"); err != nil {
t.Fatal(err)
}
backend, err := first.Open(ctx, "v")
if err != nil {
t.Fatal(err)
}
a, b := bytes.Repeat([]byte{0x31}, 4096), bytes.Repeat([]byte{0x42}, 4096)
write := func(offset int64, data []byte) {
t.Helper()
if n, err := backend.Write(ctx, offset, data); err != nil || n != len(data) {
t.Fatal(n, err)
}
if err := backend.Sync(ctx); err != nil {
t.Fatal(err)
}
}
write(0, a)
if _, err := first.CaptureVolume(ctx, "v"); err != nil {
t.Fatal(err)
}
write(4096, b) // completed Sync, deliberately absent from the last HEAD
if sealed {
if _, _, err := first.DetachVolumePlain(ctx, "v"); err != nil {
t.Fatal(err)
}
}
before, err := remote.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
if err := first.Close(); err != nil {
t.Fatal(err)
}
clock.at(3) // beyond both original expiry/skew endpoints
if _, err := p.RenewWorkspaceLease(ctx, "v", "r", 1); err != nil {
t.Fatal("returning process could not obtain the authority re-grant", err)
}
if fresh {
root = t.TempDir()
b = make([]byte, 4096) // the absent local log cannot be claimed as present
}
second := open()
_, err = second.RecoverVolume(ctx, "v")
if sealed {
after, readErr := remote.GetHead(ctx)
if !errors.Is(err, storage.ErrChunkLayerDetached) || readErr != nil || !reflect.DeepEqual(after, before) {
t.Fatal("same-epoch re-grant reactivated the seal", after, err, readErr)
}
blocked, openErr := second.Open(ctx, "v")
if openErr != nil {
t.Fatal(openErr)
}
if _, readErr := blocked.Read(ctx, 0, make([]byte, 4096)); !errors.Is(readErr, frontend.ErrNotReady) {
t.Fatal("sealed re-granted process exposed guest I/O", readErr)
}
return
}
if err != nil {
t.Fatal(err)
}
returning, err := second.Open(ctx, "v")
if err != nil {
t.Fatal(err)
}
for i, want := range [][]byte{a, b} {
got := make([]byte, 4096)
if _, err := returning.Read(ctx, int64(i*4096), got); err != nil || !bytes.Equal(got, want) {
t.Fatal("return lost locally acknowledged bytes", i, err)
}
}
claimed, err := remote.GetHead(ctx)
if err != nil || claimed.Gen <= before.Gen || claimed.Epoch != 1 || claimed.Holder != before.Holder || claimed.RemoteLSN != before.RemoteLSN {
t.Fatal("return served without the new generation fence", claimed, err)
}
if _, err := second.CaptureVolume(ctx, "v"); err != nil {
t.Fatal(err)
}
final, err := remote.GetHead(ctx)
if fresh {
if err != nil || !reflect.DeepEqual(final, claimed) {
t.Fatal("empty-root return published bytes/frontier absent from HEAD", final, err)
}
return
}
if err != nil || final.RemoteLSN <= before.RemoteLSN {
t.Fatal("first returning cut did not cover the local log", final, err)
}
payload, err := remote.Get(ctx, final.Chunks[0].Key)
if err != nil || len(payload) < 8192 || !bytes.Equal(payload[:4096], a) || !bytes.Equal(payload[4096:8192], b) {
t.Fatal("first cut did not publish the full acknowledged image", err)
}
}
@@ -0,0 +1,276 @@
package authority
import (
"context"
"errors"
"sync"
"testing"
"time"
)
// INV-WS-LEASE-REGRANT-001: expiry alone does not abandon an unchanged owner.
// A new guard may use a durable re-grant; existing fenced guards stay terminal.
func TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
store := &hookStore{AuthorityStore: disk}
p := newLeasePublisher(t, store, time.Second, clock)
original := bindAndGrant(t, p, "v", "r")
before := p.WorkspaceState("v").Lease
clock.at(3)
writes := 0
store.setBefore(func(r DurableRecord) error { writes++; return nil })
renewed, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil {
t.Fatalf("unchanged expired holder cannot obtain a durable re-grant: %v", err)
}
if renewed.ReplicaID != "r" || renewed.Epoch != 1 || renewed.Revoking || renewed.ExpiresAtNS <= clock.now().UnixNano() || renewed.ExpiresAtNS <= original.ExpiresAtNS || writes != 1 {
t.Fatalf("bad re-grant %+v writes%d", renewed, writes)
}
records, err := disk.Load()
if err != nil {
t.Fatal(err)
}
found := false
for _, r := range records {
if r.VolumeID == "v" && r.Workspace != nil && r.Workspace.Lease != nil {
l := r.Workspace.Lease
found = true
if l.ExpiresAtNS < renewed.ExpiresAtNS || l.ExpiresAtNS < before.ExpiresAtNS || l.MaxClockSkewNS < before.MaxClockSkewNS {
t.Fatalf("grant ahead of durable horizon/skew: disk%+v reply%+v", l, renewed)
}
}
}
if !found {
t.Fatal("re-grant used without durable lease")
}
line, _ := p.VolumeAuthorityLine("v")
if line.Epoch != 1 || line.ReplicaID != "r" {
t.Fatal("re-grant minted authority", line)
}
// Immediate flapping/repeated requests take the memory path: one durable
// re-grant, no extra writes while its positive grant is outstanding.
for i := 0; i < 10; i++ {
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatal(err)
}
}
if writes != 1 {
t.Fatalf("repeat requests amplified durable writes: %d", writes)
}
}
func TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure(t *testing.T) {
for _, fail := range []bool{false, true} {
t.Run(map[bool]string{false: "durable", true: "uncertain"}[fail], func(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
store := &hookStore{AuthorityStore: disk}
p := newLeasePublisher(t, store, time.Second, clock)
before := bindAndGrant(t, p, "v", "r")
clock.at(3)
entered, release := make(chan struct{}), make(chan struct{})
var releaseOnce sync.Once
releaseWriter := func() { releaseOnce.Do(func() { close(release) }) }
store.setBefore(func(DurableRecord) error {
close(entered)
<-release
return nil
})
store.setAfter(func(DurableRecord) error {
if fail {
return errors.New("write landed but reply lost")
}
return nil
})
type answer struct {
lease WorkspaceLease
err error
}
done := make(chan answer, 1)
finished := make(chan struct{})
// Registered last: release and join before publisher/store cleanup.
t.Cleanup(func() {
releaseWriter()
select {
case <-finished:
case <-time.After(5 * time.Second):
t.Error("re-grant worker did not finish during cleanup")
}
})
go func() {
defer close(finished)
l, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
done <- answer{l, err}
}()
select {
case <-entered:
case got := <-done:
t.Fatal("re-grant returned before the durable write witness", got)
case <-time.After(5 * time.Second):
t.Fatal("re-grant did not enter the durable write")
}
if visible, ok := p.WorkspaceLeaseReply("v"); !ok || visible.ExpiresAtNS != before.ExpiresAtNS {
t.Error("grant published ahead of durable store", visible)
}
// Events decide success; timers only bound failed handshakes.
releaseWriter()
var got answer
select {
case got = <-done:
case <-time.After(5 * time.Second):
t.Fatal("released re-grant did not return")
}
if fail {
if got.err == nil || got.lease.ExpiresAtNS != 0 {
t.Fatal("uncertain write produced a usable grant", got)
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil {
t.Fatal("renewal bypassed uncertain re-grant")
}
} else if got.err != nil || got.lease.ExpiresAtNS != clock.sec(4).UnixNano() {
t.Fatal("durable re-grant not returned", got)
}
})
}
}
func TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
p := newLeasePublisher(t, disk, time.Second, clock)
bindAndGrant(t, p, "v", "r")
clock.at(3)
req := WorkspaceMoveRequest{RequestID: "force", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
grant, err := p.MoveWorkspace(context.Background(), req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42})
if err != nil || !grant.Issued || grant.NewEpoch != 2 {
t.Fatal("fixture did not issue forced successor", grant, err)
}
clock.at(7)
if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil {
t.Fatal("old epoch re-granted after forced issue", got)
}
line, _ := p.VolumeAuthorityLine("v")
if line.Epoch != 2 || p.WorkspaceState("v").Lease.Epoch != 2 {
t.Fatal("re-grant undid forced issue", line)
}
}
func TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
p := newLeasePublisher(t, disk, time.Second, clock)
bindAndGrant(t, p, "v", "r")
clock.at(3)
req := WorkspaceMoveRequest{RequestID: "force", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "old", TargetHost: "new", ExpectedEpoch: 1, TargetDataAddr: "nd", TargetCtrlAddr: "nc", Kind: "forced", Force: true}
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", req.RequestID, "r", 1); err != nil {
t.Fatal("forced preflight was not actually admitted", err)
}
if _, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err != nil {
t.Fatal("same-owner re-grant failed", err)
}
if _, err := p.MoveWorkspace(context.Background(), req, WorkspaceHead{Gen: 7, Epoch: 1, Holder: "old/r", RemoteLSN: 42}); err == nil {
t.Fatal("force ignored the grant committed after its HEAD preflight")
}
line, _ := p.VolumeAuthorityLine("v")
if line.Epoch != 1 {
t.Fatal("two winning successors", line)
}
if len(p.WorkspaceState("v").Moves) != 0 {
t.Fatal("refused forced move reserved an epoch")
}
}
func TestWorkspaceLeaseSealedAckNeverRegrants(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
store := &hookStore{AuthorityStore: disk}
p := newLeasePublisher(t, store, time.Second, clock)
bindAndGrant(t, p, "v", "r")
ctx := context.Background()
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil {
t.Fatal(err)
}
// ACK is the master's durable evidence for this holder's sealed generation.
clock.at(10)
writes := 0
store.setBefore(func(DurableRecord) error { writes++; return nil })
got, err := p.RenewWorkspaceLease(ctx, "v", "r", 1)
if err == nil && (!got.Revoking || got.ExpiresAtNS > clock.now().UnixNano()) {
t.Fatalf("sealed/ACKed owner got usable re-grant: %+v", got)
}
if writes != 0 || p.WorkspaceState("v").Ack.HeadGen != 7 {
t.Fatal("sealed proof mutated by re-grant")
}
}
// INV-WS-LEASE-REGRANT-001: expiry alone cannot fence a previous process
// whose own clock may lag. The full skew bound must pass before re-grant.
func TestWorkspaceLeaseRegrantWaitsForFullSkew(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
store := &hookStore{AuthorityStore: disk}
p := NewPublisher(nil, WithStore(store), WithWorkspaceLeaseConfig(10*time.Second, clock.now), WithWorkspaceMaxClockSkew(4*time.Second))
t.Cleanup(p.CloseWorkspaceExtenders)
grant := bindAndGrant(t, p, "v", "r")
if grant.ExpiresAtNS != clock.sec(10).UnixNano() || p.WorkspaceState("v").Lease.ExpiresAtNS != clock.sec(15).UnixNano() {
t.Fatal("fixture did not create the declared grant/horizon", grant)
}
writes := 0
store.setBefore(func(DurableRecord) error { writes++; return nil })
// The deadline+skew boundary is 14 s; horizon+skew is 19 s.
// Re-grant uses the same MAX barrier as a forced move, including the
// interval after the shorter deadline has passed and its final ns.
for _, now := range []time.Time{clock.sec(13), clock.sec(14), clock.sec(19).Add(-time.Nanosecond)} {
clock.ns.Store(now.UnixNano())
if got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil {
t.Fatal("re-grant crossed the later expiry/skew boundary early", now, got)
}
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "force", "r", 1); err == nil {
t.Fatal("forced move crossed the shared boundary early", now)
}
if writes != 0 {
t.Fatal("unsafe early re-grant attempted persistence", writes)
}
}
clock.at(19)
if err := p.WorkspaceForcedMoveAdmitted(context.Background(), "v", "force", "r", 1); err != nil {
t.Fatal("fixture did not reach the shared forced-move barrier", err)
}
got, err := p.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil || got.ExpiresAtNS <= clock.now().UnixNano() || writes != 1 {
t.Fatalf("safe unchanged owner cannot return: grant=%+v writes=%d err=%v", got, writes, err)
}
}
func TestWorkspaceLeaseRegrantRetainsPersistedSkewAfterRestart(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
first := newLeasePublisher(t, disk, time.Second, clock)
before := bindAndGrant(t, first, "v", "r")
first.CloseWorkspaceExtenders()
clock.at(3)
returned := NewPublisher(nil, WithStore(disk), WithWorkspaceLeaseConfig(time.Second, clock.now), WithWorkspaceMaxClockSkew(time.Millisecond))
t.Cleanup(returned.CloseWorkspaceExtenders)
// Restart deadline is 4 s. The newly configured 1 ms bound has passed,
// but the original persisted bound still protects the previous process.
clock.at(4.5)
if got, err := returned.RenewWorkspaceLease(context.Background(), "v", "r", 1); err == nil {
t.Fatal("smaller restart setting shortened the old barrier", got)
}
clock.at(6)
got, err := returned.RenewWorkspaceLease(context.Background(), "v", "r", 1)
if err != nil || got.MaxClockSkewNS != before.MaxClockSkewNS {
t.Fatal("re-grant lowered the persisted skew", got, err)
}
records, err := disk.Load()
if err != nil {
t.Fatal(err)
}
if len(records) != 1 || records[0].Workspace.Lease.MaxClockSkewNS != before.MaxClockSkewNS || records[0].Workspace.Lease.ExpiresAtNS < got.ExpiresAtNS {
t.Fatal("preserved re-grant bound was not durable", records)
}
}
@@ -0,0 +1,62 @@
package authority
import (
"context"
"testing"
"time"
)
// INV-WS-SAME-HOST-CLEAN-MOVE-001: an unchanged sealed generation and its
// durable ACK remain a clean-move proof after the lease expires overnight.
func TestWorkspaceSameHostCleanMoveUsesOvernightSeal(t *testing.T) {
disk, _ := newTempStore(t)
clock := newTestClock()
p := newLeasePublisher(t, disk, time.Second, clock)
bindAndGrant(t, p, "v", "r")
ctx := context.Background()
req := WorkspaceMoveRequest{RequestID: "return", VolumeID: "v", ExpectedReplicaID: "r", TargetReplicaID: "r", ExpectedHost: "host", TargetHost: "host", ExpectedEpoch: 1, TargetDataAddr: "d", TargetCtrlAddr: "c", Kind: "clean"}
head := WorkspaceHead{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true}
if _, err := p.MoveWorkspace(ctx, req, head); err == nil {
t.Fatal("same-host move accepted a seal without revocation ACK")
}
if err := p.BeginWorkspaceRevocation(ctx, "v", "r", 1); err != nil {
t.Fatal(err)
}
if err := p.AckWorkspaceRevocation(ctx, "v", WorkspaceRevokeAck{ReplicaID: "r", Epoch: 1, HeadGen: 7}); err != nil {
t.Fatal(err)
}
clock.at(86400)
for _, bad := range []WorkspaceHead{
{Gen: 7, Epoch: 1, Holder: "host/r", RemoteLSN: 42},
{Gen: 8, Epoch: 1, Holder: "host/r", RemoteLSN: 42, Detached: true},
{Gen: 7, Epoch: 1, Holder: "other/r", RemoteLSN: 42, Detached: true},
{Gen: 7, Epoch: 2, Holder: "host/r", RemoteLSN: 42, Detached: true},
} {
if _, err := p.MoveWorkspace(ctx, req, bad); err == nil {
t.Fatal("same-host move bypassed sealed-generation proof", bad)
}
}
forced := req
forced.Kind, forced.Force = "forced", true
if _, err := p.MoveWorkspace(ctx, forced, head); err == nil {
t.Fatal("same-host forced move accepted")
}
if line, _ := p.VolumeAuthorityLine("v"); line.Epoch != 1 || len(p.WorkspaceState("v").Moves) != 0 {
t.Fatal("refusal reserved or published authority", line)
}
grant, err := p.MoveWorkspace(ctx, req, head)
if err != nil {
t.Fatal("sealed same-host clean move refused", err)
}
if !grant.Issued || grant.NewEpoch != 2 || grant.OldHost != "host" || grant.NewHost != "host" || grant.HeadGen != 7 || grant.RemoteLSN != 42 {
t.Fatal("wrong journaled successor", grant)
}
again, err := p.MoveWorkspace(ctx, req, WorkspaceHead{})
if err != nil || again != grant {
t.Fatal("same-ID replay changed the successor", again, err)
}
loaded := NewPublisher(nil, WithStore(disk)).WorkspaceState("v")
if loaded == nil || len(loaded.Moves) != 1 || loaded.Moves[0] != grant {
t.Fatal("same-host grant not durable", loaded)
}
}
@@ -0,0 +1,9 @@
package durable
import "time"
// MinCaptureInterval is the shortest automatic cut interval blockvolume
// accepts (--chunk-capture-interval; 0 turns the timer off). A program
// that builds blockvolume with a shorter floor sets it before parsing
// flags; nothing changes it at run time.
var MinCaptureInterval = 5 * time.Minute
@@ -36,3 +36,11 @@ func SetTestBeforeIOLock(b frontend.Backend, f func()) { b.(*StorageBackend).tes
func SetTestBeforeAttachWait(b frontend.Backend, f func()) {
b.(*StorageBackend).testBeforeReadReadyWait = f
}
func SetTestAfterGate(b frontend.Backend, f func()) { b.(*StorageBackend).testAfterGate = f }
func StopFlipAt(b frontend.Backend) time.Time { return b.(*StorageBackend).StopFlipAt() }
func StopIOForTest(ctx context.Context, b frontend.Backend, evidence string) error {
return b.(*StorageBackend).StopIO(ctx, evidence)
}
@@ -1190,10 +1190,18 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
// the cut gets three quarters, the settlement what is left. The bound is
// cooperative (contexts): a syscall that never returns is not bounded here.
var start time.Time
var stopIOReturned time.Time
// stopIOBegan is the backend's flip (admission closed, under its mu: an
// I/O whose gate runs after it is refused; one gated before it is
// admitted even if it registers later), stopIOReturned when the admitted
// I/O has drained; both are logged so a measurement can tell a refusal
// after the flip from an admitted I/O that failed.
var stopIOBegan, stopIOReturned time.Time
defer func() {
if !stopIOReturned.IsZero() {
// Emit after the cut releases its barrier, using the actual return time.
// Emit after the cut releases its barrier, using the actual times.
if !stopIOBegan.IsZero() {
log.Printf("durable: volume=%s admission closed at %s", volumeID, stopIOBegan.UTC().Format(time.RFC3339Nano))
}
log.Printf("durable: volume=%s StopIO returned at %s", volumeID, stopIOReturned.UTC().Format(time.RFC3339Nano))
}
}()
@@ -1267,6 +1275,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
return false
}
stopIOReturned = time.Now()
stopIOBegan = h.backend.StopFlipAt()
h.chunkDetach = true
beginFreeze()
return true
@@ -1328,6 +1337,7 @@ func (p *DurableProvider) detachVolume(ctx context.Context, volumeID string, pla
}
if err == nil {
stopIOReturned = time.Now()
stopIOBegan = h.backend.StopFlipAt()
}
if err == nil {
p.stopChunkLoop(h)
@@ -0,0 +1,187 @@
package durable_test
import (
"context"
"errors"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// A detach logs when admission closed (the backend's operational flip,
// taken under its lock) as well as when StopIO returned, both with RFC 3339
// nanoseconds, so a test measuring guest errors can tell a refusal by
// contract (after the flip) from an admitted I/O that failed.
func TestLiveDetachLogsWhenAdmissionClosed(t *testing.T) {
p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour)
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
if _, err := b.Write(context.Background(), 4096, block(0x51)); err != nil {
t.Fatal(err)
}
logs := &lockedLog{}
captureWriteLogs(t, logs)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
started := time.Now()
if _, _, err := p.DetachVolume(ctx, "v1"); err != nil {
t.Fatal(err)
}
ended := time.Now()
stamp := func(marker string) time.Time {
t.Helper()
var found []time.Time
for _, line := range strings.Split(logs.String(), "\n") {
if _, s, ok := strings.Cut(line, marker); ok {
at, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(s))
if err != nil {
t.Fatalf("%q: %v", line, err)
}
found = append(found, at)
}
}
if len(found) != 1 {
t.Fatalf("%d lines with %q, want 1:\n%s", len(found), marker, logs.String())
}
return found[0]
}
closed := stamp("volume=v1 admission closed at ")
returned := stamp("volume=v1 StopIO returned at ")
if closed.Before(started) || returned.Before(closed) || ended.Before(returned) {
t.Fatalf("closed %s, returned %s: want started %s <= closed <= returned <= ended %s", closed, returned, started, ended)
}
if got := durable.StopFlipAt(b); !got.Equal(closed) {
t.Fatalf("logged %s, backend flip %s: the log must carry the flip itself", closed, got)
}
}
// The flip time is the admission cutoff: a write whose gate passed before
// the flip is admitted and completes (StopIO drains it), and a write whose
// gate runs after the flip is refused, so nothing is admitted after the
// logged boundary.
func TestStopFlipIsTheAdmissionCutoff(t *testing.T) {
p := chunkProvider(t, t.TempDir(), storage.NewMemChunkRemote(), v1View(), time.Hour)
openRecovered(t, p)
b, err := p.Open(context.Background(), "v1")
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
parkedA, releaseA := make(chan struct{}), make(chan struct{})
parkedB, releaseB := make(chan struct{}), make(chan struct{})
var onceA, onceB sync.Once
freeA := func() { onceA.Do(func() { close(releaseA) }) }
freeB := func() { onceB.Do(func() { close(releaseB) }) }
errA, errB, stopErr := make(chan error, 1), make(chan error, 1), make(chan error, 1)
var launched struct{ a, b, stop atomic.Bool }
// Registered before anything starts: every parked writer is released and
// every goroutine is joined within a bound, whatever the test hits.
t.Cleanup(func() {
freeA()
freeB()
cancel()
for name, c := range map[string]struct {
on *atomic.Bool
ch chan error
}{"write A": {&launched.a, errA}, "write B": {&launched.b, errB}, "StopIO": {&launched.stop, stopErr}} {
if !c.on.Load() {
continue
}
select {
case <-c.ch:
case <-time.After(5 * time.Second):
t.Errorf("%s did not return", name)
}
}
})
// Write A passes the gate, then parks (it registers after the flip and
// still completes: admission is the gate's decision).
var parkA, parkB atomic.Bool
parkA.Store(true)
durable.SetTestAfterGate(b, func() {
if parkA.CompareAndSwap(true, false) {
close(parkedA)
<-releaseA
}
})
launched.a.Store(true)
go func() { _, err := b.Write(context.Background(), 0, block(0x10)); errA <- err }()
select {
case <-parkedA:
case <-time.After(5 * time.Second):
t.Fatal("write A never passed the gate")
}
// Write B parks before the gate.
parkB.Store(true)
durable.SetTestBeforeIOLock(b, func() {
if parkB.CompareAndSwap(true, false) {
close(parkedB)
<-releaseB
}
})
launched.b.Store(true)
go func() { _, err := b.Write(context.Background(), 4096, block(0x20)); errB <- err }()
select {
case <-parkedB:
case <-time.After(5 * time.Second):
t.Fatal("write B never reached the gate")
}
launched.stop.Store(true)
go func() { stopErr <- durable.StopIOForTest(ctx, b, "test stop") }()
deadline := time.Now().Add(5 * time.Second)
for durable.StopFlipAt(b).IsZero() {
if time.Now().After(deadline) {
t.Fatal("the stop never flipped")
}
time.Sleep(time.Millisecond)
}
// B now reaches its gate after the flip (it may first wait behind the
// drain for ioMu); A is admitted and still in flight, so StopIO waits.
freeB()
select {
case err := <-stopErr:
stopErr <- err
t.Fatalf("StopIO returned (%v) while admitted write A was still in flight", err)
case <-time.After(100 * time.Millisecond):
}
freeA()
select {
case err := <-errA:
errA <- err
if err != nil {
t.Fatalf("write A (gate before the flip): %v, want admitted and completed", err)
}
case <-time.After(5 * time.Second):
t.Fatal("write A never returned")
}
select {
case err := <-stopErr:
stopErr <- err
if err != nil {
t.Fatalf("StopIO: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("StopIO never returned after A completed")
}
select {
case err := <-errB:
errB <- err
if !errors.Is(err, frontend.ErrNotReady) {
t.Fatalf("write B (gate after the flip): %v, want refused (ErrNotReady)", err)
}
case <-time.After(5 * time.Second):
t.Fatal("write B never returned")
}
}
@@ -148,7 +148,15 @@ const maxFullBlockBatchBlocks = 64
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()
testBeforeIOLock func()
// testAfterGate, test-only, runs in admit after the gate passed and
// before the I/O registers under mu.
testAfterGate func()
// stopFlipAt is when admission last closed for a stop, taken under mu
// just after operational went false; guarded by mu. An I/O whose gate
// saw operational before it was admitted (and StopIO drains it); every
// gate after it refuses.
stopFlipAt time.Time
testPrecopyQueued func() // after FIFO registration, outside mu
testPrecopyGranted func(*precopyWaiter) // FIFO grant under mu; nonblocking test hook
testPrecopyStopFallback func() // before fallback lock attempts, outside mu
@@ -482,8 +490,12 @@ func (b *StorageBackend) SetOperational(ok bool, evidence string) {
// The caller owns mu; publication never calls the store or waits for I/O.
func (b *StorageBackend) setOperationalLocked(ok bool, evidence string) {
flipped := !ok && b.operational.Load()
b.opEvidence.Store(evidence)
b.operational.Store(ok)
if flipped {
b.stopFlipAt = time.Now() // after the store: no gate after this instant admits
}
b.waitAttachReady = false
// A host drain closes storage admission, but is not the old path's
// teardown. Keep a final pre-copy queue parked until Close or its budget;
@@ -512,6 +524,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool {
}
b.opEvidence.Store(evidence)
b.operational.Store(false)
b.stopFlipAt = time.Now()
b.waitAttachReady = false
b.notifyReadReadyLocked()
return true
@@ -539,6 +552,7 @@ func (b *StorageBackend) TryStopIO(evidence string) bool {
b.precopy = p
b.opEvidence.Store(evidence)
b.operational.Store(false)
b.stopFlipAt = time.Now()
b.waitAttachReady = false
b.notifyReadReadyLocked()
return true
@@ -561,6 +575,13 @@ func (b *StorageBackend) stopPlainDetachIfIdle() error {
return nil
}
// StopFlipAt is when admission last closed for a stop (zero if never).
func (b *StorageBackend) StopFlipAt() time.Time {
b.mu.Lock()
defer b.mu.Unlock()
return b.stopFlipAt
}
// StopIO makes the backend refuse every new Read, Write and Sync with
// ErrNotReady (evidence), then waits, bounded by ctx, for the I/O admitted
// before the stop to finish. After a nil return no I/O admitted before the
@@ -823,6 +844,9 @@ func (b *StorageBackend) admit() (func(), error) {
b.ioMu.RUnlock()
return nil, err
}
if hook := b.testAfterGate; hook != nil {
hook()
}
b.mu.Lock()
if b.precopy != nil && b.precopy.active {
b.mu.Unlock()
@@ -102,7 +102,7 @@ func TestWorkspaceMoveRefusalNamesTheMissingPrecondition(t *testing.T) {
}{
{"unknown source", move("unplaced", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"), `move source unknown: no issued move or placement names replica "r1" at epoch 1`},
{"unknown target node", move("placed", "node-z", "127.0.0.1:19301", "127.0.0.1:19302"), `move target node "node-z" is not registered`},
{"target is the source", move("placed", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target "node-a" is the current source host`},
{"same-host clean still needs prepared endpoints", move("bound", "node-a", "127.0.0.1:19101", "127.0.0.1:19102"), `move target endpoints 127.0.0.1:19101/127.0.0.1:19102 on "node-a" are not registered (live bindings on that node: 127.0.0.1:19121/127.0.0.1:19122)`},
{"target on another host", move("placed", "node-b", "10.9.9.9:19311", "127.0.0.1:19312"),
`move target endpoints 10.9.9.9:19311/127.0.0.1:19312 on "node-b" are not registered (not on the node's hosts: it registers 127.0.0.1:19301/127.0.0.1:19302; no per-volume binding is prepared)`},
{"explicit binding elsewhere", move("bound", "node-b", "127.0.0.1:19301", "127.0.0.1:19302"),
@@ -0,0 +1,67 @@
package master
import (
"testing"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/protobuf/proto"
)
// INV-WS-SAME-HOST-CLEAN-MOVE-001: retirement belongs to an epoch, so the
// old epoch's replay cannot retire the re-prepared same-host binding.
func TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding(t *testing.T) {
h, conn, ctx := reviewBindingHost(t)
reviewCreate(t, conn, ctx, "v")
ws := control.NewWorkspaceServiceClient(conn)
b := &control.WorkspaceBinding{VolumeId: "v", ServerId: "node-a", DataAddr: "127.0.0.1:10000", CtrlAddr: "127.0.0.1:10001"}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal(err)
}
if _, err := ws.PlaceWorkspace(ctx, &control.WorkspacePlacement{VolumeId: "v", ServerId: "node-a", ReplicaId: "r1"}); err != nil {
t.Fatal(err)
}
reviewHeartbeat(t, conn, ctx, "v", "node-a", b.DataAddr, b.CtrlAddr)
if _, err := h.RunLifecycleProductTick(); err != nil {
t.Fatal(err)
}
if line := waitAuthorityLine(t, h.Publisher(), "v"); line.Epoch != 1 {
t.Fatal(line)
}
id := &control.WorkspaceIdentity{VolumeId: "v", ReplicaId: "r1", Epoch: 1}
if _, err := ws.RenewWorkspaceLease(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.RevokeWorkspace(ctx, id); err != nil {
t.Fatal(err)
}
if _, err := ws.AckWorkspaceRevoked(ctx, &control.WorkspaceRevocationAck{Identity: id, HeadGen: 9}); err != nil {
t.Fatal(err)
}
if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(got) != 1 || !got[0].Retired {
t.Fatal("ACK did not retire the old binding", got, err)
}
req := &control.WorkspaceMove{RequestId: "return", VolumeId: "v", ExpectedReplicaId: "r1", ExpectedEpoch: 1, TargetReplicaId: "r1", TargetServerId: "node-a", TargetDataAddr: b.DataAddr, TargetCtrlAddr: b.CtrlAddr, Kind: "clean"}
if _, err := ws.MoveWorkspace(ctx, req); err == nil {
t.Fatal("same-host move accepted an unprepared retired binding")
}
if _, err := ws.RegisterWorkspaceBinding(ctx, b); err != nil {
t.Fatal("same-host re-prepare refused", err)
}
forced := proto.Clone(req).(*control.WorkspaceMove)
forced.Kind, forced.Force = "forced", true
if _, err := ws.MoveWorkspace(ctx, forced); err == nil {
t.Fatal("same-host forced move accepted over RPC")
}
if _, err := ws.MoveWorkspace(ctx, req); err != nil {
t.Fatal("same-host clean move refused over RPC", err)
}
if _, err := ws.MoveWorkspace(ctx, req); err != nil {
t.Fatal("same-host move replay refused", err)
}
if line, _ := h.Publisher().VolumeAuthorityLine("v"); line.Epoch != 2 || line.DataAddr != b.DataAddr || line.CtrlAddr != b.CtrlAddr {
t.Fatal("same-host move did not publish exactly the next epoch", line)
}
if got, ok, err := h.Lifecycle().WorkspaceBindings.Get("v"); err != nil || !ok || len(got) != 1 || got[0].Retired {
t.Fatal("old epoch retired the re-prepared binding", got, err)
}
}
@@ -323,7 +323,9 @@ func (s *services) workspaceMoveCheckLocked(q *control.WorkspaceMove) (req autho
refusal = fmt.Sprintf("move source unknown: no issued move or placement names replica %q at epoch %d", q.GetExpectedReplicaId(), q.GetExpectedEpoch())
case !ok:
refusal = fmt.Sprintf("move target node %q is not registered", q.GetTargetServerId())
case target.ServerID == oldHost:
// INV-WS-SAME-HOST-CLEAN-MOVE-001: the authority clean-proof
// checks still run after these endpoint and binding checks.
case target.ServerID == oldHost && (q.GetKind() != "clean" || q.GetForce()):
refusal = fmt.Sprintf("move target %q is the current source host", target.ServerID)
case !replay && s.host.colocatedTargetRefused(target.ServerID):
refusal = fmt.Sprintf("move target node %q shares the authority store's file system (strict journal isolation)", target.ServerID)
@@ -0,0 +1,26 @@
package wsclient
import (
"context"
"errors"
"fmt"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// CleanMove implements M2 Acked -> Moved (clean), INV-WS-CLEAN-MOVE-001.
// The master checks the actual detached HEAD and recorded ACK.
func (c *Client) CleanMove(ctx context.Context, q *control.WorkspaceMove) (*control.WorkspaceGrant, error) {
const op = "clean move"
if q.GetKind() != "clean" || q.GetForce() || q.GetVolumeId() == "" || q.GetRequestId() == "" || q.GetExpectedReplicaId() == "" || q.GetExpectedEpoch() == 0 || q.GetTargetReplicaId() != q.GetExpectedReplicaId() || q.GetTargetServerId() == "" || q.GetTargetDataAddr() == "" || q.GetTargetCtrlAddr() == "" {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("clean move requires explicit identity, request id and target endpoints; force is not allowed")}
}
g, err := c.rpc.MoveWorkspace(ctx, q)
if err != nil {
return nil, classify(op, err)
}
if err := checkGrant(g, q); err != nil {
return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: fmt.Errorf("%v; rerun with the same request id", err)}
}
return g, nil
}
+25
View File
@@ -0,0 +1,25 @@
package wsclient
import (
"context"
"errors"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// Revoke implements M2 Granted -> Revoking (INV-WS-CLEAN-MOVE-001).
// Its reply proves the request was recorded, not that the host has ACKed.
func (c *Client) Revoke(ctx context.Context, id *control.WorkspaceIdentity) (*control.WorkspaceLeaseFact, error) {
const op = "workspace revoke"
if id.GetVolumeId() == "" || id.GetReplicaId() == "" || id.GetEpoch() == 0 {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("volume, replica and positive epoch are required")}
}
lease, err := c.rpc.RevokeWorkspace(ctx, id)
if err != nil {
return nil, classify(op, err)
}
if lease.GetVolumeId() != id.GetVolumeId() || lease.GetReplicaId() != id.GetReplicaId() || lease.GetEpoch() != id.GetEpoch() || !lease.GetRevoking() {
return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: errors.New("reply does not match the requested revoking identity")}
}
return lease, nil
}
+24
View File
@@ -0,0 +1,24 @@
package wsclient
import (
"context"
"errors"
control "github.com/seaweedfs/seaweed-block/core/rpc/control"
)
// Show reads the existing M2 lease/ACK/move view. It grants no authority.
func (c *Client) Show(ctx context.Context, volume string) (*control.WorkspaceStatus, error) {
const op = "workspace show"
if volume == "" {
return nil, &Error{Outcome: OutcomeRefusedLocally, Op: op, Err: errors.New("volume is required")}
}
view, err := c.rpc.QueryWorkspace(ctx, &control.WorkspaceVolume{VolumeId: volume})
if err != nil {
return nil, classify(op, err)
}
if view == nil {
return nil, &Error{Outcome: OutcomeUnknown, Op: op, Err: errors.New("missing workspace reply")}
}
return view, nil
}
+2 -2
View File
@@ -213,11 +213,11 @@ func (c *Client) ForceMove(ctx context.Context, m ForcedMove) (*control.Workspac
}
// checkGrant binds a successful answer to the request that was sent: an
// issued forced grant for this request id and volume, from the expected
// issued grant of the requested kind for this request id and volume, from the expected
// holder at the expected epoch to the requested target, at a higher epoch.
// Anything else leaves the outcome unknown.
func checkGrant(g *control.WorkspaceGrant, q *control.WorkspaceMove) error {
if !g.GetIssued() || g.GetKind() != "forced" || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() ||
if !g.GetIssued() || g.GetKind() != q.GetKind() || g.GetRequestId() != q.GetRequestId() || g.GetVolumeId() != q.GetVolumeId() ||
g.GetOldReplicaId() != q.GetExpectedReplicaId() || g.GetOldEpoch() != q.GetExpectedEpoch() ||
g.GetNewReplicaId() != q.GetTargetReplicaId() || g.GetNewHost() != q.GetTargetServerId() || g.GetNewEpoch() <= g.GetOldEpoch() {
return fmt.Errorf("the answer does not match the request (issued=%t kind=%q request=%q volume=%q old=%s@%d new=%s@%d on %q)",
@@ -0,0 +1,76 @@
package storage
import (
"context"
"errors"
"testing"
)
// Abort at a witnessed PUT boundary, after three immutable chunks are stored.
// Count submitted bytes as well as completed PUTs so a retransmission cannot
// hide behind a successful final HEAD.
type abortUploadBytesRemote struct {
*fakeChunkRemote
cancel context.CancelFunc
calls, stored, submittedBytes, storedBytes int
}
func (r *abortUploadBytesRemote) Put(ctx context.Context, key string, b []byte) error {
r.calls++
r.submittedBytes += len(b)
if r.stored == 3 && r.cancel != nil {
r.cancel()
return ctx.Err()
}
if err := r.fakeChunkRemote.Put(ctx, key, b); err != nil {
return err
}
r.stored++
r.storedBytes += len(b)
return nil
}
// INV-CUT-STAGED-REUSE-001: an interrupted rolling cut retains its completed
// uploads in-process; retrying the unchanged image sends only the remainder.
func TestChunkStageV3_MidUploadAbortReducesRetryBytes(t *testing.T) {
s, f, l, w := precopyLayer(t, 1, 5)
l.cfg.COWSpillLimit = ctChunkBytes
l.cfg.UploadConcurrency = 1
ctx, cancel := context.WithCancel(ctTimeout(t))
defer cancel()
r := &abortUploadBytesRemote{fakeChunkRemote: f, cancel: cancel}
l.remote = r
before := f.stats().head
frontier := s.NextLSN() - 1
want := w.imageAt(frontier)
if _, err := l.Cut(ctx); !errors.Is(err, context.Canceled) {
t.Fatalf("mid-upload cut: %v, want cancellation", err)
}
if f.stats().head.Gen != before.Gen {
t.Fatal("aborted cut published HEAD")
}
if r.calls != 4 || r.stored != 3 || r.storedBytes != 3*ctChunkBytes {
t.Fatalf("abort boundary: calls=%d stored=%d bytes=%d", r.calls, r.stored, r.storedBytes)
}
firstCalls, firstStored := r.calls, r.stored
firstSubmitted, firstBytes := r.submittedBytes, r.storedBytes
r.cancel = nil
result, err := l.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
retryCalls, retryStored := r.calls-firstCalls, r.stored-firstStored
retrySubmitted, retryBytes := r.submittedBytes-firstSubmitted, r.storedBytes-firstBytes
t.Logf("first: PUTs=%d stored=%d submitted_bytes=%d stored_bytes=%d; retry: PUTs=%d stored=%d submitted_bytes=%d stored_bytes=%d", firstCalls, firstStored, firstSubmitted, firstBytes, retryCalls, retryStored, retrySubmitted, retryBytes)
if retryCalls != 2 || retryStored != 2 || retryBytes != 2*ctChunkBytes || retrySubmitted != retryBytes {
t.Fatalf("retry did not send only the two remaining chunks: PUTs=%d stored=%d submitted=%d stored_bytes=%d", retryCalls, retryStored, retrySubmitted, retryBytes)
}
if retrySubmitted >= firstSubmitted || retryBytes >= firstBytes {
t.Fatal("retry uploaded at least as many bytes as the aborted attempt")
}
if result.Head.RemoteLSN != frontier {
t.Fatalf("retry frontier=%d want%d", result.Head.RemoteLSN, frontier)
}
assertImage(t, "retry image", f.imageOf(t, result.Head), want)
assertNoIntentsLeft(t, f)
}
@@ -0,0 +1,93 @@
package storage
import (
"context"
"errors"
"testing"
)
// revokingBudget admits every cut and keeps its abort, so the test can
// revoke the cut's host budget the way the limiter does at MaxHold.
type revokingBudget struct{ abort func(error) }
func (b *revokingBudget) Admit(_ context.Context, _ int64, abort func(error)) (uint64, error) {
b.abort = abort
return 1, nil
}
func (b *revokingBudget) ReserveCOW(uint64, int64) error { return nil }
func (b *revokingBudget) Release(uint64) {}
// revokeAfterRemote revokes the budget at the PUT after `after` completed
// ones. Every PUT attempt is counted before it reaches the fake, so a
// re-send of a completed key is recorded even if the caller then
// reconciles it.
type revokeAfterRemote struct {
*fakeChunkRemote
budget *revokingBudget
after int // revoke once this many PUTs completed; < 0: never
completed int
bytes int // bytes of every PUT attempt
dups int // attempts for a key that already completed
keys map[string]bool
}
func (r *revokeAfterRemote) Put(ctx context.Context, key string, b []byte) error {
if r.after >= 0 && r.completed == r.after {
r.budget.abort(errors.New("test: cut held its host slot past MaxHold"))
<-ctx.Done()
return context.Cause(ctx)
}
r.bytes += len(b)
if r.keys[key] {
r.dups++
}
if err := r.fakeChunkRemote.Put(ctx, key, b); err != nil {
return err
}
r.keys[key] = true
r.completed++
return nil
}
// A cut whose host budget is revoked mid-upload (MaxHold) keeps the
// chunks it already uploaded: the next cut uploads only the rest, fewer
// bytes than the whole dirty set, and retransmits nothing.
func TestCutRevokedMidUploadKeepsItsUploads(t *testing.T) {
const dirty = 5
s, f, l, w := precopyLayer(t, 0, dirty)
l.cfg.UploadConcurrency = 1
budget := &revokingBudget{}
r := &revokeAfterRemote{fakeChunkRemote: f, budget: budget, after: 2, keys: map[string]bool{}}
l.remote = r
l.cfg.Budget = budget
base := f.stats().head.Gen
if _, err := l.Cut(ctTimeout(t)); !errors.Is(err, errCutBudgetRevoked) {
t.Fatalf("first cut: %v; want the budget revocation", err)
}
if f.stats().head.Gen != base {
t.Fatal("a revoked cut moved HEAD")
}
first := r.bytes
if first != 2*ctChunkBytes {
t.Fatalf("first attempt uploaded %d bytes before the revocation; want %d", first, 2*ctChunkBytes)
}
r.after, r.bytes = -1, 0
result, err := l.Cut(ctTimeout(t))
if err != nil || result.Head.Gen != base+1 {
t.Fatalf("retry: %+v %v", result, err)
}
if result.Stats.StageRounds != 0 {
t.Fatalf("the retry staged (%d rounds); this control is for uploads made after the barrier", result.Stats.StageRounds)
}
if r.dups != 0 {
t.Fatalf("%d PUTs re-sent an already completed key", r.dups)
}
if r.bytes >= dirty*ctChunkBytes || r.bytes != (dirty-2)*ctChunkBytes {
t.Fatalf("retry uploaded %d bytes; want only the %d chunks not yet uploaded (%d bytes), less than the dirty set (%d)",
r.bytes, dirty-2, (dirty-2)*ctChunkBytes, dirty*ctChunkBytes)
}
assertImage(t, "published image", f.imageOf(t, result.Head), w.imageAt(s.NextLSN()-1))
assertNoIntentsLeft(t, f)
}
@@ -0,0 +1,41 @@
package storage
import (
"bytes"
"errors"
"testing"
)
// INV-WS-SAME-HOST-CLEAN-MOVE-001: the returning host consumes its sealed
// image only with a newly issued epoch; same-epoch reopening stays sealed.
func TestClaimChunkHeadSameHostCleanMovePreservesSealedImage(t *testing.T) {
s, _ := newChunkTestStore(t)
r := newFakeChunkRemote()
layer := mustAttach(t, s, r, ctConfig(1))
want := makeBlock(4096, 0x63)
if _, err := s.Write(0, want); err != nil {
t.Fatal(err)
}
if _, err := s.Sync(); err != nil {
t.Fatal(err)
}
if _, err := layer.Detach(ctTimeout(t)); err != nil {
t.Fatal(err)
}
sealed := copyHead(r.stats().head)
if _, err := ClaimChunkHead(ctTimeout(t), r, ctConfig(1)); !errors.Is(err, ErrChunkLayerDetached) || !sameHead(r.stats().head, sealed) {
t.Fatal("same-epoch reopen consumed the seal", err)
}
claimed, err := ClaimChunkHead(ctTimeout(t), r, ctConfig(2))
if err != nil {
t.Fatal(err)
}
expected := copyHead(sealed)
expected.Gen++
expected.Epoch = 2
expected.State = ChunkHeadActive
expected.DetachedBy = nil
if !sameHead(claimed, expected) || !bytes.Equal(r.imageOf(t, claimed)[:4096], want) {
t.Fatalf("same-host claim changed sealed image/frontier: sealed=%+v claimed=%+v", sealed, claimed)
}
}
@@ -359,12 +359,17 @@ stateDiagram-v2
Granted --> Granted: Renew before horizon and deadline (from memory)
Granted --> Revoking: BeginWorkspaceRevocation
Revoking --> Acked: host acks detached HEAD gen while the lease is valid
Acked --> Moved: CLEAN move
Acked --> Moved: CLEAN move, including same host, new epoch
Granted --> Expired: horizon or deadline passes
Expired --> Granted: unchanged holder, no move/revocation, MAX expiry + skew passed; durable re-grant
Expired --> Moved: FORCED move after expiry + skew bound, then HEAD read (an older-epoch HEAD is accepted)
}
```
**Return after lease expiry.** A new process of the unchanged holder and epoch may obtain one durable re-grant after the existing forced-move barrier: both the persisted horizon and granted/restart deadline plus full skew have passed. Re-grant and forced issue serialize under the publisher lock; the winner prevents the competing operation. Revocation, a pending move or uncertain persistence refuses a usable grant. Existing fenced guards remain terminal. The returning process claims a new HEAD generation before I/O, keeps its local acknowledged WAL, and publishes it on the first cut. An empty local root restores only HEAD; a same-epoch sealed HEAD remains detached.
**Same-host planned return.** A sealed volume can be moved cleanly back to its source host after the exact detached-generation ACK was recorded. The move issues a higher epoch even when the host and endpoints are unchanged. The returning process claims the sealed HEAD before serving; a same-epoch reopen remains detached. Forced moves to the source host remain refused. Re-preparing the binding preserves the old retired-epoch tag, so replaying that retirement cannot retire the new binding.
**Moving back to a host with a surviving local file.** A fresh volume claims HEAD before serving. A non-fresh attach reads HEAD first; if another holder published it, the attach fails closed with `ErrChunkStaleLocalRoot` (`core/frontend/durable/provider_chunk.go`): the volume is not served, and one log line and the status evidence name the local root to remove or quarantine, after which the next attach starts fresh from HEAD (#167).
## 8. Security model
+154 -50
View File
@@ -56,19 +56,19 @@ stateDiagram-v2
| 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 | 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`, `INV-WAL-V3-ACTIVATION-001`, `INV-WAL-V3-DESCRIPTOR-001`, `INV-WAL-V3-MAP-PUBLISH-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 | `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 | `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`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-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 | `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`, `INV-WAL-V3-W-RECOVERY-001`, `INV-WAL-V3-FENCE-001`, `INV-WAL-V3-MAP-PUBLISH-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`, `INV-WAL-V3-W-RECOVERY-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`, `INV-WAL-V3-W-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 | `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`, `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`, `INV-WAL-V3-RECLAIM-001`, `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` |
| Serving | FaultLatched | the first failed `fsync` of the store file, or a WAL append whose write failed | `core/storage/walstore.go` `noteFsyncFailure`, `syncFile`; `core/storage/walstore_v3.go` `appendWriteV3` | `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` | — |
The v2 writer, scanner, checkpoint path, C11 codec/reconciler and in-place converter are retired. Native map and descriptor rules remain enforced; v2 inputs refuse open without mutation. `TestNativeReplacementLegacyBytesRefusedWithoutMutation` and `TestChunkAttachRefusesAnUnmappedNativeStore` cover these admission boundaries. The receiver session bitmap 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 (`INV-WAL-V3-OWNER-001`). Contention refuses open without changing bytes; descriptor close or process exit releases ownership. The offline converter is retired; legacy volumes refuse open unchanged. 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`).
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 (`INV-WAL-V3-OWNER-001`). Contention refuses open without changing bytes; descriptor close or process exit releases ownership. The offline converter is retired; legacy volumes refuse open unchanged. 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-FAIL-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.
@@ -96,9 +96,10 @@ blockmaster's publisher is the only component that mints epochs. Diagrams: the a
| 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-LEASE-HORIZON-MONO-001`, `INV-WS-RENEW-NONBLOCKING-001`, `INV-LEASE-VIEW-001`, `INV-WS-FORCED-MOVE-REPLY-001`, `INV-WS-FORCED-MOVE-HALF-SKEW-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-FORCED-MOVE-REPLY-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` |
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node other than the source, and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-001` |
| Acked | Moved (clean) | HEAD detached by the expected holder at the expected epoch, and the acknowledgement names that HEAD generation; the target may be the same host, with a newly issued epoch and every binding/collision/isolation check retained | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `validateWorkspaceMoveRequest`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-SAME-HOST-CLEAN-MOVE-001` |
| Acked or Expired | (move refused, nothing written) | blockmaster admits a move only with valid target endpoints (host:port, port 1..65535, data and ctrl distinct), a known source host, a registered target node (the source itself only for a clean, non-force move), and target endpoints that either match a live per-volume binding or, for a volume without bindings, lie on the target node's registered hosts (any port) and are not owned by another assignment or binding, and, under strict journal isolation, a target node whose durable root does not share the authority store's file system (the retry of an issued move excepted); each refusal names its condition and is logged | `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked`; `core/host/master/journal_isolation.go` `colocatedTargetRefused` | `INV-WS-CLEAN-MOVE-001`, `INV-WS-FORCED-MOVE-001`, `INV-MASTER-JOURNAL-ISOLATION-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 | Granted | Same current holder/epoch, no pending move or revocation/ACK, store certain; horizon and granted/restart deadline plus full skew both passed (the existing forced-move barrier); a busy authority writer refuses this attempt, otherwise persist the new horizon before its grant. A terminal guard stays terminal; a new process claims HEAD before I/O. | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked` | `INV-WS-LEASE-REGRANT-001`, `INV-WS-REOPEN-FENCE-001`, `INV-WS-CLAIM-BEFORE-SERVE-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, for the lease the last move issue started (never a predecessor's); blockmaster reads HEAD only after this admission; HEAD is the expected holder's at the expected epoch or any HEAD at an older epoch (the holder never claimed it, or an earlier holder's late claim landed; the lost range starts at that HEAD's remote LSN); a HEAD at the expected or a higher epoch that is not the expected holder's is refused; the lost range (the HEAD's remote LSN, the barrier as LostUntil, the HEAD's generation via the move record and the HEAD entry's filer mtime read with HEAD, or unknown) is written before the reservation. The OSS operator client sends the explicit force only with `--confirm-forced <volume>@<expected epoch>`; `PreviewWorkspaceMove` runs this admission (HEAD read only once admitted) and writes nothing | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`, `PreviewWorkspaceForcedMove`; `core/authority/workspace_lost_range.go` `recordLostRangeLocked`; `core/host/master/workspace_service.go` `MoveWorkspace`, `PreviewWorkspaceMove`; `core/rpc/wsclient/wsclient.go` `ForceMove` | `INV-WS-FORCED-MOVE-001`, `INV-WS-LEASE-HORIZON-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-FORCED-CONFIRM-001` |
| Moved | epoch issued | the move journal record is durable first; a retried request id gets the same epoch; the issue write starts the new holder's lease (horizon issue + 1.5·TTL, granted deadline issue + TTL), published with the epoch in one lease-view section and never lowering a deadline a renewal raised; the new holder is then Granted, and one that dies before its first renewal still expires; the answer to an issued forced move (also a replay) carries its stored lost range, or no range and the reason when that record is missing or fails its checks; a failure after the issue is answered as issued-but-failed (`Internal`, rerun with the same request id), never as a refusal, and the issue is still logged; an issuing write whose durable outcome is unknown is answered as unknown (`Internal`, restart then rerun with the same request id) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `issueWorkspaceMove`, `MoveWorkspace`; `core/authority/workspace_lease_view.go` `publishIssuedLeaseLocked`; `core/host/master/workspace_service.go` `grantWithLostRange`, `postIssueError` | `INV-AUTH-MOVE-JOURNAL-001`, `INV-LEASE-VIEW-001`, `INV-WS-LOST-RANGE-READOUT-001`, `INV-WS-LOST-RANGE-FAILCLOSED-001`, `INV-WS-LOST-RANGE-AUDIT-001`, `INV-WS-LOST-RANGE-UNCERTAIN-001` |
@@ -148,7 +149,7 @@ RF2 qualification limitation until ordered-live certification is wired (#297). S
| `Degraded` | `CatchingUp` or `NeedsRebuild` | the engine decides catch-up when the gap is in the primary WAL, rebuild when it is not | `core/engine/apply.go` `decide` | `INV-REPL-CATCHUP-REBUILD-001`, `INV-REPL-RECOVERY-SESSION-UNIQUE-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` |
| `NeedsRebuild` | — | no successor through `SetState` or `Invalidate`; the rebuild runs as a separate session (single-lane by default, dual-lane with `--recovery-mode=dual-lane`) | `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`).
@@ -258,7 +259,7 @@ stateDiagram-v2
| Pre-copy admission | (Not reachable in this release; see the note below.) opt-in: close frontend admission and drain registered operations for at most 100 ms before taking the store barrier; rejected attempts clear the pause and grant every waiter FIFO admission under one lock hold before ordinary uploads; each waiter rechecks the ordinary gate without waiting for another I/O to finish | `precopy_admission.go` `BeginPrecopyPause`; `chunk_precopy.go` `PrecopyDetachWithAdmission` | `INV-CUT-PRECOPY-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` |
| Pre-copy detach | (Not reachable in this release; see the note below.) at most five rolling attempts within a cooperative 60 s context; authoritative candidates and measured costs admit the final cut after the bounded drain; a known estimate may use the declared five-second freeze ceiling when it is at least 90% of the previous comparable known estimate or on the final physical round; frozen commands wait up to the five-second cutover budget and receive FIFO admission grants together after a safe abort, without serializing on I/O completion; each queue bound starts at the command arrival | `chunk_precopy.go`; `precopy_admission.go`; `DurableProvider.DetachVolume` | `INV-CUT-PRECOPY-001` |
| Guest-frozen detach | (Not reachable in this release; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001`, `INV-WS-FREEZE-REFUSAL-INPUTS-001` |
| Guest-frozen detach | (Not reachable in this release, except the HTTP400 validation; see the note below.) `frozen=true` carries a non-future guest freeze origin; invalid freeze options return HTTP400 `invalid_freeze_budget` before any provider admission or mutation (generic `bad_request` is not that proof); forecast before staging, recheck authoritative candidates after Sync, and perform at most one cut. Ordinary frozen refusal issues no staging/payload upload and retains dirty bytes. Explicit `allowOverBudget=true` records `over_budget` and retains authority, drain and CAS settlement checks; actual whole-guest elapsed still reports a five-second violation. | `chunk_frozen_budget.go`; `chunk_precopy.go`; `captureLocked`; `DetachVolumeFrozen`; `/chunk/detach` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001`, `INV-WS-FREEZE-REFUSAL-001`, `INV-WS-FREEZE-REFUSAL-INPUTS-001` |
| Checkpoint tail | one cost observation reports remaining bytes, tail cost, frozen admission estimate/known bit, storage limit and quiesce slack after a cut. Same-host duration advice is rechecked at admission before upload. | `chunk_precopy.go` `candidateTail`; `chunk_frozen_budget.go` `frozenBudgetEstimate`; `chunk_control.go` `ChunkCutResponse` | `INV-CUT-PRECOPY-001`, `INV-WS-FREEZE-ACCOUNTING-001` |
| Pre-copy host drain | (Not reachable in this release; see the note below.) a committed freeze keeps commands held while host storage admission closes; transport teardown cancels held commands before joining the session, without issuing their storage work | `storage_adapter.go` `setOperationalLocked`; `nvme/session.go` `serve` | `INV-CUT-PRECOPY-001` |
| Copy | every candidate chunk (native owned LSN map relative to HEAD plus retained WAL/in-memory dirt) is read by a bounded upload worker at upload time; a staged copy is reused only if unchanged since staging; native copy occurs after barrier release with pre-publication COW ownership | `core/storage/chunk_layer.go` `captureLocked` | `INV-CUT-QUIESCED-001`, `INV-CUT-STAGED-REUSE-001`, `INV-CUT-BITMAP-001`, `INV-CUT-READ-LOGICAL-001`, `INV-CUT-GUEST-BOUNDED-WAIT-001` |
@@ -271,7 +272,7 @@ stateDiagram-v2
| Settled | drop the intents; settle native map capture tokens, keeping chunks dirtied after the cut; a refused current-lineage point retains intent-rooted completed uploads until reuse, supersession or clean Close (unresolved CAS roots excluded) | `core/storage/chunk_layer.go` `finishCut` | `INV-CUT-BITMAP-001` |
| Pending | the outcome is unknown and HEAD still shows the CAS base: keep the proposal and its intents | `core/storage/chunk_layer.go` `captureLocked` | `INV-WS-CAS-UNKNOWN-001` |
Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged.
Not reachable in this release: the frozen detach and the pre-copy detach. `/chunk/detach` refuses a valid `frozen` request with `frozen_detach_unsupported` before any provider call (`INV-CUT-FROZEN-DETACH-REFUSED-001`), and blockvolume refuses to start with `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`). So the transitions Admit → FrozenForecast, FrozenForecast → Refused, FrozenForecast → Quiesce, Quiesce → Refused (guest-frozen recheck), Quiesce → FinalFreeze and FinalFreeze → OpenWindow, and the rows Pre-copy admission, Pre-copy detach, Guest-frozen detach (apart from its HTTP400 validation) and Pre-copy host drain, are not reached by a released process. Their code is kept and still tested below the HTTP handler; the text above is unchanged.
Periodic HEAD cuts default to 15 minutes in blockvolume (OSS minimum 5 minutes;
0 explicitly disables); they do not create named snapshots. One five-minute
@@ -289,7 +290,7 @@ HEAD states, snapshots, forks, intents, key bindings, GC and volume delete in th
| — | `active` (gen 1, epoch 0) | the first HEAD is an exclusive create (`CASHead` with expected gen 0); a fork or restore HEAD carries the parent's `RemoteLSN` and references | `core/frontend/chunkstore/chunk_remote.go` `CASHead`; `core/frontend/chunkstore/catalog.go` `EnsureVolume`, `Fork`, `Restore` | `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` |
| `detached` | `active` | takeover CAS at a higher issued epoch, including a clean move to the same host | `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` |
@@ -409,7 +410,7 @@ Tests: `TestSnapshotSchedule_SlotsAreOffsetPerVolume`, `_FailureIsTypedAndBacksO
## Part B. Invariant ledger
224 rows: 201 ACTIVE, 20 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 209 new.
306 rows: 220 ACTIVE, 83 STUB, 3 ARCHIVED; 15 kept from the internal ledger, 291 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.
@@ -420,38 +421,113 @@ The "Machine / transition" column refers to Part A. Notes under a table record w
| `INV-REBUILD-SNAPSHOT-COMPLETE-001` | A rebuild snapshot returns all readable nonzero blocks or an error, never a partial success. The sender propagates snapshot failure before shipping blocks or RebuildDone. | M3 NeedsRebuild (base enumeration) | `core/storage/logical_storage.go` `AllBlocks`; storage implementations; `core/transport/rebuild_sender.go` `doRebuild` | `TestChunkHydration_SnapshotFailsOnReadError`, `TestRebuildSnapshotErrorNeverShipsPartialImage` | Existing fail-closed recovery contract; error propagation only | ACTIVE |
| `INV-WAL-SYNCED-RECOVERED-001` | After a crash without media corruption, `Recover` returns every write that a `Sync` acknowledged. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover` | `TestNativeReplacementTornWrapKeepsAcknowledgedSuffix` (`core/storage/legacy_replacement_v3_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-FE-NVME-READY-001` | Reads and writes on successfully recovered chunk volumes awaiting attachment wait up to 3s (or an earlier caller deadline) for attachment readiness before storage admission; NVMe readiness timeout/refusal returns Namespace Not Ready (SC0x82), DNR=0, without reading or mutating storage; closed/stale lineage retain their ANA errors and physical I/O faults retain Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `readyCheck`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable`; `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` | — | ACTIVE |
| `INV-FE-NVME-READY-001` | A read or write on a successfully recovered chunk volume awaiting attachment waits for attachment readiness, before storage admission, for at most 3 s or until an earlier caller deadline, on the local monotonic clock. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `admitAfterAttachUnqueued`, `awaitAttachAdmission`, `readyCheck` | `TestWALStoreChunk_PendingReadWaitIsBounded`; `TestWALStoreChunk_PendingReadHonoursEarlierDeadline`; `TestWALStoreChunk_TakeoverWriteWaitsForAttach`; `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE |
| `INV-FE-NVME-READY-STATUS-001` | An NVMe read or write whose attachment-readiness wait times out or is refused completes with Namespace Not Ready (SC 0x82), DNR=0, without reading or mutating storage. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestWALStoreChunk_TakeoverReadBeforeAttachIsRetryable`; `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestWALStoreChunk_PendingAttachBeyondHostRetryBudget` (`core/frontend/durable/takeover_read_ready_test.go`) | — | ACTIVE |
| `INV-FE-NVME-READY-ANA-001` | An I/O that ends during the attachment-readiness wait because the backend closed or its lineage went stale keeps its ANA error, and a physical I/O fault keeps Internal Error. | M1 Opened / Recovering → Serving | `core/frontend/durable/storage_adapter.go` `attachReadyTimeout`; `core/frontend/nvme/io.go` `mapBackendError` | `TestSessionReadNotReadyIsRetryable` (`core/frontend/nvme/read_ready_retry_test.go`); `TestReadReadinessWaitDoesNotHoldAdmissionAndCloseWakesIt` (`core/frontend/durable/read_ready_wait_test.go`) | — | ACTIVE |
| `INV-WAL-REPLAY-LWW-001` | Replay of the validated native prefix retains the highest admitted LSN per LBA; invalid cursor, nonce or LSN order is refused. | M1 Recovering | `core/storage/dirty_map.go` `putAtIfNewer` | `TestWALLSNOrderV3_RefusesDuplicateAndLower` (`core/storage/wal_lsn_order_v3_test.go`) | `WALRecovery` `ReplayLastWriter` | ACTIVE |
| `INV-WAL-REUSE-PERSISTED-TAIL-001` | The WAL writer reuses only bytes that the both durable descriptor slots has already released. | M1 write lifecycle: Checkpointed → Reusable | `core/storage/wal_io_v3.go` `append`; `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3` | `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_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` | `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`); `TestNativeReplacementCheckpointSIGKILL` (`core/storage/legacy_checkpoint_replacement_v3_linux_test.go`) | `WALRecovery` `I1` | ACTIVE |
| `INV-WAL-FRONTIER-GAP-001` | A durable BASE anchor and its contiguous synced install-lane suffix survive recovery; an unpersisted frontier jump is not admitted. | M1 Recovering | `core/storage/walstore_v3.go` `recoverV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_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_map_checkpoint_v3.go` `publishCheckpointV3` | `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_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` | `TestNativeReplacementDataFsyncFailureIsSticky` (`core/storage/legacy_replacement_v3_test.go`); `TestNativeReplacementCallerPublicationFaults` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_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_v3.go` `latchV3`, `appendWriteV3` | `TestNativeReplacementQueuedApplyAfterFailedAppend` (`core/storage/legacy_replacement_v3_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_v3.go` `latchV3`, `appendWriteV3` | `TestNativeReplacementQueuedApplyAfterFailedAppend` (`core/storage/legacy_replacement_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_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`); `TestNativeReplacementSyncCallerReturnOrdering` (`core/storage/legacy_sync_replacement_v3_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` (`core/storage/walstore_activation_test.go`); `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy` (`core/storage/walstore_activation_test.go`); `TestWALStoreProductionCreateOptions` (`core/storage/walstore_activation_test.go`); `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`); `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN` (`core/frontend/durable/provider_format_v3_test.go`); `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE |
| `INV-WAL-V3-ACTIVATION-001` | Public create produces an owned-map v3/impl3 volume with the requested chunk geometry, in mode C unless mode A is requested. | M1 open/create/readonly | `core/storage/walstore.go` `CreateWALStoreWithOptions`; `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestWALStoreProductionSelectorCreatesMappedV3`, `TestWALStoreProductionCreateOptions` (`core/storage/walstore_activation_test.go`) | Selector wiring only; native protocol remains the accepted composed format model, not a new model proof | ACTIVE |
| `INV-WAL-V3-ACTIVATION-FALLBACK-001` | When descriptor slot A is damaged without being a valid legacy superblock and slot B is valid, writable and read-only open select slot B. | M1 open/create/readonly | `core/storage/walstore_v3.go` `refuseLegacyWALStore`, `openWALStoreV3File`; `core/storage/walstore_readonly_v3.go` `openReadOnlyV3`; `core/storage/superblock_v3.go` `selectSlotV3` | `TestWALStoreProductionFallsBackWhenDamagedSlotOnlyLooksLegacy` (`core/storage/walstore_activation_test.go`) | — | ACTIVE |
| `INV-WAL-V3-ACTIVATION-PROVIDER-001` | The durable provider's capture, HEAD restore and status paths probe, open and create volumes through the public v3 selectors (`ProbeWALStoreV3`, `OpenWALStore`, `CreateWALStoreWithOptions`). | M1 open/create/readonly | `core/frontend/durable/provider.go` `openOrCreate` | `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN`, `TestDurableProviderV3_StatusTracksRecoverSyncAndCapture` (`core/frontend/durable/provider_format_v3_test.go`) | — | ACTIVE |
| `INV-WAL-V3-LEGACY-FIXTURE-ISOLATION-001` | No default-build production code calls a legacy fixture constructor, and no legacy fixture is in the transitive import closure of the production storage packages. | M1 open/create/readonly | build layout: legacy fixtures outside the default production import closure | `TestLegacyFixtureIsolation` (`core/storage/legacy_fixture_isolation_test.go`) | — | 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-DESCRIPTOR-001` | A v3 descriptor slot is used only if it is valid: a matching CRC32C (Castagnoli), every reserved byte zero, an accepted impl, a nonzero slotGen at most 2^64-2, a nonzero nonce, and geometry consistent under checked arithmetic. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `decodeSlotV3`, `descriptorV3.validate`, `checkedAddV3` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3CounterExhaustion` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-BASE-001` | A valid v3 descriptor slot has CheckpointLSN ≤ mapCoveredCheckpoint ≤ W, and BASE fields that follow the rules of its BASE state. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `descriptorV3.validate` | `TestSlotV3VectorsDecodeAsExpected`, `TestSlotV3InstalledMayHaveCursorBelowTail` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-SELECT-001` | Of the two v3 descriptor slots, open selects the valid selectable slot with the higher slotGen, and never a prepared migration slot. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`); `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` (`core/storage/walstore_close_v3_test.go`) | — | STUB |
| `INV-WAL-V3-DESCRIPTOR-CONFLICT-001` | Open is refused when both v3 descriptor slots are valid but carry the same slotGen with different bytes, or disagree on the UUID or the geometry. | M1 Opened (v3 descriptor selection) | `core/storage/superblock_v3.go` `selectSlotV3`, `sameGeometryV3` | `TestSlotV3Selection` (`core/storage/superblock_v3_test.go`) | — | STUB |
| `INV-WAL-V3-RECORD-001` | An impl-3 WAL record has a fixed 62-byte prefix, 70 bytes of overhead in all, a CRC32C (Castagnoli) and an explicit EntrySize. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `encodeWALEntryV3`, `payloadSizeV3` | `TestWALEntryV3_CanonicalBarrierBytes`, `TestWALEntryV3_TypeFootprints` | `WALRecovery` abstract record validity; physical byte rules are code-test obligations | STUB |
| `INV-WAL-V3-RECORD-REFUSE-001` | The impl-3 record codec refuses unknown types or flags, a zero nonce, invalid per-type geometry, overflowing count, LSN, cursor or LBA spans, nonzero padding, a bad CRC or footer, and truncation, before allocating a payload. | M1 v3 record framing | `core/storage/wal_entry_v3.go` `payloadSizeV3`, `decodeWALEntryV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALEntryV3_RefusesInvalidEncode`, `TestWALEntryV3_RefusesMalformedWire`, `FuzzWALEntryV3_DecodeNeverPanics` | — | 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. One earliest command deadline spans adapter batches and the long store admission waits (capture, lifecycle); short locks (store, descriptor, WAL writer) are taken blocking and keep RWMutex writer preference, with the deadline checked once held. The deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write: an expired command starts no new payload WAL I/O, and expiry before append preserves the WAL/nextLSN/dirty state. A batch that returns a committed prefix with a storage error keeps that error in the classified error set. Issued WAL I/O retains its existing lifecycle ownership. Pure caller expiry stays retryable through required-observer classification and NVMe; a provided physical cause remains terminal. No wait grants reuse or acknowledges writes. | M1 Serving (write admission) | `walstore.go` `walUsedFraction`, `openInitializedInternal`; `wal_admission.go` `Acquire`; `write_command_budget.go`; `StorageBackend.Write`; NVMe `handleWrite` | `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestSessionWriteBudgetIncludesDispatchQueue`, `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`, `TestWALStoreV3WritePressureSampleMatchesOccupancy`, `TestStorageBackendExpiredWriteDoesNotAppend`, `TestStorageBackendRequiredObserverDeadlineStaysRetryable`; `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-ADMISSION-001` | v3 write admission measures WAL pressure from the active v3 writer's physical head minus the both-slot reuse floor, as a fraction of WALSize. | M1 Serving (write admission) | `core/storage/walstore.go` `openInitializedV3`, `WALStore.walUsedFraction`; `core/storage/write_command_budget.go` `WALStore.writePressureSample` | `TestWALStoreV3AdmissionUsesNativeOccupancy` (`core/storage/walstore_admission_v3_test.go`); `TestWALStoreV3WritePressureSampleMatchesOccupancy` (`core/storage/write_command_budget_test.go`); liveness under pressure: `TestWALStoreChunkV3_SequentialBurstFlush` (public provider and NVMe handler, default 64 MiB WAL, 320 MiB literal readback), `TestWALStoreChunkV3_BurstPatternBindsFullLBA` (32/64/256 MiB alias controls) (`core/frontend/durable/provider_chunk_burst_test.go`) | Existing reuse/durability rules unchanged; pressure/liveness is not a new model claim | ACTIVE |
| `INV-WAL-V3-ADMISSION-FAULT-001` | A terminal I/O fault latched while a v3 write waits on WAL pressure or for an admission slot ends that wait with the fault's original typed cause, also when the deadline has expired at the same check. | M1 Serving (write admission) | `core/storage/wal_admission.go` `walAdmission.acquireContext`, `walAdmission.terminalFault`; `core/storage/write_command_budget.go` `WALStore.writeBudgetError` | `TestWALStoreV3AdmissionReturnsFaultLatchedDuringPressureWait` (Write and WriteBatch); `TestWALStoreV3WriteBudgetKeepsTerminalFault` (`core/storage/write_command_budget_test.go`) | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-DEADLINE-001` | One command deadline, the earlier of the caller's deadline and the command's arrival plus `WriteCommandBudget`, bounds every adapter batch of a write and its store waits for the capture and lifecycle locks, on the local clock. | M1 Serving (write admission) | `core/frontend/write_budget.go` `WithWriteBudget`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `writeBytes`; `core/storage/write_command_budget.go` `WALStore.writeAdmissionDeadline`, `WALStore.acquireWriteLock`; `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendWriteKeepsOneDeadlineAcrossBatches`, `TestWALStoreV3WriteContextDeadlineIncludesCaptureWait`, `TestWALStoreV3WriteBudgetIncludesPostAdmissionWait`, `TestSessionWriteBudgetIncludesDispatchQueue` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-SHORTLOCK-001` | A v3 write takes the store, descriptor and WAL writer locks blocking, never by polling, so RWMutex writer preference holds, and its command deadline is checked once they are held. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext`; `core/storage/write_command_budget.go` `WALStore.writePressureSample`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3ExpiredWriterRefusesAfterShortLockWait`, `TestWALStoreV3WriteKeepsWriterPreferenceUnderReaders`, `TestWALStoreV3WriteBudgetRefusesAfterDescriptorWaitBehindSync` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-NOPAYLOAD-001` | A v3 write whose command deadline has passed starts no new payload WAL write: the deadline is checked again after a checkpoint rollover and inside the WAL writer after its descriptor snapshot, lock wait and encoding, before the first payload write. | M1 Serving (write admission) | `core/storage/walstore_v3.go` `WALStore.appendWriteV3`, `WALStore.writeBatchV3Locked`, `WALStore.v3BudgetAfterRollover`; `core/storage/wal_io_v3.go` `walWriterV3.append` | `TestWALStoreV3WriteBudgetRefusesNewPayloadAfterRollover`, `TestWALStoreV3WriteBudgetRechecksAfterRollover` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-EXPIRY-STATE-001` | A v3 write refused for an expired deadline before its append leaves the WAL bytes, nextLSN and the dirty map unchanged. | M1 Serving (write admission) | `core/storage/walstore.go` `WALStore.WriteContext`, `WALStore.WriteBatchContext` | `TestStorageBackendExpiredWriteDoesNotAppend` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-PREFIX-ERR-001` | A write batch that returns a committed prefix with a storage error keeps that error in the error set the frontend classifies. | M1 Serving (write admission) | `core/frontend/durable/storage_adapter.go` `writeFullBlockBatch`, `withStorageCause`, `observeWriteCause` | `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline` | — | ACTIVE |
| `INV-WAL-V3-ADMISSION-RETRYABLE-001` | A write that fails only because the caller's deadline expired is reported retryable, also through a required write observer and on NVMe; a write whose error carries a physical cause is reported terminal. | M1 Serving (write admission) | `core/frontend/write_budget.go` `IsWriteDeadline`; `core/frontend/durable/storage_adapter.go` `StorageBackend.Write`, `replicationWriteError`; `core/frontend/nvme/io.go` `mapBackendError`; `core/frontend/nvme/session.go` `Session.handleWrite` | `TestStorageBackendRequiredObserverDeadlineStaysRetryable`, `TestStorageBackendPartialBatchPhysicalFaultSurvivesObserverDeadline`; `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (`core/frontend/nvme/write_command_budget_test.go`) | — | ACTIVE |
| `INV-WAL-V3-RECLAIM-001` | A mapped v3 checkpoint at cp moves retainedTail only to the end of a complete validated record whose last LSN is at most cp minus the retention window, and, while a BASE is installing, never past BaseCursor. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`; `core/storage/wal_io_v3.go` `walWriterV3.reclaimThroughV3` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimKeepsPartialBatchAndRetention`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen` | Existing dual-slot retirement and nonce/cursor contract; concrete index/recovery/caller wiring is a code-test obligation | STUB |
| `INV-WAL-V3-RECLAIM-INDEX-001` | A physical v3 recovery rebuilds the writer's volatile record-boundary index only from trusted write records of the kept scan; an installing reopen indexes them without moving the writer's cursor. | M1 checkpoint / existing two-slot retirement | `core/storage/wal_io_v3.go` `walWriterV3.restoreScanV3`, `walWriterV3.rememberReclaimScanV3`, `walWriterV3.indexReclaimScanLockedV3`; `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestWALStoreV3ReclaimRebuildsIndexAfterPhysicalRecovery`, `TestWALStoreV3ReclaimAfterInstallingPhysicalReopen` | — | STUB |
| `INV-WAL-V3-RECLAIM-PUBLISH-001` | A mapped v3 checkpoint publishes retainedTail, retainedHead, the map root, CheckpointLSN and W in one slot publication, followed by a metadata-only rollover when the fallback slot still pins a lower tail. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.rolloverIfPinned` | `TestWALStoreV3CheckpointReclaimsAcrossRingLaps`, `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | — | STUB |
| `INV-WAL-V3-RECLAIM-FAIL-001` | When a v3 checkpoint publication or its rollover fails, no WAL byte is released for reuse and the dirty entries at or below the checkpoint stay unchanged for retry. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.rolloverCheckpointV3Locked`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestWALStoreV3ReclaimSecondSlotFailureKeepsOldPin` | — | STUB |
| `INV-WAL-V3-RECLAIM-EXCL-001` | No v3 writer is admitted between a checkpoint's slot publication and the end of both its rollover and its retirement of the dirty entries at or below the checkpoint. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.publishCheckpointV3`, `WALStore.retireCheckpointDirtyV3Locked` | `TestWALStoreV3ReclaimRetiresReferencesBeforeReuse` | — | STUB |
| `INV-WAL-V3-RECLAIM-SETTLE-001` | A pending v3 rollover (the fallback slot pinning a lower tail) is settled without a new checkpoint by the idle refresh, by a flusher cycle whose checkpoint does not advance, and by write admission. | M1 checkpoint / existing two-slot retirement | `core/storage/walstore_map_checkpoint_v3.go` `WALStore.rolloverCheckpointV3Locked`, `WALStore.persistOwnedMapCheckpointV3`; `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.appendWriteV3` | `TestWALStoreV3ReclaimRolloverProgressWithoutNewCheckpoint` | — | STUB |
| `INV-WAL-V3-OWNER-001` | v3 read/write open and offline readonly open 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 | `core/storage/volume_lock*.go`; `walstore_v3.go`; `walstore_readonly_v3.go` | `TestWALStoreV3CreatorKeepsOwnershipThroughPublication` (`core/storage/volume_lock_v3_test.go`); `TestWALStoreV3OwnerExcludesOpenAndReadOnly` (`core/storage/volume_lock_v3_test.go`); `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | 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` | `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`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `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. Extents are reused only when no live root references them (both slot roots, in-flight candidates, an uncertain candidate until reopen); the free tail is truncated above the highest live page. | M1 (dark map preparation only) | `core/storage/chunk_lsn_map_v3.go` `Prepare`, `readChunkLSNMapV3`; `core/storage/chunk_map_extents_v3.go` (live set, allocation, release, truncation); `core/storage/chunk_map_publication_v3.go` `publishMapV3`; `core/storage/descriptor_v3.go` (slot report, uncertain candidate) | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3StatsAfterReopen`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned` (`core/storage/chunk_map_extents_v3_test.go`); `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` (`core/storage/walstore_close_v3_test.go`); `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshAndSetWModeCloseTheWindow` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3AppendWriteErrorLatchesTheStore` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SyncRechecksTheFaultAtTheAckBoundary` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeWaitsForAHeldBatch` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3InstallingScanErrorIsTypedNotReady` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3Decision` (`core/storage/recovery_v3_test.go`); `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | `WALFormat` composed model | 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` | 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 (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); 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 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`, `TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`, `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 (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 | 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 | STUB |
| `INV-WAL-V3-CATCHUP-001` | A v3 catch-up source that is installing refuses with `ErrBaseInstalling` and emits nothing, also for an empty request at the head. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.ScanLBAs`, `WALStore.scanLBAsV3` | `TestCatchUpV3InstallingAtHeadRefuses` (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-CATCHUP-BASE-001` | A v3 catch-up request covered by an installed BASE (fromLSN at or below BaseLSN) fails with typed `WALRecycled`: the peer needs a rebuild. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3CompletedBASEUsesRebuild`, `TestCatchUpV3CompletedBASESuffix` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-CATCHUP-DAMAGE-001` | Damage in the retained v3 WAL makes a catch-up fail with a typed WAL integrity error and emit nothing. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `v3CatchUpEntries` | `TestCatchUpV3CorruptFirstRecordFails`, `TestCatchUpV3CorruptMiddleRecordFails` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-CATCHUP-REVALIDATE-001` | A v3 catch-up emits entries only from a scan whose recovery generation, nonce, BASE state and ID, install epoch, retainedTail and CheckpointLSN are unchanged after the scan. | M1 BASE lifecycle / M3 CatchingUp | `core/storage/walstore_recovery.go` `WALStore.scanLBAsV3` | `TestCatchUpV3InstallRetireABARefusesOldScan`, `TestCatchUpV3AfterCheckpointRingReuse`, `TestCatchUpV3ScanOverlappingCheckpointReuseIsRecycled` (tag `swblock_format_v3_test`) | — | STUB |
| `INV-WAL-V3-BINDING-001` | Every record and padding the v3 writer emits carries the selected nonce and its own absolute logical cursor and fits within WALSize of the both-slot reuse floor; an append that does not fit is refused. | M1 Recovering | `core/storage/wal_io_v3.go` `walWriterV3.append`, `walSnapshotV3` | `TestWALIOV3_RealWriterReopenScan`, `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_FloorAndPwriteFailureRefuse` (`core/storage/wal_io_v3_test.go`) | Record/lap admission is abstracted in composed WALFormatR5; physical framing/wrap boundaries remain code-test obligations | STUB |
| `INV-WAL-V3-SCAN-BINDING-001` | The v3 scanner checks a record's nonce and exact expected cursor before it uses the record's Length or count, and trusts the record only after the whole record validates again. | M1 Recovering | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-SCAN-STOP-001` | The v3 scanner skips only geometric end-of-ring slack and stops at the first untrusted record, never searching inside a payload for a later record. | M1 Recovering | `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALIOV3_WrapPaddingAndSlack`, `TestWALIOV3_EmbeddedRecordInPayloadIsNotScanned`, `TestWALIOV3_StopsAtBindingBeforeEmbeddedRecord` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-MAP-PUBLISH-001` | Once a v3 store has bound a validated map, every descriptor publication carries the bound map tuple or a prepared candidate's, with merged CheckpointLSN ≤ map coverage C ≤ merged W. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `sameMapTupleV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedWithMapV3` | `TestMapPublicationV3_IsolatedMergedCoverageAndWPositive`, `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestWALStoreV3_AutomaticMapCheckpoint`, `TestWALStoreV3_AutomaticCheckpointMetadataOrderAndRetry` | WALFormatR5 map coverage / volatile proof epoch; physical caller wiring remains a code obligation | STUB |
| `INV-WAL-V3-MAP-PUBLISH-REPLACE-001` | A prepared v3 map candidate is published only with a higher map generation, coverage not below the bound map's, and the same sidecar and proof domain with its epoch and mutation token unchanged since preparation; a stale candidate writes no slot. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3`, `prepareMapPublicationV3`, `mapPublicationProofV3.validV3` | `TestMapPublicationV3_ProofEpochAndMutationRefusal`, `TestMapPublicationV3_ProofChangedDuringPersistenceRefuses`, `TestMapPublicationV3_HeldPublicationsBothOrders`, `TestWALStoreV3_PreparedCheckpointRefusesChangedProof`, `TestCheckpointV3_EffectiveBaseWriteStillInvalidatesProof`, `TestCheckpointV3_DefiniteCutClearInvalidatesHeldProof`, `TestCheckpointV3_ExhaustedMutationCounterStillRefusesAppend` | — | STUB |
| `INV-WAL-V3-MAP-PUBLISH-ROLLOVER-001` | A v3 publication without a prepared map candidate (a W-only publication or a rollover) carries the bound map root unchanged. | M1 Serving (v3 map publication) | `core/storage/chunk_map_publication_v3.go` `validateMapPublicationV3` | `TestMapPublicationV3_CoverageWAndNoUnpreparedRoot`, `TestCheckpointV3_AppendRolloverAfterPrepareKeepsRetainedSuffix` | — | STUB |
| `INV-WAL-V3-FLUSH-LIFETIME-001` | A 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 v3 map candidate names immutable pages and root in the store's owned sidecar, checked against the descriptor's identity and geometry. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3`, `encodeMapPageV3`, `encodeMapRootV3` | `TestChunkLSNMapV3_PersistReloadAndReuse`, `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | WALFormatR5 abstract map dependency; physical encoding/digest/order are code obligations | STUB |
| `INV-WAL-V3-MAP-VALIDATE-001` | A v3 map read returns no entry before the root and every page pass their domain-separated body digests, zero reserved and unused bytes, exact page counts, file bounds and non-aliasing page intervals. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `readChunkLSNMapV3`, `mapReadAtV3` | `TestChunkLSNMapV3_CanonicalVectors`, `TestChunkLSNMapV3_CorruptionAndBounds`, `TestChunkLSNMapV3_RejectsRehashedMalformedRecords`, `TestChunkLSNMapV3_EntryBoundBeforeRootIO`, `TestChunkLSNMapV3_WholePageHashIsNotBodyDigest` | — | STUB |
| `INV-WAL-V3-MAP-PERSIST-ORDER-001` | A v3 map candidate exists only after its new pages are written and fsynced, then its root is written and fsynced, then the sidecar's directory is fsynced. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_OrderOwnedOpenAndClippedPage` | — | STUB |
| `INV-WAL-V3-MAP-PERSIST-FAIL-001` | An error inside a v3 map persistence transaction yields no candidate and latches the store against later I/O; a preflight or Stat error latches nothing. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkLSNMapV3_FailureDoesNotPublishOrReuse`, `TestChunkLSNMapV3_PreflightErrorDoesNotLatch`, `TestWALStoreV3_AutomaticMapPersistenceFailureLatchesStore` | — | STUB |
| `INV-WAL-V3-MAP-EXTENT-REUSE-001` | A v3 sidecar extent is reused only when no live root references it: neither slot's root, no in-flight candidate, and, until reopen, no candidate whose publication outcome is uncertain. | M1 (map preparation) | `core/storage/chunk_map_extents_v3.go` `slotsPublishedV3`, `abandonCandidateV3`, `liveSnapshotV3`, `registerRootV3`; `core/storage/chunk_map_publication_v3.go` `publishMapV3`, `openDescriptorMapV3` | `TestChunkMapExtentsV3FallbackRootIsNeverReused`, `TestChunkMapExtentsV3NewerInFlightCandidateIsNotReused`, `TestChunkMapExtentsV3CrashBeforePublicationOfAReusedExtent`, `TestChunkMapExtentsV3UncertainCandidateStaysPinned`, `TestChunkMapExtentsV3DurableButRefusedPublicationStaysPinned`, `TestChunkMapExtentsV3ReopenRegistersTheFallbackRoot` (`core/storage/chunk_map_extents_v3_test.go`); `TestMapPublicationV3_UncertainFinalResponsePinsCandidate`, `TestWALStoreV3_UncertainMapCheckpointPinsDependencies` | — | STUB |
| `INV-WAL-V3-MAP-TRUNCATE-001` | When the v3 sidecar exceeds four times its live bytes, its free tail is truncated to the end of the highest live page and no lower. | M1 (map preparation) | `core/storage/chunk_lsn_map_v3.go` `prepareLockedV3` | `TestChunkMapV3FileStaysBoundedUnderSteadyCheckpoints` (`core/storage/chunkmap_bounded_v3_test.go`); `TestChunkMapExtentsV3TruncationKeepsAFallbackAtTheTail`, `TestChunkMapExtentsV3TruncationFaultKeepsTheSlotRoots`, `TestChunkMapExtentsV3RejectedPublicationsStayBounded`, `TestChunkMapExtentsV3ProofStalePreparesStayBounded`, `TestChunkMapExtentsV3StatsAfterReopen` (`core/storage/chunk_map_extents_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-001` | Every v3 descriptor slot write after create's initial slot A goes through the one publisher, which writes the fallback slot with slotGen + 1 while holding `descMu`. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish`, `descriptorPublisherV3.publishLockedCoreV3`; create: `core/storage/walstore_v3.go` `createWALStoreV3Configured` | `TestDescriptorV3PublishAlternatesSlotsAndReopenSelectsNewest`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-LOCKORDER-001` | The v3 publisher holds `WALStore.mu` only to take its snapshot and releases it before any slot I/O; the slot write and its fsync run in the store's fsync leaf. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishWithMapV3`; `core/storage/walstore.go` `WALStore.syncFile` | `TestDescriptorV3LockOrderRecorder` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-MERGE-001` | A v3 publication rebases onto the authoritative descriptor: W and CheckpointLSN are max-merged, and a change of identity, geometry or (outside a reset) nonce, a retainedTail regression, or a map root change without a higher map generation is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `mergeDescriptorV3`, `mergeDescriptorV3Mode` | `TestDescriptorV3MergeIsMonotonicAndRefusesForbiddenChanges`, `TestDescriptorV3ConcurrentPublishersNeverRegress` (`core/storage/descriptor_v3_test.go`); `TestResetV3OrdinaryPublicationsCannotChangeTheNonce` (`core/storage/reset_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-BASE-EDGE-001` | A v3 publication whose BASE state change is not a DESIGN 8.5 edge (none → installing, installing → installing under a new ID, installing → installed under the same ID and BaseLSN, installed → none) is refused; installed → installing is refused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `baseTransitionAllowedV3` | `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-FAIL-001` | A failed slot write (full or partial) or slot fsync publishes nothing: the authoritative descriptor stays, the store fault is latched, the candidate stays pinned as uncertain, and every later publication, rollover and WAL reuse is refused until reopen. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`, `descriptorPublisherV3.rolloverIfPinned`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3FsyncFailureIsStickyAndPublishesNothing`, `TestDescriptorV3SlotWriteErrorLatchesAndPinsTheCandidate`, `TestDescriptorV3RolloverFsyncFailureKeepsTheFloorPinned` (`core/storage/descriptor_v3_test.go`); `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate` | — | STUB |
| `INV-WAL-V3-PUBLISH-LATCH-LEAF-001` | A descriptor slot write error latches the store fault inside the fsync leaf, before `fileSyncMu` is released, so a store Sync queued on `fileSyncMu` cannot acknowledge through the uncertain slot. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/storage/walstore.go` `WALStore.syncFile`, `noteFsyncFailure` | `TestDescriptorV3QueuedStoreSyncCannotAckAfterSlotWriteError` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-SUCCESS-BOUNDARY-001` | A store fault latched while a v3 publication is in flight makes that publication fail at its success boundary, without advancing the authoritative descriptor. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3` | `TestDescriptorV3FaultLatchedDuringPublicationRefusesAtSuccessBoundary` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-COUNTER-001` | A v3 publication whose slotGen, W, CheckpointLSN, retainedTail, retainedHead, map generation, map coverage, BaseLSN or BaseCursor would exceed 2^64-2 is refused with `ErrCounterExhausted` before any write. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `checkCountersV3`; `core/storage/superblock_v3.go` `nextSlotGenV3` | `TestDescriptorV3PublicationCounterExhaustion` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-ROLLOVER-001` | When the fallback slot's retainedTail is below the selected slot's under the same nonce, a metadata-only rollover republishes the current descriptor unchanged into it, so the reuse floor rises to the selected tail. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.rolloverIfPinned` | `TestDescriptorV3FullRingRolloverAdvancesTheFloorWithoutAnyChange` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001` | No v3 WAL reuse floor is computed across nonces: while the two descriptor slots carry different nonces there is no floor, and no WAL byte is reused. | M1 Serving (v3 descriptor publication) | `core/storage/descriptor_v3.go` `descriptorPublisherV3.reuseFloor`, `descriptorPublisherV3.reuseFloorLocked` | `TestDescriptorV3MixedNoncesNeverYieldAReuseFloor` (`core/storage/descriptor_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-001` | A v3 Sync acknowledges a write only after an fsync that covers the write's WAL record has completed. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.Sync` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-W-MODE-C-001` | In mode C (the default) a Sync batch publishes W = the previous batch's acknowledged W, and that publication's one fsync covers both the batch's WAL records and the slot. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-W-MODE-A-001` | In mode A a Sync batch fsyncs the WAL first and only then publishes the slot with W = H, the highest LSN appended when the batch began. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3RecoversEveryAcknowledgedWriteInBothModes`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-W-RECOVERY-001` | Recovery of a non-installing v3 descriptor fails with `wal_corrupt` when the contiguous LSN prefix R above max(CheckpointLSN, BaseLSN) is below W* = max(slot W, highest DurableLSN of a trusted record). | M1 Recovering → Serving \| RecoveryFailed | `core/storage/recovery_v3.go` `decideRecoveryV3`, `contiguousPrefixV3`, `replayFloorV3`; `core/storage/walstore_v3.go` `WALStore.recoverV3` | `TestRecoveryV3Decision`, `TestRecoveryV3ContiguousPrefix` (`core/storage/recovery_v3_test.go`); `TestWALStoreV3TornUnsyncedTailIsNeverAFalseCorrupt` (`core/storage/walstore_v3_test.go`) | `WALFormat` composed model | STUB |
| `INV-WAL-V3-W-REFRESH-001` | When the slot W lags the acknowledged W, the flusher's idle refresh and `SetWMode` each publish W = the acknowledged W. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.refreshW`, `WALStore.SetWMode` | `TestWALStoreV3RefreshAndSetWModeCloseTheWindow`, `TestWALStoreV3FlusherCycleRunsTheIdleRefresh`, `TestWALStoreV3FlusherEmptyCycleRunsTheIdleRefresh` (`core/storage/walstore_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-CHECKPOINT-CLAMP-001` | A v3 checkpoint never exceeds the acknowledged W; entries the flusher wrote to the extent above the published checkpoint stay retry work, so a later Sync and flusher cycle advance the checkpoint and map coverage together. | M1 write lifecycle: InExtent → Checkpointed (v3) | `core/storage/walstore_v3.go` `WALStore.persistCheckpointV3`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.persistOwnedMapCheckpointV3`; `core/storage/flusher.go` `flushOnceInternal` | `TestWALStoreV3FlusherCheckpointIsClampedToTheAcknowledgedW`, `TestWALStoreV3FlusherWritesTheExtentButHoldsTheCheckpointUntilTheMap` (`core/storage/walstore_v3_test.go`); `TestWALStoreV3_FlushedProgressRetriesAfterLaterSync` (`core/storage/walstore_flushed_progress_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-SETWMODE-001` | `SetWMode` first syncs every write admitted before it under the old mode, then publishes the new mode while holding the v3 leader role, so no Sync batch acknowledges under a mode other than the descriptor's. | M1 write lifecycle: Appended → Synced (v3) | `core/storage/walstore_v3.go` `WALStore.SetWMode`, `WALStore.syncWALBatchV3Internal` | `TestWALStoreV3SetWModeWaitsForAHeldBatch`, `TestWALStoreV3NoBatchAcksUnderAStaleModeAfterSetWMode`, `TestWALStoreV3SetWModeCrashCases` (`core/storage/walstore_v3_test.go`) | — | STUB |
| `INV-WAL-V3-W-RECOVER-STRADDLE-001` | No v3 W publication or Sync acknowledgement straddles a recovery: a Sync whose completion sees a changed recovery generation is refused, and recovery sets the acknowledged W to its recovered prefix R. | M1 Recovering → Serving | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.refreshW`, `WALStore.syncWALBatchV3Internal`; `core/storage/walstore.go` `WALStore.syncWithPhases` | `TestWALStoreV3SameOpenRecoverResetsTheAcknowledgedFrontier`, `TestWALStoreV3RecoverWaitsForABatchAckAndNothingRevivesTheCut`, `TestWALStoreV3OuterSyncCompletionIsRefusedAcrossARecovery`, `TestWALStoreV3RefreshDuringRecoverWaitsAndPublishesNothing` (`core/storage/walstore_v3_test.go`) | — | STUB |
| `INV-WAL-V3-FENCE-001` | Before any append after a v3 recovery, the store zeroes the logical WAL interval [E, floor + WALSize), floor being the both-slot same-nonce reuse floor, fsyncs it through the leaf, and only then publishes retainedHead = E. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/recovery_v3.go` `fenceRangesV3` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB |
| `INV-WAL-V3-FENCE-EXACT-001` | The v3 drop fence changes only the bytes of [E, floor + WALSize) mapped modulo WALSize, in at most two ranges split at the physical wrap; no byte before E or outside the interval changes. | M1 Recovering → Serving (v3) | `core/storage/recovery_v3.go` `fenceRangesV3`; `core/storage/walstore_v3.go` `WALStore.fenceV3` | `TestWALStoreV3FenceTouchesNoByteBeforeTheHead`, `TestWALStoreV3RecoversAHistoryEndingAtTheLastRepresentableCursor` (`core/storage/walstore_v3_test.go`); `TestRecoveryV3FenceRangesAreExact` (`core/storage/recovery_v3_test.go`) | — | STUB |
| `INV-WAL-V3-NO-RESURRECTION-001` | A WAL record dropped by one v3 recovery is never replayed by a later recovery, also after a second crash. | M1 Recovering → Serving (v3) | `core/storage/walstore_v3.go` `WALStore.recoverV3`, `WALStore.fenceV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestWALStoreV3DroppedRecordsNeverResurfaceAfterASecondCrash`, `TestWALStoreV3NoFenceResurrectsInBothModes` (`core/storage/walstore_v3_test.go`) | `WALFormat` `NoResurrection` | STUB |
| `INV-WAL-V3-RESET-001` | A v3 nonce/position reset is refused with `ErrResetNotPreserved`, writing nothing, unless the dirty map is empty and CheckpointLSN is at least every appended LSN (and so equals the acknowledged W). | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `WALStore.resetIncarnationV3`, `descriptorPublisherV3.resetIncarnationV3` | `TestResetV3RefusesWhileUncheckpointed`, `TestResetV3RetainedButCheckpointedBytesDoNotBlock` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetRefusesUncheckpointedOrUnacknowledgedData` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-TWO-SLOT-001` | A reset publishes a new nonzero nonce with an empty cursor space into one descriptor slot and then the other, and succeeds only after both publications. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`; `core/storage/descriptor_v3.go` `mergeDescriptorV3Mode` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor`, `TestResetV3RefusesTheCurrentOrAZeroNonce` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-HALF-001` | After a crash between a reset's two publications, open selects the new incarnation and binds no WAL writer, so every append is refused until Recover's head publication puts the new nonce in both slots. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/walstore_v3.go` `openWALStoreV3File`, `WALStore.recoverV3`, `WALStore.appendWriteV3`; `core/storage/reset_v3.go` `descriptorPublisherV3.halfResetV3` | `TestResetV3CrashOutcomes` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetCrashOutcomes`, `TestWALStoreV3HalfResetRefusesWritesUntilRecover` (`core/storage/reset_store_v3_test.go`) | `WALFormat` reset (r4.5, pending) | STUB |
| `INV-WAL-V3-RESET-INVARIANT-001` | A reset leaves LSN allocation, W, CheckpointLSN and the map root unchanged. | M1 Serving → Serving (reset: no production caller; tests only) | `core/storage/reset_v3.go` `descriptorPublisherV3.resetIncarnationV3`, `WALStore.resetIncarnationV3` | `TestResetV3PublishesBothSlotsAndOnlyThenHasAFloor` (`core/storage/reset_v3_test.go`); `TestWALStoreV3ResetPublishesBothSlotsAndWritesRecoverAcrossACrash` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-READ-REVALIDATE-001` | A v3 read served from a dirty entry returns data only from a WAL record that validates whole (CRC, footer, type) and whose LBA and LSN match the resolving entry; on a mismatch it resolves again, so a reused WAL position never serves another block. | M1 Serving → Serving (reads; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into`, `WALStore.readRecordIntoV3` | `TestWALStoreV3ReadParkedAcrossAResetAndOverwriteReturnsItsOwnBlock`, `TestWALStoreV3ReadMissRecheckParkedAcrossAResetReturnsItsOwnBlock` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-READ-DAMAGE-001` | A v3 dirty read reports WAL damage only for a record that fails validation while the resolving entry and the recovery generation are the same before and after the attempt; a failed pread is reported as substrate I/O. | M1 Serving → Serving (reads; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.readDirtyV3Into` | `TestWALStoreV3ReadOfADamagedLiveRecordIsAnIntegrityFault`, `TestWALStoreV3ReadAcrossARecoveryThatReusesTheSamePositionAndLSNIsNotDamage`, `TestWALStoreV3ReadIOErrorsAreSubstrateIONotWALIntegrity`, `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`) | — | STUB |
| `INV-WAL-V3-RECOVER-GEN-001` | The v3 recovery generation is incremented at the start and at the end of every recovery and every reset. | M1 Serving → Serving (recovery; the reset has no production caller) | `core/storage/walstore_v3.go` `WALStore.recoverV3`; `core/storage/reset_v3.go` `WALStore.resetIncarnationV3` | `TestWALStoreV3ReadAdmittedBetweenRecoverBumpAndClearIsNotDamage` (`core/storage/reset_store_v3_test.go`); `TestWALStoreV3_FlushMaterializationBoundToRecoveryLifetime` (`core/storage/walstore_map_recovery_lifetime_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-001` | A v3 BASE install begins only if BaseLSN is at least the acknowledged W (published or not yet), the CheckpointLSN and every appended LSN; otherwise the begin writes nothing and returns `ErrInstallBaseUncovered`, or `ErrInstallSupersedeUncovered` when it supersedes. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3` | `TestBaseInstallV3BeginRefusesBelowW`, `TestBaseInstallV3BeginCoversTheAcknowledgedNotYetPublishedW`, `TestBaseInstallV3BeginRefusesBelowTheHighestAppendedLSN` (`core/storage/base_install_v3_test.go`); `TestBaseInstallV3CoveringSupersessionOverADamagedSuffix` (`core/storage/base_install_reopen_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-BEGIN-SLOTS-001` | Before the first BASE mutation of an install, both descriptor slots durably hold installing with its BaseLSN, BaseCursor = the writer head P at begin, and the new install ID. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publish` | `TestBaseInstallV3BeginPublishesInstallingIntoBothSlots` (`core/storage/base_install_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-DRAIN-001` | A BASE write or install-lane apply admitted through an install handle finishes before a later begin proceeds, and after that begin every handle of the earlier install epoch is refused with `ErrInstallSuperseded`. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.beginBaseInstallV3`, `installHandleV3.admitV3`, `installHandleV3.admissibleV3` | `TestBaseInstallV3HeldOldWriteDrainsBeforeANewBegin`, `TestBaseInstallV3ParkedOldFrameIsRefusedAfterASupersession` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3HeldOldBaseWriteDrainsBeforeANewSession`, `TestReceiverV3ParkedOldFrameIsRefusedAfterANewSession` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-HANDLE-001` | On a v3 store, BASE extent writes and install-lane applies go only through an install handle: `WriteExtentDirect` is refused, an ordinary replicated apply is refused while installing, and `WriteBase` needs installing under the handle's ID. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `installHandleV3.WriteBase`, `installHandleV3.admissibleV3`, `WALStore.applyEntryV3`; `core/storage/walstore.go` `WALStore.WriteExtentDirect` | `TestNativeReplacementDirectExtentRefusedPreservesWAL` (`core/storage/legacy_replacement_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3InstallThroughTheHandle` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-LANE-AFTER-DONE-001` | An install-lane apply through a handle is admitted while the volume is installing under its ID or, once that handle's own complete succeeded, while installed under its ID or retired, until the next begin; otherwise it returns `ErrInstallSuperseded`. | M1 Serving → Installing → Serving (install lane only with `--recovery-mode=dual-lane`) | `core/storage/base_install_v3.go` `installHandleV3.admissibleV3`, `installHandleV3.ApplyInstallEntry`, `installHandleV3.MarkBaseComplete` | `TestBaseInstallV3CompletedHandleAppliesUntilTheNextBegin` (`core/storage/base_install_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3WALAfterBaseDoneStillApplies`, `TestReceiverV3WALAfterBaseDoneSurvivesACrash` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-LANE-ORDER-001` | A v3 install-lane apply at or below the highest appended LSN is a no-op if its LBA already holds a higher LSN and fails with `ErrWALLSNOrder` otherwise; one above max(CheckpointLSN, BaseLSN, highest appended) + 1 fails with `ErrInstallLSNGap`. | M1 Serving → Installing → Serving (install lane only with `--recovery-mode=dual-lane`) | `core/storage/base_install_v3.go` `WALStore.applyEntryV3` | `TestBaseInstallV3ApplyInstallEntryOrderAndGap` (`core/storage/base_install_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-COMPLETE-001` | Installed is published only by a complete for the current installing ID, and only after one fsync of the store file covering the BASE extent bytes and the install-lane suffix, followed by the metadata and chunk checkpoint barriers. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestChunkLayerV3_BASEPresenceBarrierFailureKeepsInstalling` (`core/storage/chunk_base_v3_test.go`); tagged `swblock_format_v3_test`: `TestReceiverV3SupersededBaseDoneFailsWithoutAnAck` (`core/recovery/receiver_install_format_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-COMPLETE-MAP-001` | The installed publication sets retainedTail to at least BaseCursor and carries a fresh owned-map candidate in which every chunk a BASE write of the install touched is UNKNOWN. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`, `installHandleV3.WriteBase`, `WALStore.markMapUnknownV3` | `TestBaseInstallV3CompletePersistsTheMapUnknownOfBaseWrites`, `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-SUPERSEDED-001` | After a successful complete, the open store neither serves nor flushes a WAL record appended before the begin, and recovery from an installed descriptor scans no record behind BaseCursor. | M1 Serving → Installing → Serving | `core/storage/base_install_v3.go` `WALStore.markBaseCompleteV3`; `core/storage/wal_io_v3.go` `scanWALV3Accepted` | `TestBaseInstallV3CompleteServesTheImageAcrossACrash` (`core/storage/base_install_v3_test.go`); `TestWALIOV3_InstalledScanBeginsAtMaxTail` (`core/storage/wal_io_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BASE-RETIRE-001` | A v3 descriptor goes from installed to none only when CheckpointLSN ≥ BaseLSN and both the newly written slot and the slot it leaves as fallback carry retainedTail ≥ BaseCursor; installing never goes to none. | M1 Serving → Installing → Serving | `core/storage/descriptor_v3.go` `retireBaseV3`, `baseTransitionAllowedV3` | `TestBaseInstallV3RetiresOnlyOnceTheCheckpointCoversBaseLSN`, `TestBaseInstallV3InstallingToNoneIsRefused` (`core/storage/base_install_v3_test.go`); `TestDescriptorV3BaseTransitionTable` (`core/storage/descriptor_v3_test.go`) | `WALFormat` handle and BASE configs (pending) | STUB |
| `INV-WAL-V3-BASE-RETIRE-GATE-001` | On a store whose provider deferred BASE retirement at open, retirement of an installed BASE waits for this open's attach commit. | M1 Serving → Installing → Serving (deferral only with `--durable-impl=walstore-chunk`) | `core/storage/base_install_v3.go` `WALStore.DeferBaseRetirementV3`, `WALStore.CommitChunkAttachV3`, `WALStore.AllowBaseRetirementV3`; `core/storage/chunk_base_v3.go` `chunkLayerImpl.holdBaseTransitionV3`; `core/storage/descriptor_v3.go` `descriptorPublisherV3.publishLockedCoreV3`; `core/frontend/durable/provider.go` `openOrCreate` | `TestBaseInstallV3CommitChunkAttach`, `TestBaseInstallV3RetirementWaitsForTheGate` (`core/storage/base_install_v3_test.go`); `TestDurableProviderV3_DefersBASERetirementUntilLocalPresence` (`core/frontend/durable/provider_format_v3_base_test.go`) | — | 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; this is checked again at its completion. | M1 Installing | `core/storage/walstore.go` `WALStore.Sync`, `WALStore.syncWithPhases` | `TestInstallLogV3SyncIsGatedWhileInstalling` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-INSTALL-LOG-ACK-001` | `SyncInstallLog(id)` returns H, the highest LSN appended when it starts, only after a WAL fsync and then a descriptor publication of W = max(W, H) with BaseState still installing: always mode A. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3IsModeAAndSurvivesACrash` (`core/storage/install_log_v3_test.go`) | `WALFormat` install-log ack | STUB |
| `INV-WAL-V3-INSTALL-LOG-REFUSE-001` | Under `installMu` shared, `SyncInstallLog` is refused with `ErrNotInstalling` outside an install and with `ErrInstallIDMismatch` for another install ID. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog`, `installLogTargetV3` | `TestInstallLogV3Refusals` (`core/storage/install_log_v3_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-FAULT-001` | `SyncInstallLog` acknowledges nothing when a store fault has latched by its final check under `WALStore.mu`. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `WALStore.SyncInstallLog` | `TestInstallLogV3AFaultLatchedBeforeTheAckRefusesIt` (`core/storage/install_log_v3_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-SCOPE-001` | `SyncInstallLog` is on the narrow `InstallLogSyncer`, not on `LogicalStorage`, and no package other than `core/storage` and `core/recovery` names `InstallLogSyncer`. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/storage/install_log_v3.go` `InstallLogSyncer` | `TestInstallLogSyncerIsReceiverOnly` (`core/recovery/install_log_boundary_test.go`) | — | STUB |
| `INV-WAL-V3-INSTALL-LOG-RECEIVER-001` | The rebuild receiver's durable progress ack is `SyncInstallLog(installID)` until its own session's completion, and the ordinary `Sync` after it. | M1 Installing (only with `--recovery-mode=dual-lane`) | `core/recovery/receiver.go` `Receiver.sendAck` | tagged `swblock_format_v3_test`: `TestReceiverV3ProgressAckIsTheInstallLog` (`core/recovery/receiver_install_format_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-001` | A v3 `WriteBatch` of n > 1 blocks is one record (type 0x04) with LSNs first..first+n-1 under one CRC32C, so a crash keeps all n blocks or none. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore.go` `WALStore.WriteBatch` | `TestWALStoreV3BatchRoundTripAcrossACrash`, `TestWALStoreV3TornBatchIsAllOrNothing`, `TestWALStoreV3CrashMidBatchServesNoneOfIt` (`core/storage/walstore_batch_v3_test.go`) | `WALFormat` batch records | STUB |
| `INV-WAL-V3-BATCH-READERS-001` | Each v3 batch block's dirty entry names its data offset in the record, and every reader (store read, flusher, recovery replay, install-path replays, offline reader) uses the block only from a whole valid record whose block has that LBA, LSN and offset. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.readRecordIntoV3`, `readWholeRecordV3`, `blockOfRecordV3`, `flusher.readDirtyRecordV3`, `WALStore.replayRecordV3`; `core/storage/walstore_readonly_v3.go` `WALStoreReader.readV3` | `TestWALStoreV3BatchFlushesEveryBlock`, `TestWALStoreV3ReadOnlyReaderServesBatchBlocks`, `TestWALStoreV3BatchRoundTripAcrossACrash` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-ACK-001` | A Sync that covers a v3 batch returns a frontier of at least the batch's last LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`, `WALStore.advanceAfterAppendV3` | `TestWALStoreV3BatchAckCoversItsLastLSN` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-BATCH-MAP-001` | The owned map records every block of a v3 batch at its own LSN. | M1 Serving | `core/storage/walstore_v3.go` `WALStore.writeBatchV3Locked`; `core/storage/walstore_map_checkpoint_v3.go` `WALStore.recordMapWriteV3` | `TestWALStoreV3BatchRecordsMapCoverage` (`core/storage/walstore_batch_v3_test.go`) | — | STUB |
| `INV-WAL-V3-MIGRATE-001` | ARCHIVED: the in-place v2 converter is removed. Public opens refuse v2 bytes without mutation; no upgrade path is provided. | M1 open refusal | `core/storage/walstore_v3.go` `openWALStoreV3WithOptions` | `TestNativeReplacementLegacyBytesRefusedWithoutMutation` (`core/storage/legacy_replacement_v3_test.go`) | none (retired tool) | ARCHIVED |
| `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` | `TestSessionWriteBudgetDeadlineIsRetryableIncludingFUA` (expiry and joined physical-fault wire status); `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 |
@@ -464,18 +540,35 @@ 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. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the 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-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. Production create and open run this bind (`openWALStoreV3File`); capture does not. 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 map-requiring actual-store opener (production open) 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. The entry snapshot may already contain LSNs above cp or W from pre-snapshot appends; max-LSN entries remain monotone and idempotent under replay. Strictly newer ordered WAL appends update per-chunk max LSN without invalidating an older checkpoint-prefix proof: their retained suffix is replayed before recovery serves. BASE writes, capture UNKNOWN clearing and lifecycle boundaries still invalidate proofs. A reused ordered LSN below a speculative retained map maximum can set UNKNOWN without invalidating the prefix; the high max and replayed retained suffix remain conservative. Recover rebuilds the volatile cache from the selected root and retained WAL prefix. Metadata/chunk callbacks precede map and descriptor durability. The actual chunk capture (production with `--durable-impl=walstore-chunk`) 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 chunk transition drain (no production caller: a BASE install comes only from replication, which `walstore-chunk` refuses) 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 now creates and opens mapped v3 too (`INV-WAL-V3-ACTIVATION-001`), 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 create and open select mapped v3 (`INV-WAL-V3-ACTIVATION-001`); the BASE caller and readonly/status controls have dedicated rows below. WAL tail reclamation is wired (`INV-WAL-V3-RECLAIM-001` family). Existing 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 immutabLine truncated
- `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. Sidecar extents are reused only after neither slot nor a pending or uncertain candidate references them; see `chunk_map_extents_v3.go` and its tests.
- `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, 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 the 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; 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-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. 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). Production reaches it through both callers below: the legacy single-lane caller by default, the dual-lane `Receiver` with `--recovery-mode=dual-lane`. 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`). A v3 begin with an attached chunk layer that has no BASE transition hook is refused (`errV3NotYet`), writing nothing (`TestBaseInstallV3BeginRefusesWithAnUnsupportedAttachedChunkLayer`; a supported layer is drained as in `INV-WAL-V3-CHUNK-BASE-001`); 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; the provider's former refusal of a HEAD restore onto a v3 store is gone since row 12a (see the `INV-WAL-V3-MAP-PUBLISH-001` note); 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; 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`: Archived with the converter and its legacy fixtures; v2 inputs refuse open without mutation.
- `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, 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`).
- `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. Since activation (row 12b) production create and open (`CreateWALStoreWithOptions`, `OpenWALStoreWithOptions`) reach it. Without the row-7 map candidate (unmapped test fixtures only) the v3 checkpoint and tail do not advance. They are still STUBs although the path is active; their promotion is pending a per-row check of their tests. 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, 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). The v3 store is wired in (rows 4 and 5) and activated (row 12b); the row is still a STUB although the path is active, its promotion pending a per-row check of its tests. The v2 checkpoint path (`persistCheckpointReleasing`) is retired. 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). Since the activation commit (plan row 12b) production walstore open and create reach the v3 codec; the row is still a STUB although the path is active, its promotion pending a per-row check of its tests. 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`).
- `INV-WAL-V3-ACTIVATION-001` family: writable and read-only open validate the owned-map dependencies of the selected slot and of every valid fallback slot before the store or reader is returned, and refuse a valid legacy superblock with `ErrUnsupportedLegacyFormat` without changing a byte: see M1 — → Opened (tests `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_ReadOnlyRefusesIncompleteOrCorruptDependencies` with its fallback-page case, `TestNativeReplacementLegacyBytesRefusedWithoutMutation`). A zero chunk geometry option becomes 1024 blocks per chunk, so every public create is mapped; create persists an all-UNKNOWN initial map before its first slot.
- `INV-WAL-V3-DESCRIPTOR-CONFLICT-001`: the old statement said the two slots must not disagree on identity; of the identity fields, open compares the UUID, together with the geometry. The next publication's slotGen comes from `nextSlotGenV3` (`INV-WAL-V3-PUBLISH-COUNTER-001`). `TestWALStoreV3CloseKeepsTheNewestSlotAAndItsW` is a store-level control of the selection: a v3 `Close` writes no slot, and reopen selects the newest one.
- `INV-WAL-V3-RECORD-001`: codec success alone is not nonce, cursor or lap replay admission; that belongs to the scanner (`INV-WAL-V3-SCAN-BINDING-001`).
- `INV-WAL-V3-ADMISSION-001` family: at every store call the store derives its own admission deadline from the command deadline, min(command deadline, now + `admissionTimeout`) less a reserve of min(1 s, a quarter of the time left), so the append and its completion keep headroom; the 4 s local admission timeout restarts for each adapter batch, while the command deadline does not. The budget is cooperative: it never interrupts a mutex wait or a WAL write already started, and issued WAL I/O keeps its existing lifecycle ownership. Keeping a committed prefix's storage error in the classified set means a later observer deadline cannot turn a physical fault into a retryable one; on NVMe a retryable deadline is Namespace Not Ready, DNR=0. The WAL-pressure wait and its locks are in Part D. The burst tests are liveness controls: they would stall if a waiter held a lock the flusher needs, but they do not assert the lock state.
- `INV-WAL-V3-RECLAIM-001` family: reuse still needs both valid same-nonce slot tails: see M1 Serving → Serving (checkpoint) and `INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`. A catch-up scan revalidates the tail and checkpoint before it delivers its buffered entries (`INV-WAL-V3-CATCHUP-REVALIDATE-001`). Writer exclusion until the rollover and the dirty retirement end means no write reuses a released position while a dirty entry still names it. The flusher also caps the checkpoint at the lowest active catch-up pin (`persistOwnedMapCheckpointV3`). An installing reopen indexes record boundaries without restoring or rewinding the writer's cursor or LSN (`rememberReclaimScanV3`).
- `INV-WAL-V3-CATCHUP-001` family: the revalidation closes begin/complete/retire ABA, so a superseded prefix is never published; a source that began installing during the scan refuses with `ErrBaseInstalling`, and any other change makes it scan again. A request at or below CheckpointLSN minus the retention window also fails with `WALRecycled`. A scan holds no store lock across its callbacks and emits all of its entries or none.
- `INV-WAL-V3-BINDING-001` family: a writer whose pwrite failed refuses every later append, and the store latches the fault: see M1 Serving → FaultLatched and FaultLatched → FaultLatched (test `TestWALIOV3_FloorAndPwriteFailureRefuse`). A scan result (`walScanResultV3`) is a typed read-only result, never an acknowledgement or serving permission; recovery decides from it (`INV-WAL-V3-W-RECOVERY-001`). The scan start for a BASE descriptor is in `INV-WAL-V3-BASE-SUPERSEDED-001`.
- `INV-WAL-V3-MAP-PUBLISH-001` family: binding validates the map root and pages of the selected slot and of every valid fallback slot before serving: see M1 — → Opened (tests `TestMapPublicationV3_BindValidatesBothSlotDependencies`, `TestWALStoreV3_OpenRequiresBothMapGenerations`, `TestWALStoreV3_MappedCreateOpenOwnsMap`, `TestDurableProviderV3_MissingMapRefusesBeforeBackend`). Recover invalidates the map proof epoch at its start and at its end, on success and on failure: see M1 Recovering → Serving (tests `TestWALStoreV3_RealRecoverInvalidatesMapProofAtStartAndEnd`, `TestWALStoreV3_FailedRecoverInvalidatesMapProofAtBothBoundaries`, `TestWALStoreV3_AutomaticMapRecoverRebuildsCoverage`). A candidate whose slot publication outcome is unknown stays pinned until reopen (`INV-WAL-V3-MAP-EXTENT-REUSE-001`, `INV-WAL-V3-PUBLISH-FAIL-001`). Controls of the capture, seed and provider callers described in the next note, not of the publication rule itself: `TestDurableProviderV3_InvalidHEADFrontierRefusesBeforeClaim`, `TestDurableProviderV3_HEADRestoreAfterLostClaimResponse`, `TestDurableProviderV3_MappedCheckpointCaptureAndReopen`, `TestDurableProviderV3_DefaultSelectorCreatesV3`, `TestChunkLayerV3_MapOnlyCaptureNeedsNoLegacyBitmap`, `TestChunkLayerV3_IgnoresProvidedLegacyBitmap`, `TestChunkLayerV3_MapOnlyFreshZeroHEADPreservesLocalWrites`, `TestChunkLayerV3_MapOnlyRefusesLegacyBASEHeaderMutation`, `TestChunkLayerV3_MapStatusConcurrentClose`, `TestChunkLayerV3_CaptureUsesOwnedMapAfterCheckpoint`, `TestChunkLayerV3_MaxLSNSelectsAfterReopenWithCleanLegacyBitmap`, `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN`, `TestChunkLayerV3_UnsettledCaptureNeverClearsUNKNOWN`, `TestChunkLayerV3_RefusesMapGeometryBeforeRemote`, `TestChunkLayerV3_CheckpointProgressUnderContinuousAppends`, `TestChunkLayerV3_CheckpointProgressAtWALPressure`, `TestCheckpointV3_NewerBatchReplaysAfterPreparedPrefix`, `TestCheckpointV3_LazyFillDoesNotInvalidatePreparedPrefix`, `TestCheckpointV3_NoFlushPressureWithRealPin`, `TestCheckpointV3_SpeculativeMaximumAfterDroppedSuffix`, `TestCheckpointV3_HeldHydrationWithLocalWriteAndFlush`; `TestDurableProviderV3_HEADRestorePreservesRemoteImageAndNextLSN` is also a control of `INV-WAL-V3-ACTIVATION-PROVIDER-001`.
- `INV-WAL-V3-MAP-BYTES-001` family: root and pages are addressed by offset and SHA-256; with 4096-byte alignment, distinct page offsets that do not overlap the root rule out a partial overlap. Truncation keeps a root the fallback slot names readable.
- `INV-WAL-V3-PUBLISH-001` family: create writes the initial descriptor into slot A directly (`createWALStoreV3Configured`) before the store opens; every later slot write is the publisher's. The lock graph is metadata callbacks, then `WALStore.mu` (snapshot only), then `descMu`, then `fileSyncMu` (the leaf, inside `syncFile`). An fsync error is latched by the leaf itself (`noteFsyncFailure`); the publisher latches a slot write error because the leaf does not. The success-boundary refusal is the #172 rule. `TestCheckpointV3_AppendRolloverFaultRefusesHeldCandidate` drives the failure rule through an append's rollover.
- `INV-WAL-V3-W-001` family: because mode C's slot carries the previous batch's W, the acknowledged writes above the slot W are at most those of the newest acknowledged batch, which is unprotected only against media corruption before the next Sync or the idle refresh (`INV-WAL-V3-W-REFRESH-001`; test `TestWALStoreV3ModeCWindowIsExactlyTheNewestBatch`). For an installing descriptor, recovery reports a short prefix (R < W*) or a scan error as `ErrBaseIncomplete`, not `wal_corrupt` (`installingErrorV3`; test `TestWALStoreV3InstallingScanErrorIsTypedNotReady` covers the scan error). A Sync acknowledges nothing when a store fault has latched by its final check (`INV-WAL-FSYNC-STICKY-001`).
- `INV-WAL-V3-FENCE-001`: with mixed slot nonces (a reset stopped between its two publications) the fence interval is empty, because old-nonce bytes fail the scanner's nonce binding (`fenceRangesV3`). A fence write error latches the store inside the leaf.
- `INV-WAL-V3-RESET-001` family: an empty dirty map means no entry names an old-incarnation WAL position. Between the two reset publications the slots carry different nonces, so there is no reuse floor (`INV-WAL-V3-PUBLISH-NONCE-FLOOR-001`); only a reset changes the nonce (`INV-WAL-V3-PUBLISH-MERGE-001`). A dirty read holds no lock across its WAL read, so the position it resolved may be reused (after a reset the cursor space restarts at 0); LSN allocation runs on across a reset, so a matching LBA and LSN identify the resolved write and no nonce is checked. A reset is also refused during a BASE install and while a previous reset is half published. A BASE resume and a covering supersession bump the recovery generation the same way.
- `INV-WAL-V3-BASE-001` family: begin, complete and the attach commit take `installMu` exclusive; handle mutations take it shared. Begin covers every appended LSN because an unacknowledged record above BaseLSN would leave a hole behind BaseCursor. Begin also refuses a zero install ID, the installing ID itself (`TestBaseInstallV3BeginRefusals`) and a begin while installed (retire first). An install-lane apply stays admitted after the handle's own completion because the session's WAL lane can outlive its BaseDone (DESIGN r17.4). The retirement deferral is meant to keep the installed descriptor as the provider's completed-image evidence while a reopen could still read the volume as fresh from HEAD. It is lifted by the attach commit when the volume is already installed (`CommitChunkAttachV3`), or after a BASE transition once local presence is durably saved and this open's attach is committed (`holdBaseTransitionV3`); a new begin defers it again. Open question: whether the attach commit's removal of the fresh marker and its directory fsync, before the deferral is lifted, is the full safety argument on the non-chunk-managed path where the commit lifts it; the presence-durable form is the stronger, chunk-managed path. Controls of the resume, supersession and same-open Recover rules in the next note: `TestBaseInstallV3SupersessionAfterReopenFencesTheOldSuffix` (`core/storage/base_install_reopen_v3_test.go`); `TestBaseInstallV3ResumeAfterReopenFencesAndServesTheSuffix`, `TestBaseInstallV3ResumeRefusesADamagedSuffix`, `TestBaseInstallV3EBelowThePersistedHead`, `TestBaseInstallV3SameOpenRecoverLeavesNoStaleResumeCut`, `TestBaseInstallV3SameOpenRecoverKeepsTheLiveInstallServed`, `TestBaseInstallV3SameOpenRecoverOverDamageFailsClosed` (`core/storage/base_install_resume_v3_test.go`).
- `INV-WAL-V3-INSTALL-ACK-001` family: DESIGN r17.4 section 7. `SyncInstallLog` attests install-log durability only, never a readable image, and never changes BaseState; its final fault check is the #172 acknowledgement boundary. The former clause that a v2 store's `SyncInstallLog` is its `Sync` is dropped: open refuses legacy formats, so every open store is v3.
- `INV-WAL-V3-BATCH-001` family: a single-block `WriteBatch` is an ordinary write record. The writer consumes the whole LSN range of a batch (`INV-WAL-V3-LSN-ORDER-001`). A torn acknowledged batch fails recovery closed (`INV-WAL-V3-W-RECOVERY-001`). A failed batch pwrite latches the store and is never acknowledged: see M1 Serving → FaultLatched (`INV-WAL-APPEND-STICKY-001`).
- Enforced by reading (no test asserts it), M1 rows: `INV-WAL-V3-ADMISSION-001` family, that a WAL-pressure or admission-slot wait wakes the flusher and holds no store, descriptor or WAL writer lock while it sleeps, and that no such wait grants WAL reuse or acknowledges a write (`walAdmission.acquireContext`, `writePressureSample`); `INV-WAL-V3-ACTIVATION-FALLBACK-001`, the read-only half (`openReadOnlyV3` runs the same `refuseLegacyWALStore` and `selectSlotV3`; the test opens writable); `INV-WAL-V3-BASE-HANDLE-001`, the refusal of an ordinary replicated apply while installing (`applyEntryV3`); `INV-WAL-V3-BASE-DRAIN-001`, that a complete also waits for every admitted handle mutation (`markBaseCompleteV3` takes `installMu` exclusive); `INV-WAL-V3-RESET-INVARIANT-001`, that LSN allocation is unchanged (the tests compare W, CheckpointLSN and the map root); `INV-WAL-V3-INSTALL-LOG-RECEIVER-001`, the switch to the ordinary `Sync` after the session's completion (`Receiver.sendAck`); and that a publication refused at its success boundary keeps its written candidate pinned as uncertain until reopen (`publishLockedCoreV3`).
### B.2 Core: authority and epochs
@@ -489,7 +582,7 @@ Notes:
| `INV-LEASE-VIEW-OWNED-001` | The granted deadline and the extender flag exist only in the lease view; refreshing the view from its derive inputs never changes either of them. | M2 every workspace transition | `core/authority/workspace_lease_view.go` `refreshLeaseViewLocked`, `setLeaseDeadlineLocked`, `extendWorkspaceLease` | — | — | STUB |
| `INV-WS-LEASE-HORIZON-001` | For the active lease of the current authority epoch, the `Lease.ExpiresAtNS` persisted in the authority store is at least the published horizon, and the published horizon is at least every grant issued since the last reload. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `firstWorkspaceGrant`, `newWorkspaceLease`, `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked`, `issueWorkspaceMove` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceRestartForcedBarrierHonoursHorizon`, `TestWorkspaceAmbiguousExtensionLatchesUncertainty`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceLeaseGuardFencesByHorizonUnderStalledStore` (`core/host/master/workspace_lease_horizon_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-HORIZON-MONO-001` | Within one lease the published horizon never decreases: an extension writes a new horizon only when it is greater than the current one. | M2 Granted → Granted | `core/authority/workspace_lease_view.go` `extendWorkspaceLease`; `core/authority/workspace.go` `persistWorkspaceLocked` | `TestWorkspaceExtenderHeldOrdersSameVolumeWriters`, `TestWorkspaceLeaseConcurrentRenewalsWritersExtendersClose` (`core/authority/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-WS-RENEW-NONBLOCKING-001` | Live renewals take only the leaf lease lock and lock-free lifecycle snapshots; they never wait on publisher/store locks. First grants and expired re-grants persist synchronously; an expired re-grant refuses immediately if the publisher lock is busy. | 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 |
| `INV-MASTER-JOURNAL-ISOLATION-001` | Under strict journal isolation, blockmaster gives no new work to a node whose durable root shares the authority store's file system: it refuses that node's heartbeat while it serves no volume, a new placement on it and a move onto it; work the node already has is kept. | M2 workspace move: Acked or Expired → (move refused, nothing written); workspace placement admission; node heartbeat | `core/host/master/journal_isolation.go` `refuseColocatedHeartbeat`, `colocatedTargetRefused`, `reconcilePlacements`, `nodeServesVolumes`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/host/master/workspace_binding.go` `PlaceWorkspace` | `TestColocatedNodeIsAlarmedButAcceptedByDefault`, `TestStrictRefusesColocatedNodeWithoutVolumes`, `TestStrictAcceptsColocatedNodeThatAlreadyServes`, `TestStrictRefusesPlacementAndMoveOntoColocatedNode`, `TestStrictProductLoopSkipsColocatedNodeForNewPlacement` (`core/host/master/journal_isolation_test.go`); `TestStrictReplaysAnIssuedMoveToANowColocatedTarget`, `TestStrictKeepsAnIdempotentPlacementOnANowColocatedNode` (`core/host/master/journal_isolation_fold_test.go`) | — | ACTIVE |
@@ -501,9 +594,9 @@ 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. A Revoking lease still gets its bounded drain reply, min(horizon, deadline), never extended: see M2 any (workspace) → Uncertain. A failed move on an uncertain volume is answered as an unknown outcome before any admission refusal, the request's own cancellation or deadline stays typed, and an issued move's replay still returns its stored grant: see M2 Uncertain → Uncertain (move answer). The renewal path reads uncertainty from the lease view (`INV-LEASE-VIEW-001`), not from `persistWorkspaceLocked`.
- `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-LEASE-HORIZON-001`, `INV-WS-LEASE-HORIZON-MONO-001`: a move issue that replaces the lease with the new holder's (a clean handoff, or a forced move past the barrier) is its ordered successor and ends the scope of these rows. If that issue write is persisted ambiguously (it may have landed while memory has not published it), the volume is uncertain and no further grant at the old epoch is issued (`INV-AUTH-UNCERTAIN-001`), so no disk expiry is claimed for it.
- `INV-LEASE-VIEW-001`, `INV-LEASE-VIEW-OWNED-001`: writers refresh the view under the publisher lock, then the lease lock, at every change of a derive input; the renewal path takes only the lease lock (`INV-WS-RENEW-NONBLOCKING-001`). A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised: see M2 Moved → epoch issued (test `TestWorkspaceIssuePublishNeverLowersARenewedDeadline`, `core/authority/workspace_issue_publish_test.go`).
- `INV-LEASE-VIEW-001`, `INV-LEASE-VIEW-OWNED-001`: writers refresh the view under the publisher lock, then the lease lock, at every change of a derive input; the live renewal path takes only the lease lock (`INV-WS-RENEW-NONBLOCKING-001`). A move issue publishes the derived view and the new holder's initial deadline in one lease-lock section, never lowering a deadline a renewal raised: see M2 Moved → epoch issued (test `TestWorkspaceIssuePublishNeverLowersARenewedDeadline`, `core/authority/workspace_issue_publish_test.go`).
- Enforced by reading (no test asserts it): `INV-AUTH-PERSIST-BEFORE-PUBLISH-001`, that no subscriber sees a failed write (`applyWithWorkspaceMove` writes the store before it changes memory and snapshots the subscribers); `INV-AUTH-UNCERTAIN-001`, the drain reply on an uncertain volume (`RenewWorkspaceLease` answers a Revoking lease before it checks uncertainty); `INV-LEASE-VIEW-OWNED-001` (`refreshLeaseViewLocked` assigns only the derived part); the one-section issue publish (`publishIssuedLeaseLocked`); `INV-WS-LEASE-HORIZON-MONO-001`, that an extension writes only a greater horizon (`extendWorkspaceLease`); and the note above on `INV-WS-LEASE-HORIZON-001`, that no old-epoch grant follows an issue write with an unknown outcome (the latch, then the uncertainty check in `RenewWorkspaceLease`).
- `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.
- `INV-WS-RENEW-NONBLOCKING-001`: First grants and expired re-grants are synchronous exceptions (M2 Expired → Granted, `INV-WS-LEASE-REGRANT-001`); the expired path uses TryLock and refuses a busy publisher. The cited live-renewal tests inject delays or holds before or inside the store write; they show sensitivity to a slow store, not a measured disk trace.
- `INV-MASTER-JOURNAL-ISOLATION-001`: a refused heartbeat gets FailedPrecondition. A new placement is either a workspace placement or one the product loop plans. Work the node already has means: the node serves by durable state (a placement slot or a current authority line that names it), a repeated identical placement, or the retry of an issued move. Without strict mode, co-location only raises an alarm.
### B.3 Core: replication and replica roles
@@ -555,9 +648,11 @@ Notes:
| `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`); `TestLocalReopenRejectsForeignClaimImage` (`core/frontend/durable/provider_reopen_belt_test.go`) | — | ACTIVE |
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is the only filer of its group: a master listing another filer or several refuses at once, whichever master answers first; a filer no master lists within 60 s is refused. A startup census, not a fence: a filer added to the group later is not detected. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerFavourableThenStalledRefuses`, `TestIsTargetComparesScopedAddresses`, `TestCheckSingleFilerPasses` (`core/frontend/chunkstore/single_filer_test.go`), `TestChunkWiringRefusesAMultiFilerGroup` (`cmd/blockvolume/single_filer_test.go`), `TestOpsChunk_WritingCommandsRunTheSingleFilerCheck` (`cmd/sw-block/chunk_start_check_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry: same holder and epoch only, no move pending or issued, not revoking, store certain, one durable write, and only once max(horizon, deadline) + skew bound has passed; the new process claims HEAD with a new generation before any I/O, so no older incarnation writes or CASes after. | M2 lease: Expired → Granted | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut`, `TestWorkspaceLeaseRegrantCannotUnsealSameEpoch`, `TestWorkspaceLeaseRegrantEmptyRootClaimsOnlyHEAD` (`core/authority/workspace_regrant_storage_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory` | ACTIVE |
| `INV-WS-LEASE-001` | A host admits frontend I/O and cuts only under an unexpired lease for its exact `{volume, replica, epoch}`; a fenced guard never reopens, even on a late renewal reply. | M4 lease guard: Valid → Fenced | `core/host/volume/workspace_lease.go` `permits`, `Refresh` | `TestWorkspaceLeaseExpiryFencesWithoutTimerAndCannotReopen`, `TestWorkspaceDelayedRenewalCannotUndoExpiry` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostRequiresLeaseBeforeFrontendAndCut` (`core/host/volume/workspace_runtime_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | `WorkspaceTakeover` `NoDualServing` | ACTIVE |
| `INV-WS-REVOKE-ACK-001` | A host acknowledges a revocation only after its frontend and cuts have stopped; a cancelled or expired drain sends no acknowledgement. | M4 lease guard: Revoking → Acked | `core/host/volume/workspace_lease.go` `drain` | `TestWorkspaceRevocationAckOnlyAfterFrontendAndCutsStop` (`core/host/volume/workspace_lease_test.go`); `TestWorkspaceHostCancelOrExpiryDuringRevokeDrainNeverACKs` (`core/host/volume/workspace_runtime_test.go`) | `WorkspaceTakeover` `CleanNoLoss` | ACTIVE |
| `INV-WS-STOP-PENDING-001` | From when the detach hook of a chunk detach runs until the lease guard fences, or until that detach's resume clears stop-pending, each sleep of the guard after a completed renewal is at most 250 ms on the local monotonic clock. | M4 lease guard: Valid → StopPending → Valid \| Fenced | `core/host/volume/workspace_lease.go` `StopPending`, `ClearStopPending`, `renewDelay`, `Run`; `core/host/volume/workspace_runtime.go` `WorkspaceStopPending`, `WorkspaceStopResumed`; `core/frontend/durable/provider_chunk.go` `DetachVolume`, `detachVolume`, `resumeAfterDetach`; `cmd/blockvolume/main.go` `run` (wiring) | `TestWorkspaceLeaseStopPendingSchedule`, `TestWorkspaceHostStopResumedClearsOnlyTheLatestAttempt`, `TestWorkspaceHostFailedDetachStopPendingByOutcome`, `TestWorkspaceHostDetachHookFencesWithinPoll`, `TestWorkspaceLeaseStopPendingNeverBlocks` (`core/host/volume/workspace_lease_stop_pending_test.go`); `TestWALStoreChunk_DetachHookPrecedesDrain`, `TestWALStoreChunk_DetachResumeHookOnlyOnProvenAbort`, `TestWALStoreChunk_DetachCallsStopHook` (`core/frontend/durable/provider_chunk_detach_hook_test.go`) | — | ACTIVE |
| `INV-WS-SAME-HOST-CLEAN-MOVE-001` | A clean move may name the source host as its target only when HEAD is sealed by the current holder and the revocation ACK is recorded for that HEAD generation; it issues a higher epoch. A forced move to the source host is refused. | M2 Acked → Moved (clean); M4 Claiming → Holder | `core/authority/workspace.go` `validateWorkspaceMoveRequest`, `prepareWorkspaceMoveLocked`; `core/host/master/workspace_service.go` `workspaceMoveCheckLocked`; `core/storage/chunk_restore.go` `ClaimChunkHead` | `TestWorkspaceSameHostCleanMoveUsesOvernightSeal` (`core/authority/workspace_same_host_clean_test.go`); `TestWorkspaceRPCSameHostCleanMoveKeepsRepreparedBinding` (`core/host/master/workspace_same_host_clean_test.go`); `TestClaimChunkHeadSameHostCleanMovePreservesSealedImage` (`core/storage/chunk_same_host_clean_test.go`) | `WorkspaceRegrant` `SameHostLoadsSealed` | 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 admitted only after the persisted lease horizon and the granted or restart deadline, each plus the clock-skew bound, have passed for the lease the last move issue started (never a predecessor's): see M2 Expired → Moved (forced). | M2 lease: Expired → Moved (forced) | `core/authority/workspace.go` `prepareWorkspaceMoveLocked`, `WorkspaceForcedMoveAdmitted`, `forcedMoveAdmissionLocked`, `forcedMoveBarrierLocked`, `workspaceHeadAdmits`; `core/host/master/workspace_service.go` `MoveWorkspace`, `workspaceMoveCheckLocked` | `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`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry`, `TestWorkspaceUnclaimedGrantHEADRule`, `TestWorkspaceLateClaimThenUnclaimedGrantForcedReassign` (`core/authority/workspace_unclaimed_grant_test.go`); `TestWorkspaceForcedMoveAdmittedMatchesMoveAdmission` (`core/authority/workspace_forced_admission_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignOverRPC` (`core/host/master/workspace_unclaimed_grant_test.go`); `TestWorkspacePausedGranteeRefusedAtAttach` (`core/host/master/workspace_paused_grantee_test.go`) | — | ACTIVE |
| `INV-WS-FORCED-MOVE-REPLY-001` | The lease expiry the master reports to a host is the granted expiry, never the persisted horizon. | M2 Granted → Granted; Granted → Revoking | `core/authority/workspace_lease_view.go` `RenewWorkspaceLease`, `WorkspaceLeaseReply`, `replyExpiryNS`; `core/host/master/workspace_service.go` `RevokeWorkspace` | `TestWorkspaceLeaseClampsToHorizonUnderStalledStore`, `TestWorkspaceSameVolumeRenewalDuringHeldWrite` (`core/authority/workspace_lease_horizon_test.go`); `TestWorkspaceUnclaimedGrantForcedReassignAfterExpiry` (`core/authority/workspace_unclaimed_grant_test.go`) | — | ACTIVE |
@@ -601,6 +696,7 @@ Notes:
| `INV-CUT-COW-OWNER-001` | Before any read-visible native mutation, a pending candidate has one saving owner; copying/saving collisions wait. The immutable cut buffer is exactly the image at H. | M5 OpenWindow → Copy | `chunk_cut_cow.go` `claim`, `beforeCOWMutation`; Write/WriteBatch/applyEntryV3 pre-publication hooks | `TestCutCOWV3_MutationCompletesWhileEarlierChunkCopyIsHeld`, `TestCutCOWV3_CopyingChunkWaitsButPendingChunkSaves`, `TestCutCOWV3_TwoWritersOneSaveAndCloseJoinsSavedReader`, `TestCutCOWV3_OverlappingRealBatchesPreserveCut` | CutCOW2 BufFrozen/HeadImage; writer/batch multiplicity tested, not modelled | ACTIVE |
| `INV-CUT-COW-DRAIN-001` | Terminal invalidation forbids new references; aborting owners release themselves before join. Side cleanup and destructive transitions wait for actual I/O references. Store Close cannot miss first attachment; every Close waits for full shutdown. | M5 Closed/Aborted → Drain; M1 Close/Recover | `chunk_cut_cow.go` `abort`, `join`, `holdChunkDestructive`; `WALStore.Close`; attach capture admission | `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner`, `TestCutCOWV3_CloseJoinsHeldLiveCopy`, `TestCutCOWV3_CloseSnapshotRejectsFirstAttachAndSharesCompletion`, `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment`, `TestCutCOWV3_SpillIsEphemeralAndCleanupIsPrefixScoped`, `TestCutCOWV3_ProcessCrashDropsSideAndRestoresSyncedImage` | CutCOW2 SideOnlyInCut, abortNoJoin RED; real lifecycle races tested separately | ACTIVE |
| `INV-CUT-PLAIN-DETACH-001` | Plain detach excludes entering/admitted I/O, then seals under the caller context, including a closed idle frontend. Publication and unknown/fenced settlement remain enforced. Closed frontend handles never reopen; absent/false preserves live policy. | M5 Admit -> PlainStop -> Quiesce | `core/frontend/durable/provider_chunk.go` `detachVolume`; `storage_adapter.go` `stopPlainDetachIfIdle`; `core/host/volume/chunk_control.go` | `TestPlainDetachAfterPrecopyRefusalRequiresIdleFrontend`, `TestPlainDetachSkipsPrecopyCostAdmission`, `TestChunkDetachPlainFieldDispatch`, `TestChunkDetachPlainAdapterAndBusyResponse` ; `TestOfflineSealUsesCallerDeadline`, `TestOfflineSealCallerCancelCanRetry` (`core/frontend/durable/provider_offline_seal_test.go`); `TestChunkPlainDetachUsesCallerDeadline`, `TestChunkPlainDetachRequiresExplicitBound` (`core/host/volume/chunk_offline_seal_test.go`) | `PlainDetach` `IdleAtStop`; physical byte and HEAD controls remain native | ACTIVE |
| `INV-STOP-FLIP-CUTOFF-001` | A detach logs 'admission closed at' = the backend's flip, recorded under its mu just after operational goes false: an I/O whose gate ran before it is admitted and drained by StopIO; every gate after it refuses. Logged only on a successful stop. | M5 detach (StopIO / plain stop / pre-copy TryStopIO) | `core/frontend/durable/storage_adapter.go` `setOperationalLocked`, `TryStopIO`, `StopFlipAt`; `provider_chunk.go` detach log | `TestStopFlipIsTheAdmissionCutoff`, `TestLiveDetachLogsWhenAdmissionClosed` (`core/frontend/durable/stopio_began_log_test.go`) | — (no state machine change; the cutoff test is the proof form) | ACTIVE |
| `INV-WS-FREEZE-ACCOUNTING-001` | Frozen detach validates its origin and rechecks elapsed + known estimate against 5 s; override is explicit. Storage reports its admission estimate and quiesce slack using same-host monotonic durations. Stale advice is rechecked before upload; override and actual elapsed remain visible. | G frozen detach (M5) | `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`, `admitFrozenAt`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestFrozenBudgetInputValidation`, `TestFrozenBarrierConsumesElapsedWithoutNewAllowance`, `TestFrozenFinalOverrideIsVisibleEvenWhenEstimateFits`, `TestFrozenValidationPrecedesAnyProviderAccess`; `TestCandidateTailReportsCompleteFrozenBudget`, `TestFrozenRefusalRetainsUnknownCompleteEstimate`, `TestChunkFrozenRequestRefusalCarriesNoBudget`, `TestFrozenDrainObservationPreservesKnownBeforeReasonMutation`, `TestFrozenSaturatedTailRemainsKnownButNonActionable` | `FrozenDetachBudget` `BudgetAtAdmission`, `OverrideVisible`, `ReportSlackSound` | ACTIVE |
| `INV-WS-FREEZE-REFUSAL-001` | HTTP 400 `invalid_freeze_budget`, retryable=false, is returned only by frozen-detach request validation, before any provider admission or mutation. | M5 frozen detach admission: [*] → Refused (invalid frozen request) | `core/host/volume/chunk_control.go` `handleChunkDetach`, `chunkErrorCode`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach`; `core/frontend/durable/provider_chunk.go` `DetachVolumeFrozen` | `TestChunkFrozenValidationHasDistinctPreMutationCode` (`core/host/volume/chunk_frozen_budget_test.go`); `TestFrozenValidationPrecedesAnyProviderAccess` (`core/frontend/durable/frozen_validation_before_access_test.go`) | — (wire classification; validation/admission guards unchanged) | ACTIVE |
| `INV-WS-FREEZE-REFUSAL-INPUTS-001` | The validation refuses a frozen request whose freeze origin is missing, zero or future, or that sets plain, and allowOverBudget without frozen. Premise: the caller and blockvolume run on the same host with the same wall clock source; a cross-host caller would need a skew bound. | M5 frozen detach admission: [*] → Refused (invalid frozen request) | `core/host/volume/chunk_control.go` `handleChunkDetach`; `core/storage/chunk_frozen_budget.go` `WithFrozenDetach` | `TestChunkFrozenValidationHasDistinctPreMutationCode` (`core/host/volume/chunk_frozen_budget_test.go`) | — | ACTIVE |
@@ -611,7 +707,7 @@ Notes:
| `INV-CUT-QUIESCED-001` | HEAD is exactly the image at a quiesced cut H, and H is a synced LSN. | M5 Quiesce → Copy → CAS | `core/storage/chunk_layer.go` `captureLocked` | `TestChunkLayer_C1_HeadIsQuiescedCutImage`, `TestChunkLayer_C3_EveryHeadIsExactUnderConcurrentWrites` (`core/storage/chunk_layer_contract_test.go`) | `CutPipeline` `HeadImage`; `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-BIRTH-001` | A captured chunk birth is bounded by the same-barrier cut frontier: native capture uses min(conservative owned-map maximum, H), retaining lower inherited births. A dropped unacked suffix and reused LSN cannot emit BirthLSN > HEAD.RemoteLSN; the manifest validator still refuses future births. | M5 Quiesce -> Copy -> Manifest | `core/storage/chunk_birth.go` `captureBirths`; `core/frontend/chunkstore/manifest.go` `PrepareManifest` | `TestChunkBirthDroppedSuffixPublishesWithRealManifest` (`core/storage/chunk_birth_manifest_test.go`), `TestChunkBirthCOWDoesNotObservePostBarrierWrite`, `TestChunkBirthBASEUsesInheritedFrontierIncludingZero` | Cut image at H; real recovery/manifest regression, not a new model claim | ACTIVE |
| `INV-CUT-RECONCILING-001` | ARCHIVED: the legacy bitmap/reconciler is retired. Native owned-map validation and fail-closed attach admission replace its dirty-coverage protection; a provided legacy bitmap is ignored. | M5 native map admission | `core/storage/chunk_layer.go` `AttachChunkLayer` | `TestChunkAttachRefusesAnUnmappedNativeStore`; `TestChunkLayerV3_IgnoresProvidedLegacyBitmap` (`core/storage/chunk_layer_map_only_v3_test.go`) | legacy reconciliation transition retired | ARCHIVED |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-STAGED-REUSE-001` | Completed uploads survive a refused point in-process, under their intents. A chunk pre-copied outside the barrier is used only if HEAD generation is unchanged and no write and no same-open `Recover` touched it after staging; otherwise it is copied again in the native COW window. | M5 Stage → Copy | `core/storage/chunk_layer.go` `captureLocked`, `stage` | `TestChunkStageV3_SpillBudgetTriggersPrecopy` (`core/storage/chunk_cut_progress_test.go`); `TestChunkStageV3_AbortedPointReusesUploads` (`core/storage/chunk_cut_progress_test.go`); `TestChunkPrecopy_RedirtiedStagedChunkIsRecopied` (`core/storage/chunk_layer_precopy_test.go`); `TestNativeReplacementRecoverInvalidatesStagedImage` (`core/storage/legacy_replacement_v3_test.go`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-CUT-BITMAP-001` | The owned map never under-reports: its checkpoint coverage is durable before WAL recycling; UNKNOWN is cleared only after definite HEAD publication and an unchanged capture token. | M5 CAS → Settled; M1 InExtent → Checkpointed | `core/storage/walstore_map_checkpoint_v3.go` `publishCheckpointV3`; `core/storage/chunk_layer_map_v3.go` `persistCapturedMapV3` | `TestWALStoreV3_AutomaticMapCheckpoint` (`core/storage/walstore_map_checkpoint_v3_test.go`); `TestChunkLayerV3_ChangedCaptureTokenKeepsUNKNOWN` (`core/storage/chunk_layer_map_v3_test.go`) | `CutCapture` `HeadImage` | ACTIVE |
| `INV-CUT-RECOVER-BARRIER-001` | Native `Recover` aborts and drains OPEN COW owners before lower locks, with admission held through recovery and a hook snapshot recheck. 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` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_DestructiveSnapshotRetriesFirstAttachment` (`core/storage/chunk_cut_cow_lifetime_test.go`); `TestCutCOWV3_RecoveryAndCloseDrainSavingOwner` (`core/storage/chunk_cut_cow_lifetime_test.go`) | — | ACTIVE |
| `INV-CUT-UPLOAD-FROM-BUFFER` | CopyFinish owns an immutable at-H slot. Every PUT retry sends that slot, without rereading local bytes; transient failures keep the point until the caller deadline, window abort or 30-second object deadline. Guest writes to a copied chunk need no save. | M5 Copy -> Upload | `chunk_cut_cow.go` `copyCOWEntry`; `chunk_upload.go` `putCaptured` | `TestCutUploadRetriesPastThreeAttemptsAtSamePoint`, `TestChunkCutUploadDeadlineBoundRetainsDirt`, `TestCutCOWV3_PutRetryUsesFrozenSlot` (`core/storage/chunk_cut_alignment_test.go`) | CutCOW2 BufFrozen; separate upload action extension pending | ACTIVE |
@@ -646,7 +742,7 @@ Notes:
| `INV-CUT-INTENT-CLOSE-001` | Close deletes the intents of reusable uploads and leftover intents, but never an intent of a proposal whose CAS outcome is still unresolved. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `dropIntents` | `TestChunkCloseDropsReusableButKeepsUnknownCASRoots` (`core/storage/chunk_review271_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsIntentsAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | 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-HYDRATION-WAIT-001` | A read command shares its arrival deadline across chunks. A timed-out waiter returns typed pending without cancelling a shared fill. Per-layer worker and distinct-flight limits bound remote work; Close wakes waiters and joins issued fills before storage release. Physical/hash errors remain terminal. | M4 Holder (hydration wait) | `core/storage/chunk_hydration.go`; `core/storage/walstore.go` `ReadContext`; `core/frontend/durable/storage_adapter.go` `readStorageBlock`; `core/frontend/nvme/session.go` `handleRead` | `TestDurableHydration_MultipleChunksShareOneDeadline`, `TestDurableHydration_NVMePreservesPhysicalAndHashErrors`, `TestSessionReadBudgetIncludesQueueResidence`, `TestChunkHydration_QueueAndWorkerLimitsAreBounded`, `TestChunkHydration_CloseWakesCallerAndJoinsUninterruptibleGet`, `TestChunkHydration_ContextlessReadAllowsSlowFill`, `TestChunkHydration_NewGenerationDoesNotJoinStaleGet`, `TestChunkHydration_StaleCompletionKeepsReplacement`, `TestDurableHydration_RMWFenceWinsCallerExpiry` | — | 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 |
| `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) | — | ACTIVE |
| `INV-CUT-TIMER-RESTART-001` | A successful cut of any kind restarts the periodic timer, which runs on in-process monotonic time (a restart starts a fresh schedule; wall-clock steps move nothing). | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestWALStoreChunk_ExplicitCutRestartsTheTimer`, `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`); `TestCutPolicy_TimerRunsOnObservationTime`, `TestCutPolicy_StaggerPreservesExplicitTimerReset` (`core/frontend/durable/cut_policy_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-SKIP-001` | A periodic cut decided from an older last cut is skipped under the capture lock: no automatic cut follows another within the interval. | M5 periodic trigger (before Admit) | `core/storage/chunk_periodic_cut.go` `CutUnlessCutSince`; `core/frontend/durable/provider_chunk.go` `chunkLoop` | `TestChunkPeriodicCut_SkipsAfterANewerCut`, `TestChunkPeriodicCut_SkipsANewerCutWithAnOlderStamp` (`core/storage/chunk_periodic_cut_test.go`); `TestWALStoreChunk_ExplicitCutOverlappingTheTimerRestartsIt` (`core/frontend/durable/provider_chunk_sched_test.go`) | — | ACTIVE |
| `INV-CUT-TIMER-SLOT-WAIT-001` | A periodic cut refused because every host cut slot is held is a wait, not a failure: no backoff or minimum spacing; it retries after a random delay under 200 ms that shrinks with lateness, and status reports the wait until any later cut succeeds. Other errors keep the backoff. | M5 periodic trigger (before Admit) | `core/frontend/durable/provider_chunk.go` `cutPolicy.after`, `chunkLoop`; `core/hostlimit/limiter.go` `ErrSlotsHeld` | `TestCutPolicy_HostSlotBusyIsAWaitNotAFailure`, `TestCutPolicy_SuccessDuringSlotWaitDropsTheSlotRetry`, `TestCutWaitSlot_StatusEndsTheWaitAfterALaterCut`, `TestNewSlotDelay_ShrinksWithLateness`, `TestCutPolicy_OneSlotWaitBound` (`core/frontend/durable/cut_policy_test.go`); `TestTimerCutRunsSoonAfterHostSlotFrees`, `TestSlotWaitEndsWithASuccessfulDetachSeal` (`core/frontend/durable/host_slot_wait_test.go`); `TestAdmitClosedDuringPoolAcquisitionIsRevoked` (`core/hostlimit/limiter_test.go`) | — | ACTIVE |
@@ -656,7 +752,7 @@ A guest read has a cooperative arrival budget; internal contextless readers keep
Notes:
- `INV-CUT-TIMER-RESTART-001`, `INV-CUT-TIMER-SKIP-001`: cuts are identified and ordered by the layer's in-process `CutSeq`, never by the `LastCutNs` wall stamp: a `CutSeq` not seen before is a success at the moment it is observed, and a periodic decision is skipped once `CutSeq` has moved; at start the existing value is not new, so a restart keeps the startup phase. The scheduled-snapshot worker (`INV-SNAP-SCHEDULED-KEEP-001`) runs on the same monotonic time: slots are the loop start plus the volume's offset plus whole periods; a re-armed loop on the same handle keeps its schedule (failures, retry time); a restart starts a fresh one. Tests: `TestScheduledSnapshotLoop_TakesEachSlotOnMonotonicTime`, `_RearmKeepsTheSchedule`, `_OverdueWithNoSuccess`, `TestSnapshotSchedule_SlotsAreOffsetPerVolume`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`.
- Not reachable in this release: `INV-WS-FREEZE-ACCOUNTING-001` (except its estimate and quiesce-slack report, which every successful cut returns) and `INV-CUT-PRECOPY-001`. `/chunk/detach` refuses `frozen` (`INV-CUT-FROZEN-DETACH-REFUSED-001`) and blockvolume refuses `--chunk-detach-precopy` (`INV-CUT-PRECOPY-FLAG-REFUSED-001`), so neither the frozen admission nor the pre-copy admission runs in a released process. Their code is kept and their tests below the HTTP handler still assert them, so their status stays ACTIVE. For the same reason the pre-copy policy that `INV-CUT-PLAIN-DETACH-001` keeps for an absent or false `plain` field is always off. `INV-WS-FREEZE-REFUSAL-001` stays reachable: its HTTP400 validation runs before the refusal. So do `INV-WS-FREEZE-REFUSAL-INPUTS-001` and `INV-WS-FREEZE-REFUSAL-PRECEDENCE-001`.
- `INV-WS-FREEZE-REFUSAL-001`: a generic `bad_request` is not proof of a clean refusal. The validation also refuses a non-frozen request that carries a freeze origin (`handleChunkDetach`). `INV-WS-FREEZE-REFUSAL-INPUTS-001` compares the caller's Unix-nanosecond origin with blockvolume's `time.Now`, with no skew bound.
- `INV-HOST-CUT-BUDGET-001`: an unavailable pool skips normal, fill and idle work with an alarm: see M7 (test `TestUnusablePoolClassPolicy`). Coordinated reservations do not account retained crash spill, fallback leases or process RSS (`HostBudget` excludes fallback). Guest I/O and WAL reclamation never take a slot (M7). Hold expiry (`MaxHold`, `INV-HOST-CUT-BUDGET-SETTLE-001`) and upload pacing (`INV-HOST-CUT-BUDGET-PACING-001`) run on the process's local clock.
- Enforced by reading (no test asserts it): the refusal of a non-frozen request that carries a freeze origin; and an explicit zero freeze origin, which the test sends only as a missing origin (both decode to zero).
@@ -800,9 +896,14 @@ Notes:
| ID | Invariant | Machine / transition | Enforced in | Tests | TLA+ | Status |
|---|---|---|---|---|---|---|
| `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved non-partition node, including dm/md nodes and all slaves, advertises write through; write back or unknown/unreadable device policy selects fsync. `SWBLOCK_SYNC=fsync|fdatasync` explicitly overrides detection (other platforms retain fsync). The selected mode and reason are logged and exposed in durable status without mid-life reselection. Descriptor/map/create/directory durability still uses fsync. `SWBLOCK_ALLOCATION=sparse|prezero` selects allocation at create; sparse is the default and fallocate is refused. `SWBLOCK_PREZERO=1` aliases prezero, which explicitly writes every byte only at create, fsyncs, then refuses holes/unwritten FIEMAP mappings. Existing files are never prezeroed. | M1 Create / Sync / Checkpoint | `data_sync.go`, `device_sync_linux.go`; `walstore_v3.go` Create; `walstore.go` data sync seams; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`), `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncStackNodePolicy`, `TestDeviceDataSyncMalformedTopology`, `TestDeviceDataSyncPolicy`, `TestExplicitDataSyncPolicyDoesNotInspectDevice` (`core/storage/device_sync_linux_test.go`; positive cache fixtures witness empty-stack/cycle guards), `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten`, `TestFallocateAllocationIsRefused`, `TestDefaultCreatedVolumeStaysSparse`, `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE |
| `INV-WAL-DATA-SYNC-001` | `SWBLOCK_SYNC=auto` is the default. Once at volume open, Linux WAL/extent sync selects fdatasync only when every resolved non-partition node, including dm/md nodes and all slaves, advertises write through; write back or an unknown or unreadable device policy selects fsync. | M1 Create / Sync / Checkpoint | `data_sync.go`, `device_sync_linux.go`; `walstore.go` data sync seams | `TestExplicitAutoDataSyncPolicy`, `TestDeviceDataSyncStackNodePolicy`, `TestDeviceDataSyncMalformedTopology`, `TestDeviceDataSyncPolicy` (`core/storage/device_sync_linux_test.go`; positive cache fixtures witness empty-stack/cycle guards), `TestFdatasyncAcknowledgedWritesSurviveSIGKILL`, `TestDataSyncSyscallProbe` (`core/storage/data_sync_linux_test.go`) | Same abstract durable sync action; syscall/extent initialization and process-crash versus power-loss limits are outside the model | ACTIVE |
| `INV-WAL-DATA-SYNC-OVERRIDE-001` | An explicit `SWBLOCK_SYNC=fsync` or `SWBLOCK_SYNC=fdatasync` overrides detection without inspecting the device. Platforms other than Linux keep fsync. | M1 Create / Sync / Checkpoint | `data_sync.go` `configuredDataSyncMode`, `selectedDataSyncMode` | `TestExplicitDataSyncPolicyDoesNotInspectDevice` (`core/storage/device_sync_linux_test.go`) | — | ACTIVE |
| `INV-WAL-DATA-SYNC-STATUS-001` | The data sync mode chosen at open and its reason are logged and exposed in durable status. | M1 Create / Sync / Checkpoint | `data_sync.go` `bindDataFileSync`, `DataSyncPolicy`; `core/frontend/durable/storage_adapter.go` status | `TestDurableProvider_DataSyncStatus` (`core/frontend/durable/data_sync_status_test.go`) | — | ACTIVE |
| `INV-WAL-ALLOCATION-001` | `SWBLOCK_ALLOCATION` selects allocation at create: sparse, the default, or prezero; fallocate is refused. `SWBLOCK_PREZERO=1` is an alias of prezero. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestDefaultCreatedVolumeStaysSparse`, `TestFallocateAllocationIsRefused` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE |
| `INV-WAL-PREZERO-001` | Prezero writes every byte at create and fsyncs; a file opened as initialized is refused when it has holes or unwritten extent mappings. | M1 Create / Sync / Checkpoint | `walstore_v3.go` Create | `TestPrezeroCreatesInitializedVolume`, `TestInitializedFileRejectsSparseAndUnwritten` (`core/storage/data_sync_linux_test.go`) | — | ACTIVE |
| `INV-WAL-FLUSH-SYNC-COVERS-WAL-001` | WAL and extent data live in one store file, and the WAL sync and the flusher's extent sync are the same whole-file fsync or fdatasync of that one descriptor, never a range sync, so every flusher sync also makes the WAL durable. | M1 Serving → Serving (checkpoint) | `core/storage/walstore.go` `openInitializedV3`; `core/storage/data_sync.go` `bindDataFileSync`; `core/storage/flusher.go` `flushOnceInternal` | — | — | STUB |
- `INV-WAL-DATA-SYNC-001` and the rows split from it: enforced by reading, with no test of their own: the mode is not reselected during the life of an open volume; descriptor, map, create and directory durability always use fsync, whatever the data sync mode; an existing file is never prezeroed.
Notes:
- `INV-WAL-FLUSH-SYNC-COVERS-WAL-001`: the one-file, one-descriptor, no-range-sync clause is enforced by reading; no test asserts it yet. Fault-injection tests replace the WAL sync and the extent sync separately and do not check that they are the same call.
@@ -826,16 +927,16 @@ One row per wait in the data and control paths. Guest-visible rows on one path m
|---|---|---|---|---|---|---|
| `core/storage/chunk_publish_settled.go` `runPublishSettled` (from `unlockCap`, on the cut or detach caller's goroutine) | the `OnPublishSettled` hook to return | the hook's duration: the hook must return without blocking and without remote calls, enqueueing its work to its own worker | the hook implementer | none: a stalled hook stalls its caller, and later reports queue without a bound (a nil hook queues nothing) | none (`capMu` and `stMu` released) | yes on detach (the detach caller delivers before returning) |
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.
Format v3 row 4 runs in production recovery (`WALStore.recoverV3`). Its typed scan result preserves trusted records, absolute end, highest LSN, contiguous frontier, trusted DurableLSN and stop cause separately. The W/BASE/fence owner (`WALStore.recoverV3`) 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)
### 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.
- `INV-WAL-V3-READONLY-001` (ACTIVE; the public selector `OpenReadOnly` opens this reader): the 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. Its production caller is `cmd/m01verify`.
- 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)
### 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.
- `INV-WAL-V3-CHUNK-BASE-001` (ACTIVE for mapped v3; no production caller of begin/complete with a layer attached: a layer attaches only with `--durable-impl=walstore-chunk`, which refuses replica roles): 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 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.
@@ -847,6 +948,9 @@ Format v3 row 4 remains dark. Its typed scan result preserves trusted records, a
| Offline seal | M5 PlainStop -> Quiesce; `INV-CUT-PLAIN-DETACH-001` | Caller context; positive HTTP timeoutMs. Completed uploads resume only within one blockvolume process and matching owner/HEAD/chunk versions; after restart the seal must fit seal_timeout_ms. | Provider owns drain, detached cut and settlement. Cancellation preserves unknown/fenced outcome safety; a closed frontend stays closed. | No admission lock held during store or remote I/O. |
| Plain seal remote proof | M5 RemoteProof; `INV-WS-SEAL-REPLAY-001` | Earlier caller context or existing 2 s HEAD-operation bound for the filer read; attachment serialization retains its owner's cooperative caller bound | Provider registers with Close; closeBoundRemote cancels the read, and Close joins it. Failure keeps frontend admission closed. | Attachment mutex serializes against recover/detach; no backend/store/map lock spans the filer read. |
| Frontend pre-copy admission | M5 tentative admission -> resume; `INV-CUT-PRECOPY-001` (not reachable in this release) | Earlier of caller deadline and this command arrival + 5 s; one bound across retries, no inherited pause clock | Owner `finishPrecopyLocked`: resume or terminal Close clears the pause and grants all waiters in FIFO arrival order under one `b.mu` hold; each rechecks the ordinary gate. Expiry removes only its waiter and refuses with typed `ErrBackendBusy` + deadline cause (guest-visible: yes). Only a typed pause refusal requeues a granted waiter under the original command deadline; already-observed stale-primary and other gate errors are returned unchanged. Grant versus queue expiry is decided under the same lock; timely grants survive later queue-timer expiry but never caller expiry or a terminal gate. No dependency on another command's completion. | No `ioMu`, store lock, or remote call while queued. Admitted I/O retains normal per-LBA serialization and lifecycle accounting. |
| v3 write WAL-pressure admission: `core/storage/wal_admission.go` `walAdmission.acquireContext`, called by `WALStore.WriteContext` and `WALStore.WriteBatchContext` | M1 Serving (write admission); `INV-WAL-V3-ADMISSION-001`, `INV-WAL-V3-ADMISSION-DEADLINE-001`, `INV-WAL-V3-ADMISSION-FAULT-001` | The write's store admission deadline, fixed once when the write enters the store: the earlier of the caller's deadline and entry + 4 s (`admissionTimeout`), less a reserve of min(1 s, a quarter of the time then left), so at most entry + 3 s, on the local clock. In the soft band (pressure at least 0.70 and below 0.90) the pressure wait is one sleep of at most 5 ms. | Owner: the flusher. The wait wakes it (`NotifyUrgent`) on entry and at every 2 ms recheck while pressure is at or above the 0.90 hard watermark, and ends once the flusher's progress brings pressure below 0.90; a wait for one of the 64 admission slots ends when another write releases its slot. On expiry the write is refused before its append, with no WAL byte, nextLSN or dirty entry changed: `ErrWALPressureTimeout` (retryable; `frontend.ErrBackendBusy` at the durable backend), or the original fault when a terminal fault has latched, or `context.Canceled` when the caller cancelled. The wait grants no reuse and acknowledges nothing. | Held while waiting: the `captureMu` and `lifecycleMu` read locks, so a capture barrier, a BASE begin or complete, and `Close` wait behind it for at most this bound. Not held while it sleeps: the store, descriptor and WAL writer locks (each pressure sample takes and releases them). Local wait: no remote call. |
The WAL-pressure admission wait is the one wait here held under store locks (the `captureMu` and `lifecycleMu` read locks). It is a local wait: pressure samples, a timer and the flusher's local progress. No remote call is made while those locks are held, so the rule that no remote call runs under a lock still holds.
Frozen estimate reporting: a tail above the existing 60 s estimator ceiling reports the same 60 s rejection sentinel used by admission. It is known but saturated, not a complete fixed-plus-tail duration; quiesce slack is zero. Consumers must not use it as a completion forecast. Drain refusals retain the observation before their reason changes; this reporting does not reclassify refusal causes.
+167 -2
View File
@@ -65,20 +65,99 @@ sudo install -m 0640 -g sw-block deploy/config/*.env deploy/config/topology.yaml
sudo install -m 0644 deploy/systemd/*.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now sw-blockmaster sw-blockvolume
journalctl -u sw-blockvolume -f # wait for "nvme-listening"
journalctl -u sw-blockvolume -f # wait for "adopted as PRIMARY" (see the required setup below)
```
The binaries take command-line flags. The `SWB_*` variables are read only by
the example units, which turn them into flags. blockvolume itself reads only
`SW_BLOCK_ISCSI_CHAP_USERNAME` and `SW_BLOCK_ISCSI_CHAP_SECRET`.
## Required setup: make the volume known to blockmaster
blockmaster gives a blockvolume an assignment only for a volume and replica
slot it already knows. It does not learn volumes from heartbeats. Without an
assignment, blockvolume starts, opens its storage and its listeners, and
serves no I/O.
Outside Kubernetes, a volume becomes known through the accepted-topology file.
Do these steps before you start blockvolume:
1. **Write the topology file.** One entry per volume, one slot per replica;
`volume_id`, `replica_id` and `server_id` are required. This is
[`deploy/config/topology.yaml`](../deploy/config/topology.yaml):
```yaml
volumes:
- volume_id: v1
slots:
- replica_id: r1
server_id: s1
```
2. **Start blockmaster with the file and the matching slot count.**
`--expected-slots-per-volume` must equal the number of slots of each
volume: `1` here (the default is `3`).
```bash
blockmaster --authority-store /var/lib/sw-block-master/authority --listen 127.0.0.1:9180 \
--topology /etc/sw-block/topology.yaml --expected-slots-per-volume 1
```
In `blockmaster.env` these are `SWB_MASTER_TOPOLOGY` and
`SWB_MASTER_EXPECTED_SLOTS`. blockmaster reads the file only at start:
after you change it, run `sudo systemctl restart sw-blockmaster`.
3. **Start blockvolume with the identity of one slot.** `--volume-id`,
`--replica-id` and `--server-id` (`SWB_VOLUME_ID`, `SWB_REPLICA_ID`,
`SWB_SERVER_ID`) must equal one slot of the file: `v1`, `r1`, `s1` here.
**Check before starting blockvolume.** Without a usable topology, blockmaster
logs this line at start; if `journalctl -u sw-blockmaster` shows it, redo
steps 1 and 2:
```
blockmaster: WARNING: --topology not supplied or empty; controller will not mint assignments until topology is provided
```
A file that cannot be read or parsed stops blockmaster with
`blockmaster: topology: ...`.
**Check after.** blockvolume logs `blockvolume: volume v1 adopted as PRIMARY
at r1@<epoch>`, and its status shows a positive `Epoch`, `"Healthy":true` and
`"AuthorityRole":"primary"`:
```bash
journalctl -u sw-blockvolume | grep 'adopted as PRIMARY'
curl -s 'http://127.0.0.1:9203/status?volume=v1'; echo
```
`nvme-listening` alone does not prove this: blockvolume starts its NVMe/TCP
listener before it has an assignment. Without one, the status shows
`"Epoch":0`, `"Healthy":false` and `"AuthorityRole":"unknown"`.
| What you see | Missing step |
|---|---|
| blockvolume logs `blockvolume: subscribe stream: rpc error: code = Unknown desc = subscribe: volume "v1" not in accepted topology`, again every few seconds | blockmaster has no topology, or `v1` is not in it (steps 1, 2) |
| `walstore-chunk` only: `durable: chunk layer for volume=v1 waits for master authority (up to 30s): projection lacks healthy=false epoch=0`, and 30 s later `durable: chunk authority wait for volume=v1 ended after ...: assignment unavailable, not serving (projection lacks healthy=false epoch=0)` | The same. This wait runs once per start: after the fix, restart blockvolume too |
| No error in either log, and `"Epoch":0` stays | `--expected-slots-per-volume` differs from the slot count (step 2), or `--server-id` or `--replica-id` differ from the slot (step 3) |
| blockmaster logs `authority: rejected ask ...: workspace publication: no lifecycle VolumeRecord for v1; register it (CreateVolume) before publishing` | blockmaster runs with `--lifecycle-store`: a topology slot is then not enough, the volume also needs a volume record (below) |
**Workspace lease volumes (`--workspace-lease`).** Besides the steps above,
blockmaster needs `--workspace-rpc`, `--workspace-head-base-url` and
`--lifecycle-store`, and the volume needs a single-replica volume record in
that store. This release has no `sw-block` command that creates that record. Check with `sw-block ops workspace show --master 127.0.0.1:9180
--volume v1`; it names the first missing piece: `workspace RPC disabled`,
`lifecycle store unavailable`, or `workspace move requires an existing RF1
volume`. A move target must also be a registered node, or the move is refused
with `move target node "s2" is not registered`.
## blockmaster settings
| Variable | Flag | Default | Meaning |
|---|---|---|---|
| `SWB_MASTER_AUTHORITY_STORE` | `--authority-store` | required | Durable authority store: assignments, epochs, leases |
| `SWB_MASTER_LISTEN` | `--listen` | `127.0.0.1:0` | gRPC address; unauthenticated, keep it on loopback or a trusted network |
| `SWB_MASTER_TOPOLOGY` | `--topology` | empty (no assignments minted) | Accepted-topology YAML: volumes and replica slots |
| `SWB_MASTER_TOPOLOGY` | `--topology` | empty (no assignments minted: no volume serves) | Accepted-topology YAML: volumes and replica slots; required outside Kubernetes, read only at start |
| `SWB_MASTER_EXPECTED_SLOTS` | `--expected-slots-per-volume` | `3` | Replica slots per volume; `1` for a single replica |
| `SWB_MASTER_FRESHNESS_WINDOW` | `--freshness-window` | `30s` | How long a heartbeat stays fresh |
| `SWB_MASTER_PENDING_GRACE` | `--pending-grace` | `1s` | Startup grace before a missing observation is unsupported |
@@ -154,6 +233,10 @@ group while volumes run.
- **On an NVMe root,** and in that disk's other attaches: the fsync took 50-75 microseconds and the publish 2-3 milliseconds.
- **Cause:** not yet established.
- **Check the device:** `lsblk -d -o NAME,ROTA,TRAN,MODEL`, and the line blockvolume logs at start, `storage: WAL/extent sync=... file=... reason=...`, whose reason names the root's device.
- **NVMe/TCP needs native NVMe multipath on the host (`nvme_core multipath=Y`, the Ubuntu default).**
The device lookup below, and the CSI node plugin's, find the namespace as an `nvmeXnY` entry under
`/sys/class/nvme-subsystem/nvme-subsysN/`; with multipath off that directory holds no namespace entry and
neither finds the device. Check: `cat /sys/module/nvme_core/parameters/multipath` must print `Y`.
- ublk needs root. Use `sw-blockvolume-ublk.service` instead of editing the
unprivileged unit, and load `ublk_drv` at boot
(`echo ublk_drv | sudo tee /etc/modules-load.d/ublk.conf`).
@@ -293,6 +376,67 @@ The script's default engine is `SW_BLOCK_DURABLE_IMPL=smartwal`; the command
above sets `walstore`, the engine used by the Kubernetes chart and the
workspace path. There is no equivalent script for ublk yet.
## Planned workspace hand-over
For an RF1 chunk volume with a workspace lease, inspect the current logical
holder with `sw-block ops workspace show --master MASTER --volume V`. Copy the
replica and epoch exactly. The view prints the master's lease state, recorded
revocation ACK (including its HEAD generation), move records and bindings. It
does not infer a physical holder from the binding list; a binding is not proof
of a current assignment. Reported validity is a snapshot, not permission to
serve I/O.
`expired` means the master reported no positive **host validity** at query
time; it is not a claim that the master's forced-move horizon has passed.
Only the master admits a move.
Perform a clean hand-over in this order:
1. Stop the application/writer and prevent new I/O to the old attachment.
2. Seal the idle volume while its lease still permits publication:
```bash
sw-block ops chunk detach --plain --volume V --status-addr OLD_STATUS --timeout 120s >seal.json
```
Busy admission refuses the operation. Do not proceed on any failure or
unknown outcome. JSON remains on stdout; a successful command also prints
`sealed HEAD generation: G` on its own stderr line, taken from the same
JSON `headGen` field on stdout. Copy the positive `G`.
3. Request revocation using that seal and the identity from `show`:
```bash
sw-block ops workspace revoke --master MASTER --volume V --replica R --epoch E --sealed-gen G
```
Seal **before** revocation: revoking first can prevent the old host from
publishing the final image and leave only a lossy forced move. The CLI
requires exactly one of `--sealed-gen G` or `--without-seal`. The former is
your statement, not a storage check. The latter explicitly abandons the
unpublished tail and does not promise that a clean move is possible.
4. Run `ops workspace show --master MASTER --volume V` until the **recorded
ACK** names the same replica `R`, epoch `E` and HEAD generation `G`.
A successful `revoke` reply alone is not that ACK.
5. Ask for the clean authority move:
```bash
sw-block ops workspace move --clean --master MASTER --volume V --replica R --epoch E \
--target-host NEW_HOST --target-data DATA_ADDR --target-ctrl CTRL_ADDR --request-id MOVE_ID
```
Use registered target endpoints. The master checks the seal and matching
ACK. The target may be the source host once sealed, when the server supports
same-host clean reload. A command refuses rather than bypassing a missing
seal, ACK or current identity. On an **unknown outcome**, rerun with the
**SAME `--request-id MOVE_ID`**; never use a new id to guess whether it ran.
6. Start `blockvolume` on the target separately with the granted replica and
new epoch and the normal workspace-lease options. The move command only
transfers authority; it does not start the target or reconnect clients.
Workspace commands exit 0 on success, 1 on a definite server refusal, 2 on local
usage refusal, 3 on an unknown outcome, and 4 on an unproven readout. Plain
detach keeps the chunk CLI's existing JSON error and exit policy. Neither CLI
retries or polls automatically.
## Snapshots, restore and space (walstore-chunk)
**Recovery point.**
@@ -372,6 +516,27 @@ Check the data afterwards. `--depth data` reads every chunk once.
sw-block ops chunk verify --volume v1 --chunk-filer FILER --all-snapshots --depth data --timeout 30m
```
### SeaweedFS maintenance commands that destroy chunk volumes
A walstore-chunk volume keeps its data in SeaweedFS as needles that **no file's chunk list names**: the volume's
own records in the filer point at them. SeaweedFS tools that decide what is referenced from file chunk lists
therefore see every chunk of every volume and snapshot as unreferenced.
- **Never run `volume.fsck` with `-reallyDeleteFromVolume`** (alone or with `-forcePurging`) on a SeaweedFS
cluster that stores walstore-chunk volumes. It deletes the needles it considers orphaned, once they are older
than `-cutoffTimeAgo` (5 hours by default): that is the volumes' data, including every snapshot. There is no undo.
- **Never run `volume.fsck -findMissingChunksInFiler` with `-reallyDeleteFilerEntries` or
`-reallyDeleteFromVolume`** on such a cluster either.
- `volume.fsck` **without** those flags only reports. Its orphan list will contain the chunk needles; that is
expected and is not a fault.
- **Give chunk data its own collection** (`--chunk-collection`, `SWB_CHUNK_COLLECTION`) so it is easy to keep
cluster maintenance away from it. Do not put a TTL on that collection and do not delete it: both remove needles
without regard to what refers to them.
- `filer.sync`, `filer.backup` and `filer.replicate` copy file chunk lists. They do **not** copy a walstore-chunk
volume: the copied records would point at needles that do not exist on the target.
- Space is returned only by the two steps above (`sw-block ops chunk gc`, then a SeaweedFS vacuum). `volume.vacuum`
is safe: it compacts needles that were already deleted.
### Restoring a snapshot into a new volume
A restore makes a new, independent volume from a snapshot. The source volume and its snapshot can be deleted afterwards.
+37 -1
View File
@@ -17,7 +17,9 @@ the assignment. Blockvolume closes frontend admission, drains and closes the
frontend, replication, and provider, reads the stored detached HEAD, and only
then ACKs its exact generation. The authority refuses an expired lease's ACK.
Revocation does not perform a final cut. Lease expiry or cancellation closes
the host without a CLEAN ACK or cut; recovery uses a FORCED move.
the host without a CLEAN ACK or cut. A new process of the unchanged holder
and epoch may return through a durable re-grant as described below; a move
to a different holder still requires the move protocol.
The shared projection loads the guard atomically. Guard operations serialize
renewal, drain, and ACK with the operation mutex; the state mutex is held only
@@ -70,3 +72,37 @@ defaults). Beyond that, grants shrink and hosts fence: the design fails
closed. Blockmaster logs one warning per failure streak, with the write's
latency and the remaining horizon, when an extension fails, and one when
grants start to be clamped to the horizon, and a line when either recovers.
## Returning after an expired lease
Restarting the same holder at the same epoch can retain its acknowledged
local WAL after a long outage. Re-grant waits for the existing forced-move
barrier: both the durable horizon and the granted or conservative restart
deadline, each plus the full configured/persisted skew bound, must have
passed. The master then persists one new horizon before returning the grant;
neither horizon nor skew is reduced. Immediate repeated renewals use memory,
so they do not add durable re-grant writes while that grant is live.
The authority record must still name this holder and epoch. A pending move,
revocation/ACK or uncertain store prevents a usable re-grant. Re-grant and
forced issue serialize; whichever commits first makes the other refuse.
If an authority writer holds the lock, this renewal attempt refuses
immediately; a returning process may retry after the writer settles.
An already fenced guard never reopens: start a new process, which claims a
new HEAD generation before serving and retains its local WAL. Its first cut
covers those acknowledged bytes. If the local root is absent, recovery
restores only the sealed/published HEAD image and never claims missing local
bytes. A same-epoch detached HEAD stays detached even after a lease re-grant.
## Planned return on the same host
After plain detach seals HEAD and revocation records its exact generation,
a clean move may target the source host itself. Prepare the binding again
before requesting the move. The move journals a higher epoch even when its
endpoints are unchanged; start the returning blockvolume at that new epoch.
It claims the sealed HEAD before serving and preserves the sealed image and
remote frontier. The matching seal/ACK remains valid overnight while HEAD
is unchanged. A same-epoch reopen remains detached, and a forced move to the
same host is refused. Every ordinary binding, endpoint collision, journal
isolation and uncertain-outcome check still applies.
@@ -263,4 +263,4 @@ func TestInvariantStatementsAreShort(t *testing.T) {
// longStatementsLeft is the number of rows testdata/long-statements.txt may
// name. It only goes down.
const longStatementsLeft = 18
const longStatementsLeft = 0
@@ -1,19 +1 @@
# Part B rows whose Statement is over 300 characters. This list only shrinks: split a row into rows of one property each, then delete its line; never add one.
INV-FE-NVME-READY-001
INV-WAL-DATA-SYNC-001
INV-WAL-V3-ACTIVATION-001
INV-WAL-V3-ADMISSION-001
INV-WAL-V3-BASE-001
INV-WAL-V3-BATCH-001
INV-WAL-V3-BINDING-001
INV-WAL-V3-CATCHUP-001
INV-WAL-V3-DESCRIPTOR-001
INV-WAL-V3-FENCE-001
INV-WAL-V3-INSTALL-ACK-001
INV-WAL-V3-MAP-BYTES-001
INV-WAL-V3-MAP-PUBLISH-001
INV-WAL-V3-PUBLISH-001
INV-WAL-V3-RECLAIM-001
INV-WAL-V3-RECORD-001
INV-WAL-V3-RESET-001
INV-WAL-V3-W-001