Merge pull request #786 from seaweedfs/train/20261129-t1

train: eight accepted v1.0.1 PRs (#780 #771 #775 #779 #778 #773 #776 #777)
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-11-29 15:46:25 -08:00
commit d5bd456952
38 files changed
+1199 -365

No files matched your search

+10
View File
@@ -4,6 +4,13 @@ Model: <Module.Action; OtherModule.Action, or NONE (pure function of Module) for
Red-first: <commit + test that failed on the base, or NONE: reason>
Simplest: <the simplest version, and what this PR did not add>
Five questions, answered in plain words before review:
Serves: <which statement of the specification or the docs this change serves>
Decided by: <whose decision this is, and where it is recorded>
Layer use: <conventional: the layer below is used the usual way; or the deviation>
Deviation buys: <what the deviation buys, measured; or none: no deviation>
Weakens: <which existing guarantee this weakens (its cost, the way it fails, a mode it leaves out, whether its proof runs on the production type), or none and why>
<!--
The spec-trace check reads the lines above.
@@ -24,6 +31,9 @@ DOCS may still change contract text (docs/design/invariants.md): the reviewer is
NONE needs a reason of at least 10 characters. Simplest is required when the PR
changes non-test Go under core/ or cmd/.
Weakens is required on every PR that changes product code: a review is refused
without it. "none" needs its reason.
Mapped files in .github/model-code-trace.tsv require a listed Module.Action
or NONE (pure function of Module). Separate citations for multiple modules
with semicolons. Unmapped files retain the existing Model trace policy.
@@ -12,7 +12,7 @@ import (
// 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")
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1")
parse := func(iv string) error {
_, err := parseFlags(append(append([]string{}, base...), "--chunk-capture-interval="+iv))
return err
@@ -0,0 +1,23 @@
package main
import (
"strings"
"testing"
)
func TestChunkVolumeRequiresWorkspaceLeaseBeforeStart(t *testing.T) {
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--chunk-filer=filer:18888")
for _, extra := range [][]string{nil, {"--workspace-lease=false"}} {
_, err := parseFlags(append(append([]string{}, base...), extra...))
if err == nil || !strings.Contains(err.Error(), "--workspace-lease is required") || !strings.Contains(err.Error(), "forced move") {
t.Fatalf("unleased chunk start: %v", err)
}
}
if _, err := parseFlags(append(base, "--workspace-lease")); err != nil {
t.Fatalf("leased chunk start: %v", err)
}
plain := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore")
if _, err := parseFlags(plain); err != nil {
t.Fatalf("plain walstore unexpectedly requires a workspace lease: %v", err)
}
}
@@ -22,7 +22,8 @@ var errNoLayoutHolder = errors.New("blockvolume: no layout holder identity for t
// cleaning entry: a cut or a stop cancels it through the remote's state.
// cleanerOf returns the remote Start established; its Begin refuses unless
// HEAD is still that holder's at its epoch, so a process that lost the
// volume removes nothing. Automatic cleaning stays default-off; retention runs either way.
// volume removes nothing. Automatic cleaning is on by default (--chunk-maintenance-gc);
// retention runs either way.
// layoutCleaner is the holder's layout remote as the maintenance cleans
// through it (chunkstore.LayoutRemote).
type layoutCleaner interface {
@@ -18,7 +18,7 @@ func TestWALStoreChunkFlags(t *testing.T) {
base := func(extra ...string) []string {
return append(phase150RequiredBlockvolumeArgs(), extra...)
}
f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
f, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease",
"--chunk-filer=127.0.0.1:18888", "--chunk-capture-interval=5m"))
if err != nil {
t.Fatalf("walstore-chunk with a filer: %v", err)
@@ -26,12 +26,12 @@ func TestWALStoreChunkFlags(t *testing.T) {
if f.chunk.filer != "127.0.0.1:18888" || f.chunk.path != defaultChunkPath || f.chunk.captureInterval != 5*time.Minute || f.chunk.controlEndpoint {
t.Fatalf("parsed chunk flags = %+v", f.chunk)
}
f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
f, err = parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1",
"--status-addr=127.0.0.1:0", "--chunk-control-endpoint"))
if err != nil || !f.chunk.controlEndpoint {
t.Fatalf("walstore-chunk with the control endpoint: %+v %v", f.chunk, err)
}
d, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"))
d, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1"))
if err != nil {
t.Fatal(err)
}
@@ -39,15 +39,15 @@ func TestWALStoreChunkFlags(t *testing.T) {
t.Fatalf("scheduler defaults: capture %s, maintenance %s, cleaning %v; want capture off (0), maintenance 1h and the cleaning on", d.chunk.captureInterval, d.chunk.maintenanceInterval, d.chunk.automaticGC)
}
// The cleaning is on by default; the one way to turn it off is explicit.
noClean, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-maintenance-gc=false"))
noClean, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-maintenance-gc=false"))
if err != nil || noClean.chunk.automaticGC || noClean.chunk.maintenanceInterval != time.Hour {
t.Fatalf("turning the cleaning off: %+v %v", noClean.chunk, err)
}
on, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-capture-interval=15m"))
on, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=15m"))
if err != nil || on.chunk.captureInterval != 15*time.Minute {
t.Fatalf("opting in to a 15m periodic cut: %+v %v", on.chunk, err)
}
off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
off, err := parseFlags(base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1",
"--chunk-capture-interval=0"))
if err != nil || off.chunk.captureInterval != 0 {
t.Fatalf("disabling the timer: %+v %v", off.chunk, err)
@@ -56,27 +56,30 @@ func TestWALStoreChunkFlags(t *testing.T) {
t.Fatalf("walstore with the chunk defaults untouched: %v", err)
}
refused := map[string][]string{
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk"),
"no durable root": base("--durable-impl=walstore-chunk", "--chunk-filer=127.0.0.1:18888"),
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=swblock"),
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-path=/"),
"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"),
"no filer": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease"),
"no durable root": base("--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=127.0.0.1:18888"),
"relative path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-path=swblock"),
"root path": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-path=/"),
"below OSS capture floor": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=4m59s"),
"60 s in an OSS build": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=60s"),
"negative maintenance": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-maintenance-interval=-1s"),
"negative interval": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-capture-interval=-1s"),
"chunk flag on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-filer=x:1"),
"chunk path on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-path=/other"),
"control endpoint on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--status-addr=127.0.0.1:0",
"--chunk-control-endpoint"),
"control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk",
"control endpoint without a status listener": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease",
"--chunk-filer=x:1", "--chunk-control-endpoint"),
"zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"),
"too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"),
"zero upload concurrency": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-upload-concurrency=0"),
"too many uploads": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-upload-concurrency=65"),
"interval on walstore": base("--durable-root=/tmp/sw-block", "--durable-impl=walstore", "--chunk-capture-interval=5s"),
}
for name, args := range refused {
if _, err := parseFlags(args); err == nil {
_, err := parseFlags(args)
if err == nil {
t.Errorf("%s: parseFlags succeeded; want an error", name)
} else if name == "no filer" && !strings.Contains(err.Error(), "requires --chunk-filer") {
t.Errorf("missing filer refused for wrong reason: %v", err)
}
}
}
@@ -88,7 +91,7 @@ func TestChunkDetachPrecopyFlagRefused(t *testing.T) {
base := func(extra ...string) []string {
return append(phase150RequiredBlockvolumeArgs(), extra...)
}
valid := []string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1",
valid := []string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1",
"--status-addr=127.0.0.1:0", "--chunk-control-endpoint"}
f, err := parseFlags(base(valid...))
if err != nil || f.chunk.detachPrecopy {
@@ -257,7 +260,7 @@ func (*layoutAttachFiler) Get(context.Context, string) ([]byte, error) {
// replica id are different holders (B9 W2 appendix).
func TestChunkHolderIsServerAndReplica(t *testing.T) {
f, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block",
"--durable-impl=walstore-chunk", "--chunk-filer=x:1"))
"--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1"))
if err != nil {
t.Fatal(err)
}
@@ -270,7 +273,7 @@ func TestChunkHolderIsServerAndReplica(t *testing.T) {
// copy-on-write budget (M5 Stage), so the flag never had an effect. A unit
// that still passes it fails at start.
func TestChunkDirtyThresholdFlagIsGone(t *testing.T) {
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1", "--chunk-dirty-threshold=512")
args := append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1", "--chunk-dirty-threshold=512")
if _, err := parseFlags(args); err == nil || !strings.Contains(err.Error(), "flag provided but not defined") {
t.Fatalf("--chunk-dirty-threshold: %v; want flag provided but not defined", err)
}
@@ -284,7 +287,7 @@ func TestChunkSnapshotScheduleFlag(t *testing.T) {
return append(phase150RequiredBlockvolumeArgs(), extra...)
}
chunk := func(extra ...string) []string {
return base(append([]string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"}, extra...)...)
return base(append([]string{"--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1"}, extra...)...)
}
d, err := parseFlags(chunk())
if err != nil || d.chunk.snapshotSchedule != (snapshotSchedule{period: 24 * time.Hour, keep: 7}) {
@@ -12,7 +12,7 @@ import (
// (the master's workspace RPCs already do).
func TestChunkVolumeRefusesReplicationAckAtStart(t *testing.T) {
base := []string{"--master", "127.0.0.1:1", "--server-id", "node-a", "--volume-id", "v1", "--replica-id", "r1", "--data-addr", "127.0.0.1:9100", "--ctrl-addr", "127.0.0.1:9101"}
chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888")
chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--workspace-lease", "--chunk-filer", "127.0.0.1:18888")
for _, ack := range []string{"sync-quorum", "sync-all"} {
_, err := parseFlags(append(append([]string{}, chunk...), "--replication-ack", ack))
if err == nil || !strings.Contains(err.Error(), "single-replica") || !strings.Contains(err.Error(), "RF1 only") {
@@ -29,7 +29,7 @@ func (cleaningView) Projection() frontend.Projection {
// current root names and stops growing.
func TestDefaultConfigCleansAfterEachSnapshotDelete(t *testing.T) {
ctx := context.Background()
d, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--chunk-filer=x:1"))
d, err := parseFlags(append(phase150RequiredBlockvolumeArgs(), "--durable-root=/tmp/sw-block", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1"))
if err != nil {
t.Fatal(err)
}
@@ -91,7 +91,7 @@ func TestExistingDurableVolumeDisappearsDoesNotCreateFromIgnoredFlags(t *testing
}
args := append(phase150RequiredBlockvolumeArgs(), "--volume-id=v1", "--durable-root="+root, "--durable-impl="+string(impl), "--durable-blocks=4294967297")
if impl == durable.ImplWALStoreChunk {
args = append(args, "--chunk-filer=127.0.0.1:18888")
args = append(args, "--chunk-filer=127.0.0.1:18888", "--workspace-lease")
}
f, err := parseFlags(args)
if err != nil {
@@ -6,7 +6,7 @@ import (
)
func TestHostCutLimitFlags(t *testing.T) {
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--chunk-filer=x:1")
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root="+t.TempDir(), "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1")
dir := t.TempDir()
args := append(append([]string{}, base...), "--host-limit-dir="+dir, "--host-limit-normal-slots=2", "--host-limit-urgent-slots=1")
f, e := parseFlags(args)
@@ -3,7 +3,7 @@ package main
import "testing"
func TestChunkHydrationFlagsAreConfigurable(t *testing.T) {
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--chunk-filer=x:1")
base := append(phase150RequiredBlockvolumeArgs(), "--durable-root=hydration-test", "--durable-impl=walstore-chunk", "--workspace-lease", "--chunk-filer=x:1")
f, err := parseFlags(append(base, "--chunk-hydration-workers=3", "--chunk-hydration-queue-depth=17"))
if err != nil || f.chunk.hydrationWorkers != 3 || f.chunk.hydrationQueueDepth != 17 {
t.Fatalf("hydration limits: %+v err=%v", f.chunk, err)
+4 -1
View File
@@ -198,7 +198,7 @@ func parseFlags(args []string) (flags, error) {
fs.StringVar(&f.ctrlAddr, "ctrl-addr", "", "control-path address (required)")
fs.DurationVar(&f.hbInterval, "heartbeat-interval", 2*time.Second, "heartbeat send interval")
fs.DurationVar(&f.recoverTimeout, "recover-timeout", volume.DefaultRecoverTimeout, "maximum inactivity without new completed recovery or attach work for a primary-assigned replica before it reports unhealthy (recovery_timeout); not a total startup deadline")
fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "walstore-chunk workspace: require host-owned master lease; fail closed when unavailable")
fs.BoolVar(&f.workspaceLease, "workspace-lease", false, "required for walstore-chunk: require host-owned master lease; fail closed when unavailable")
fs.BoolVar(&f.printReadyLine, "t0-print-ready", false, "internal test-only: emit one structured JSON line on stdout on first assignment")
fs.BoolVar(&f.enableT1Readiness, "t1-readiness", false, "enable readiness bridge (HealthyPathExecutor) so adapter projection reaches Healthy")
fs.StringVar(&f.statusAddr, "status-addr", "", "address for the status HTTP endpoint (e.g. 127.0.0.1:0); empty disables")
@@ -328,6 +328,9 @@ func parseFlags(args []string) (flags, error) {
if err := validateChunkFlags(f); err != nil {
return flags{}, err
}
if f.durableImpl == "walstore-chunk" && !f.workspaceLease {
return flags{}, fmt.Errorf("--workspace-lease is required for walstore-chunk: without a master lease two writers can acknowledge I/O and an old holder can lose acknowledged writes after a forced move; restart with --workspace-lease")
}
if f.durableWALMultiBlockRecords {
if f.durableRoot == "" {
return flags{}, fmt.Errorf("--durable-wal-multiblock-records requires --durable-root")
@@ -113,7 +113,7 @@ func TestProcedureKillDuringPlainDetachThenCompleteHandoff(t *testing.T) {
env.requireCutCrashImage(t, "s2", 'B')
verified, _ := env.h.command(t, "ops", "chunk", "verify", "--volume", "v1",
"--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath,
"--depth", "data", "--timeout", "60s", "--bytes-per-sec", "0")
"--depth", "data", "--timeout", "60s")
var result layout.VerifyResult
if err := json.Unmarshal([]byte(verified), &result); err != nil || !result.Complete ||
len(result.Findings) != 0 || result.Chunks == 0 {
@@ -12,9 +12,8 @@ func TestWorkspaceLeaseFlagIsExplicitAndChunkOnly(t *testing.T) {
t.Fatal("workspace lease accepted without walstore-chunk")
}
chunk := append(append([]string{}, base...), "--durable-root", t.TempDir(), "--durable-impl", "walstore-chunk", "--chunk-filer", "127.0.0.1:18888")
disabled, err := parseFlags(chunk)
if err != nil || disabled.workspaceLease {
t.Fatal("ordinary chunk volume opted in", err)
if _, err := parseFlags(chunk); err == nil {
t.Fatal("chunk volume started without its required workspace lease")
}
enabled, err := parseFlags(append(chunk, "--workspace-lease"))
if err != nil || !enabled.workspaceLease {
+15 -8
View File
@@ -35,18 +35,25 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
fs.StringVar(&master, "master", "", "blockmaster gRPC address (resolves --volume name to its full layout identity)")
fs.StringVar(&filer, "chunk-filer", "", "SeaweedFS filer gRPC address host:port")
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
fs.StringVar(&snapshot, "snapshot", "", "accepted for compatibility: every snapshot HEAD names is always checked")
fs.BoolVar(&allSnapshots, "all-snapshots", false, "accepted for compatibility: every snapshot HEAD names is always checked")
fs.StringVar(&snapshot, "snapshot", "", "unsupported: every snapshot HEAD names is always checked")
fs.BoolVar(&allSnapshots, "all-snapshots", false, "unsupported: every snapshot HEAD names is always checked")
fs.StringVar(&depth, "depth", "bindings", "meta or bindings: every named object exists; data: and every chunk's bytes hash to its name")
fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)")
fs.IntVar(&concurrency, "concurrency", 1, "accepted for compatibility: chunks are read one at a time")
fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "accepted for compatibility: chunk reads are not paced")
fs.IntVar(&concurrency, "concurrency", 1, "unsupported: chunks are read one at a time")
fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "unsupported: chunk reads are not paced")
fs.DurationVar(&timeout, "timeout", 10*time.Minute, "bound for the whole pass; required with --depth data")
if err := fs.Parse(args); err != nil {
return chunkFail(chunkName(fs), stdout, stderr, ops.VolumeStatusExitInvalid, codeBadRequestCLI, err.Error(), false)
}
timeoutSet := false
unsupported := ""
fs.Visit(func(f *flag.Flag) {
switch f.Name {
case "snapshot", "all-snapshots", "concurrency", "bytes-per-sec":
if unsupported == "" {
unsupported = f.Name
}
}
if f.Name == "timeout" {
timeoutSet = true
}
@@ -56,6 +63,8 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
}
d := map[string]string{"meta": layout.DepthNames, "bindings": layout.DepthNames, "data": layout.DepthFull}[depth]
switch {
case unsupported != "":
return usage("--" + unsupported + " is unsupported; verify checks every named snapshot sequentially without pacing")
case fs.NArg() != 0:
return usage("unexpected arguments")
case volumeID == "":
@@ -64,12 +73,10 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
return usage("--chunk-filer is required")
case d == "":
return usage(fmt.Sprintf("--depth %q: meta, bindings or data", depth))
case snapshot != "" && allSnapshots:
return usage("--snapshot and --all-snapshots do not combine")
case d == layout.DepthFull && !timeoutSet:
return usage("--depth data reads every chunk: give an explicit --timeout for the pass")
case timeout <= 0 || concurrency <= 0 || bytesPerSec < 0:
return usage("--timeout and --concurrency must be positive and --bytes-per-sec not negative")
case timeout <= 0:
return usage("--timeout must be positive")
}
// One bound for the whole pass, the single-filer start check included.
// Verify writes nothing, but against a split filer view it would report
@@ -73,6 +73,14 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) {
t.Fatal(err)
}
put(layout.HeadName, hb)
e, err := mem.LookupEntry(ctx, root, layout.HeadName)
if err != nil {
t.Fatal(err)
}
e.Extended = map[string][]byte{"swb.layout.kind": []byte("head"), "swb.layout.volume": []byte(id.String()), "swb.layout.gen": []byte("1")}
if err := mem.UpdateEntry(ctx, root, e, nil); err != nil {
t.Fatal(err)
}
return mem, path.Join(root, last)
}
@@ -227,3 +235,21 @@ func TestOpsChunk_VerifyStartCheckIsBoundedByTheTimeout(t *testing.T) {
t.Errorf("verify: exit %d, out %q; want a retryable remote_unavailable refusal", code, out.String())
}
}
func TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial(t *testing.T) {
old := dialChunkFiler
dials := 0
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) {
dials++
return nil, nil, fmt.Errorf("unexpected dial")
}
t.Cleanup(func() { dialChunkFiler = old })
for _, arg := range []string{"--snapshot=s1", "--all-snapshots", "--all-snapshots=false", "--concurrency=1", "--bytes-per-sec=0"} {
t.Run(arg, func(t *testing.T) {
code, out, _ := runChunk("verify", "--volume=v1", "--chunk-filer=f:1", arg)
if dials != 0 || code != 2 || chunkErrorOut(t, out).Code != codeBadRequestCLI || !strings.Contains(out, "unsupported") {
t.Fatalf("exit=%d out=%s", code, out)
}
})
}
}
@@ -1,263 +0,0 @@
# Chunk garbage collection (W5)
`NewCollector(catalog, blobDeleter, config).Run(ctx)` traces every volume returned by the catalog, every HEAD, every snapshot (including unnamed attempt entries), and every live upload/copy intent. Use a deadline-bound context. Supply `IssuedEpoch` from the authoritative blockmaster reader, not lease expiry or a host-local projection. The CLI below binds that reader to blockmaster; there is no automatic scheduler.
A capture intent can expire only when its age strictly exceeds IntentTTL, the blockmaster has issued a higher epoch, and the actual remote HEAD has advanced to a higher epoch no greater than the issued one. Unknown authority retains it. Snapshot/fork copy intents never expire by epoch. `SweepCopies(ctx)` may settle an attempt past its recorded deadline only by claiming its final immutable publication target through Catalog.AbortSnapshot/AbortFork. Snapshot targets are `snaps/<name>/<attempt>`; fork targets are HEAD, never VOLUME. A confirmed permanent aborted target or a validated published target settles the intent. Unknown claim/read retains it. The deadline admits a claim but never by itself releases protection. Old copy intents without deadline metadata remain protected.
An immutable binding becomes a candidate only when its creation time is strictly older than Grace and no root names it. Reclamation requires another successful mark at least Grace after its first observation with the same binding bytes. A rooted candidate is forgotten; failed marks discard coverage. A bare Collector restart discards coverage; ExecuteGC restores only a completed, configuration-matching filer mark. Grace must exceed the catalog operation deadline plus the measured mark duration. Backward clock movement refuses the pass.
Before physical deletion the binding receives a conditional `swb.gc.deleted=1` tombstone; after every resolved replica deletion succeeds it becomes `done`. Bindings are never removed or rebound. Failed/uncertain blob deletion returns an error and retains the fid for a conservative retry after fresh marks. The SeaweedFS adapter deletes the exact fid, accepts only HTTP 200/202/204/404 (SeaweedFS returns 202 after synchronous replicated deletion), and propagates transport/other HTTP failures. Authenticated deployments must supply a BlobDeleter with their write authorization; this patch does not add an auth provisioning path.
Unbound needles (upload succeeded but key binding never persisted) are RETAINED. The existing interfaces cannot enumerate/count them, so `UnknownUnbound=true` reports that limitation instead of a fabricated zero. No sweep is attempted.
## Scope and follow-ups
This first Draft implements the GC core and the real Capture/intent/HEAD caller regression. Retention (newest N plus logarithmic age buckets), workspace tombstoning, automatic scheduling remain follow-up W5 slices. The CLI and blockmaster epoch binding are available below. Unnamed deleting snapshot attempts root their keys until their deleting timestamp is older than grace; normal two-mark/upload-age admission still applies afterward. The immutable attempt record is never removed, even after reclaim. Active unnamed attempts remain roots. This is not complete workspace lifecycle acceptance.
## Lock order
The new Collector mutex serializes its own passes and candidate state; it never enters WAL, publication, shard or chunk-layer locks. Remote calls execute only while holding that collector-local mutex. Producer Capture already uploads after releasing its capture/publication barrier, so GC adds no edge to the storage lock graph. The epoch-reader and BlobDeleter must not re-enter this Collector. Multiple collectors may repeat idempotent physical deletes, but each must independently satisfy the two-mark grace rule.
## Evidence boundary
The assertion RED is an initial GC candidate that already implemented HEAD/snapshot tracing and two marks but omitted intent roots; the base has no GC API to test. It is NOT claimed as a GC bug reproduced on unmodified main. The same test holds the shipping Capture before CAS after real immutable uploads, runs two GC marks, resumes CAS, and reads exact bytes through ChunkRemote. Filer/needle services are deterministic adapters; no SeaweedFS process, hardware, lab or cloud acceptance is claimed.
## Copy-sweep integration
The follow-up branch merges W2 #119 b51713e with #117 5f010ca (the #121 parent). The sole capture conflict keeps #117's pre-upload intent list and cleanup semantics, and retains #119's typed `ErrChunkRemoteUnavailable` wrapper on upload failure. No capture intent is swept through the copy protocol. Name reuse creates a new snapshot attempt; permanent old attempt tombstones continue refusing late old inserts. Volume IDs cannot be reused.
The first copy-sweep RED uses the prior retain-forever behavior (a no-op SweepCopies seam), not a claimed bug on an unmodified main. The same real Catalog caller turns GREEN with permanent-target claims. Tests cover a pending snapshot across name reuse, a fork with VOLUME already present and HEAD held, published unnamed/deleting attempts, unknown claim recovery, and the retained stalled-Capture case. Deterministic remote services only; no lab/cloud actions.
## Operational CLI
Use the existing `sw-block ops chunk` surface rather than a background job: the
operator explicitly chooses the catalog namespace and when deletion is allowed.
Before applied GC, configure durable filer writes for the namespace using the
SeaweedFS shell, e.g. `fs.configure -locationPrefix=/swblock/ -collection=swblock -fsync -apply`,
and retain that configuration. The catalog path must fall under the configured
prefix. A different namespace needs its matching rule. The default is a read-only JSON preview:
```sh
sw-block ops chunk gc --chunk-filer 127.0.0.1:18888 \
--chunk-path /swblock/chunks --master 127.0.0.1:9090
# First applied mark records candidates; it does not reclaim newly seen keys.
sw-block ops chunk gc --chunk-filer 127.0.0.1:18888 \
--chunk-path /swblock/chunks --master 127.0.0.1:9090 --apply
# Repeat --apply after at least --grace (default 1h).
```
`--master` is the blockmaster gRPC endpoint, not the SeaweedFS master. The
`EvidenceService.QueryVolumeStatus` reply must identify the requested volume and
an assigned, nonzero epoch. Unknown authority retains capture intents. Expiry
still requires both the higher issued epoch and a higher actual remote HEAD,
plus `--intent-ttl` (default 1h). No lease-expiry inference is used.
The JSON `roots` array identifies HEADs, snapshots, snapshot attempts, capture
intents and `retained_copy_intent` roots with their keys. `would_delete` lists
mature unrooted key/fid pairs; `would_expire_intents` names eligible capture
intents. `Reclaimed`, `ExpiredIntents`, `settled_copy_intents` and `mark_saved`
describe actual effects. A preview does not settle copy intents, expire capture
intents, write marks or delete blobs. Consequently a copy that an apply can
settle may still appear as a retained root in the preceding preview.
Independent apply calls persist two-mark coverage in `_GC_MARK` under the
catalog namespace. A conditional in-progress mark invalidates old coverage
before effects; only a completed pass saves fresh coverage. A failed scan after an acknowledged in-progress write does not save completed
coverage. Configuration changes cannot reuse prior coverage. A mark write can
commit and then lose its response: an error does **not** prove that remote
coverage is absent or unchanged. Do not edit or copy this state between namespaces. All filer/master/
blob calls share `--timeout` (default 1m). Grace must exceed the catalog operation
deadline (5m) plus the measured mark duration. Increase timeout only if the pass
still fits that safety margin. Permanent attempt, HEAD and key tombstones are
never removed by this command. Pre-binding needle enumeration remains unknown.
The CLI adds no storage lock edge: the collector retains its local mutex and
uses the existing remote APIs. The persisted mark uses filer conditional writes,
not a new WAL/publication/shard lock. Concurrent apply calls can conflict and
report an error. Callers must keep the failure status, but must not infer that
all effects were rolled back or that no completed mark exists remotely.
Errors after GC execution begins return `{code,message,retryable,gc}` with the
known partial counters/root report preserved in `gc`. `mark_saved=true` means
the completed-write response was acknowledged, not merely attempted.
`mark_outcome` describes this invocation: `not_attempted`, `in_progress`
(acknowledged), `complete` (acknowledged), or `unknown` (write response lost or
failed; remote outcome not established). `unknown_outcomes` names incomplete
stages (`in_progress_mark_write`, `copy_intent_settlement`, `reclamation`, or
`completed_mark_write`). A stage may have partially taken effect even though
its acknowledged counters are lower; for example a blob delete may succeed
then lose its reply. Do not interpret the counters as an upper bound or assume
that retries start from a pristine store. The next invocation reads the actual
conditional mark and authoritative roots as usual.
The opt-in end-to-end test invokes the actual CLI entrypoint against a real
blockmaster runtime and real SeaweedFS master/volume/filer processes:
```sh
CHUNKSTORE_WEED=/path/to/weed go test -tags chunkstore_integration \
./cmd/sw-block -run '^TestIntegration_OpsChunkGC_RealMasterAndStore$' \
-v -count=1 -timeout=180s
```
This test requires the binary and fails rather than skips when it is absent. It configures and reads back the filer rule `fs.configure -locationPrefix=/swblock/ -collection=swblock -fsync -apply` before creating catalog data.
It advances only the GC clock to exercise grace admission deterministically;
network services, conditional metadata writes, authority RPC and blob deletion
are real. It is not an elapsed-time soak or a lab qualification.
## Single filer
Every command that writes chunk metadata (`snapshot-delete`, `fork`, `retain`
without `--dry-run`, `volume-delete`, `gc --apply`) and `verify` make the same
start check as blockvolume before they read or write anything: it asks the
filer for its masters and filer group, and refuses unless a master lists
exactly one filer in that group and it is the `--chunk-filer` given. `verify`
writes nothing, but against a split filer view it would report false
findings. The other read-only commands and modes do not run the check. A
filer that is not the only one of its group exits 2 with code `bad_request`;
a check that cannot finish (a filer or master that does not answer) exits 1
with code `remote_unavailable`, retryable. The check runs within the command's
`--timeout`. The masters the filer reports must be reachable from where the
command runs.
## Verify
`sw-block ops chunk verify` compares one volume's remote image with what its
HEAD, and optionally its snapshots, say. It is read-only: it writes no intent,
mark, tombstone or binding, and deletes nothing.
```sh
sw-block ops chunk verify --volume v1 --chunk-filer 127.0.0.1:18888 \
[--chunk-path /swblock/chunks] [--snapshot s1 | --all-snapshots] \
[--depth meta|bindings|data] [--concurrency 2] [--bytes-per-sec 33554432] \
[--timeout 10m]
```
HEAD is always checked. `--snapshot` adds one named snapshot; `--all-snapshots`
adds every published snapshot that is not being deleted. Each depth includes the
one before it:
- `meta`: the HEAD root decodes and is self-consistent; its chunk size and chunk
indices fit the VOLUME geometry; every segment a checked root names is
readable, matches its SHA-256 and decodes strictly; the same for each checked
snapshot's embedded HEAD; a snapshot's document names the volume and the
snapshot it was found under (else `ROOT_INVALID`; the snapshot is still
checked under the name it was found under); references to one
chunk with different SHA-256s disagree (`CONTENT_MISMATCH`); for a fork, its
fork record's digest matches an attempt of the parent snapshot at the
recorded generation.
- `bindings` (the default): also, every chunk key a checked root references has
a binding in its owner's `keys/` (a fork's `@owner/key` resolves to the owner
volume), of the right kind, with a fid, without filer chunks, and not
tombstoned by GC. Each owner's `keys/` is listed once. GC's mark does not make
this check: it never looks up the bindings of the keys it roots.
- `data`: also, every distinct chunk (owner and key, across all checked roots)
is read once, and its SHA-256 must equal the reference and its length the
chunk size, the rule a guest read applies. `--depth data` requires an explicit
`--timeout`. Reads are bounded by `--concurrency` and paced by
`--bytes-per-sec` (0 leaves them unpaced).
Old capture intents below HEAD's epoch that name no key HEAD references are
reported as `INTENT_STALE`. This is a hint only: whether GC may expire an intent
remains GC's decision, with blockmaster authority.
The output is one JSON object: the HEAD generations and snapshots covered,
segments and chunks checked, distinct chunks and bytes read, the two counters
below, findings by class, and the findings, one per line. Each finding
names the volume, the root (`HEAD gen N`, `snapshot name/attempt`, an intent or
the VOLUME fork record), the chunk index or segment, the owner, key and fid, a
class and a detail. Classes: `ROOT_INVALID`, `GEOMETRY`, `SEGMENT_UNREADABLE`,
`BINDING_MISSING`, `BINDING_TOMBSTONED`, `NEEDLE_MISSING`, `CONTENT_MISMATCH`,
`SIZE_MISMATCH`, `FORK_RECORD_MISMATCH`, `INTENT_STALE`, `READ_ERROR`.
`NEEDLE_MISSING` means the blob store answered that the needle does not exist
(for SeaweedFS: HTTP 404 from every location of a fresh volume lookup; when the
cached locations all answer 404, the volume is looked up again, since it may
have moved). Any other read failure, such as a
timeout, a refused or reset connection, or another HTTP status, is retried twice
with a short backoff. If it still fails, the chunk or segment is reported as
`READ_ERROR`, with the error in the detail. `READ_ERROR` is not evidence of
damage: it means that object was **not verified**. Re-run verify, after fixing
the store's reachability if needed. The summary counts these objects separately
in `chunksNotRead`, and `readRetries` counts the retried reads. The rule below
applies to `READ_ERROR` as to any other bad outcome.
### Running beside a live owner and beside GC
Segments and chunks are immutable and written before the root that names them,
so a root read once and the segments it names are a consistent view. But nothing
registers a reader with GC: a chunk that leaves a root can be collected once
GC's grace has passed, and a long pass can outlive that. So verify checks each
chunk once, records its outcome, and computes the findings only at the end, from
those outcomes and the roots at its final read:
- HEAD is read again at least every 2 minutes during a long pass (a newer
generation replaces the view; only segments whose key changed are read again;
chunks it names that the pass has not seen are added and checked).
- When every chunk is checked, verify reads HEAD and each checked snapshot's state
once more. If that read names a chunk not seen, verify checks it and reads
again, at most 3 times; the read that names nothing new is the final read, and
no read follows it. Only a HEAD that decodes can be part of it: if that read
finds no HEAD, or one that does not decode, the final view has no HEAD root and
the pass is incomplete.
- Chunks and segments alike are read once per key, whatever reference names them,
and keep that one outcome: the content (a segment keeps its bytes), or binding
missing or tombstoned, needle missing, or a read error.
- At the end, each reference is judged against that one outcome, the same way
whatever the order the pass met them in: a bad outcome stays that outcome; a
reference with another hash is a `CONTENT_MISMATCH`; a chunk that matches its
reference but is not a chunk long is a `SIZE_MISMATCH`; a segment that does not
decode under that reference's own fields is `SEGMENT_UNREADABLE`; else it is
sound (and a sound segment reference gives that root its chunks).
- For each object and class a reference of the final read has, there is one
finding, under the first root having such a reference (HEAD, then the snapshots
still active, in order), at its first such index.
- A chunk or segment that had a problem under any reference the pass saw (or a bad
outcome) but has no finding, because no reference of the final read has one, is
counted once: in `rootDeletedDuringVerify` when a checked snapshot that was
deleted during the pass carried a problem reference, otherwise in
`supersededDuringVerify`. This includes an object still named, but only by sound
references. Deleted snapshots are listed in `snapshotsDeletedDuringVerify` as not
fully covered. The counters do not make a pass unclean.
- A key that an earlier HEAD read named, a later one did not, and the final HEAD
names again is a `ROOT_INVALID` finding ("HEAD names a key it had dropped"),
whatever its chunk's state: a key that left every root may have been collected,
and must not come back.
A finding describes each chunk as it was when checked, for the roots at the final
read; a chunk damaged after its check is the next pass's finding.
A pass that cannot finish is **incomplete**, never clean: `complete` is false and
`incomplete` gives the reason: `deadline`, `cancelled`, `error` (a filer or blob
store failure, a refused request, or a final read that returned an older HEAD),
`closing_rounds_exhausted` (each of the 3 final reads named new chunks: the volume
is too busy; re-run), `head_absent` (the final read found no HEAD) or
`head_invalid` (the final read's HEAD does not decode; also a `ROOT_INVALID`
finding). Its findings are those computed from the chunks it did check, for the
roots of its last view (none for HEAD in the last two cases).
### What verify cannot check
- Orphan needles: a needle uploaded whose binding was never written cannot be
enumerated.
- Which block inside a chunk is bad: there is one SHA-256 per chunk.
- A data chunk's size without reading it: bindings and references store no size.
- The HEAD root against an independent value: no checksum of the root is stored.
- Whether the image equals the volume's content at its remote LSN: only the
holder's local volume could say.
- Past HEAD generations, forced-move lost ranges (kept outside the filer), and
any verification history (nothing records it).
- Each replica of a needle: a read stops at the first replica that answers.
### Exit codes
- `0`: the pass completed with no finding.
- `3`: the pass completed with findings. This includes `READ_ERROR`: the pass
did not verify everything.
- `1`: the pass could not complete (the deadline passed, the filer failed, HEAD
kept naming new chunks, HEAD was gone or did not decode at the final read, or
the volume or snapshot does not exist). The error body
`{code,message,retryable}` is printed with the partial result, and its
`incomplete` reason, under `verify`. A single-filer start check that cannot
finish also exits 1 (`remote_unavailable`), before the pass, with no result.
- `2`: usage error, or the filer is not the only one of its group (`bad_request`,
before the pass, with no result).
@@ -24,6 +24,8 @@ import (
// pins it. "GAP" marks a reader that takes an absent HEAD for an empty
// one; a change that treats an absent HEAD as unknown flips those probes.
var headReaders = map[string]string{
"core/frontend/chunkstore/layout_verify.go verifyHead -> LookupEntry": "absent or unknown generation makes verify incomplete and suppresses MISSING/ORPHAN (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
"core/frontend/chunkstore/layout_verify.go verifyHead -> DecodeLayoutHeadEntry": "invalid inline envelope supplies no generation and cannot confirm findings (TestVerifyLayoutRequiresStableHeadForMissingAndOrphans)",
"cmd/blockvolume/chunk_maintenance.go newChunkMaintenance -> ReadHead": "diagnostic absent HEAD reports headGen0 and headGenError; it neither authorizes nor changes cleaning (TestMaintenanceStatusRealPassAndTimeout/head-absent)",
"core/frontend/chunkstore/layout_remote.go ProbeSnapshots -> ReadHead": "absent or failed reads do not infer snapshot deletion; open local activity skips the read (TestMaintenanceNoticesSnapshotDeleteWithoutNotification, TestLayoutSnapshotProbeSkipsOpenActivityWithoutReadingHEAD)",
"core/frontend/durable/provider_seal_replay.go readLayoutSeal -> ReadHead": "absent, unreadable and foreign layout proof refuse without cached success (TestLayoutPlainDetachReplayAfterRestartNeedsNoLegacyFactory)",
@@ -61,11 +63,11 @@ var headReaders = map[string]string{
"cmd/sw-block/chunk_b.go chunkShowContext -> ReadHead": "found=false: prints a null head, including via the chunkShow wrapper (probe TestOpsChunk_AbsentVolume)",
"cmd/sw-block/chunk_b.go chunkSnapshots -> ReadHead": "refuses volume_not_found (probe TestOpsChunk_AbsentVolume)",
"core/frontend/durable/provider_chunk.go GetHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
"core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
"core/frontend/durable/provider_chunk.go GetHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
"core/storage/chunk_head_belt.go confirmChunkHead -> GetHead": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)",
"core/storage/chunk_head_belt.go confirmChunkHead -> GetHeadRoot": "ErrHeadAbsent from the layout remote: not confirmed (probe LayoutRemote)",
"core/storage/chunk_head_belt.go readChunkHead -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
"core/storage/chunk_head_belt.go readChunkHeadRoot -> GetHeadRoot": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
"core/storage/chunk_layer.go attachChunkLayerImpl -> GetHead": "ErrHeadAbsent from the layout remote (probe LayoutRemote)",
}
@@ -217,6 +219,9 @@ func TestHeadReaders_AbsentHeadProbes(t *testing.T) {
if _, err := r.GetHead(ctx); !errors.Is(err, layout.ErrHeadAbsent) {
t.Fatalf("engine HEAD read of an absent HEAD: %v; want ErrHeadAbsent", err)
}
if _, err := r.GetHeadRoot(ctx); !errors.Is(err, layout.ErrHeadAbsent) {
t.Fatalf("engine HEAD identity read of an absent HEAD: %v; want ErrHeadAbsent", err)
}
if _, err := r.CASHead(ctx, storage.ChunkHeadVersion{Gen: 0, Epoch: 1}, storage.ChunkHead{Epoch: 1}); !errors.Is(err, layout.ErrHeadAbsent) || len(f.written) != 0 {
t.Fatalf("engine commit over an absent HEAD: %v (%d writes); want ErrHeadAbsent and none", err, len(f.written))
}
@@ -179,12 +179,16 @@ func TestHeadGenerationCacheExceptionIsSingular(t *testing.T) {
func TestHeadGenerationComparedOnlyByConditionalUpdate(t *testing.T) {
root := filepath.Clean("../../../..")
exceptions := 0
// These engine comparisons use the adapter's synthetic image-view token,
// Verify compares raw generations only to suppress unstable diagnostic findings;
// it grants no write authority. The engine comparisons below use the adapter's synthetic image-view token,
// not raw filer HEAD generation. Pin both syntax and count: a new or removed
// site forces review. No no-op-cut authority comparison is allowed here.
allowed := map[string]int{
"core/frontend/chunkstore/layout_verify.go VerifyLayout head.Gen != heads[p].Gen": 1, // read-only observation window; TestVerifyLayoutRequiresStableHeadForMissingAndOrphans
"core/storage/chunk_head_belt.go confirmChunkHead got.Gen != want.Gen": 1, // publication confirmation
"core/storage/chunk_layer.go captureLocked sc.headGen == l.head.Gen": 1, // staged image cache
"core/storage/chunk_layer.go noopCutHead root.Gen == baseHead.Gen": 1, // no-op cut keeps its base while HEAD's image token is unchanged
"core/storage/chunk_layer.go captureLocked cur.Gen == expected.Gen": 1, // unresolved CAS base
"core/storage/chunk_layer.go SettleDetach cur.Gen == base.Gen": 2, // pending and cancelled CAS base
"core/storage/chunk_layer.go resolvePending cur.Gen == base.Gen": 2, // pending and cancelled CAS base
@@ -0,0 +1,187 @@
package chunkstore
import (
"context"
"errors"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// afterCASRemote is the holder's layout remote, marking when a HEAD write
// has returned, so a test can count what the layer reads after it.
type afterCASRemote struct {
*LayoutRemote
after atomic.Bool
onAfter func()
}
func (r *afterCASRemote) CASHead(ctx context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) (uint64, error) {
gen, err := r.LayoutRemote.CASHead(ctx, e, n)
r.after.Store(true)
if r.onAfter != nil {
r.onAfter()
}
return gen, err
}
// manifestReads attaches a chunk layer over the holder's layout remote, one
// block written in every chunk, and counts every lookup of a root or a
// segment made while counting is on.
func manifestReads(t *testing.T) (*storage.WALStore, *afterCASRemote, storage.ChunkLayer, *atomic.Bool, *atomic.Int64) {
t.Helper()
lh := newLayoutHost(t)
s, err := storage.CreateWALStoreWithOptions(filepath.Join(lh.dir, "a"), lrBlocks, 4096, storage.WALStoreOptions{ChunkBlocks: lrChunkBlocks})
if err != nil {
t.Fatal(err)
}
if _, err := s.Recover(); err != nil {
t.Fatal(err)
}
r, err := NewLayoutRemote(lh.cat, lh.v, lh.me)
if err != nil {
t.Fatal(err)
}
w := &afterCASRemote{LayoutRemote: r}
l, err := storage.AttachChunkLayer(s, w, storage.ChunkLayerConfig{ChunkBlocks: lrChunkBlocks, Epoch: lh.me.Epoch, Holder: lh.me.Holder, FreshFromHead: true})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = l.Close(); _ = s.Close() })
blocks := map[uint32][]byte{}
for c := uint32(0); c < lrBlocks/lrChunkBlocks; c++ {
blocks[c*lrChunkBlocks] = block(byte(c + 1))
}
writeSync(t, s, blocks)
var counting atomic.Bool
var reads atomic.Int64
lh.ff.afterLookup = func(p string) {
if counting.Load() && (strings.Contains(p, "/root/") || strings.Contains(p, "/seg/")) {
reads.Add(1)
}
}
return s, w, l, &counting, &reads
}
// The confirmation after a HEAD write compares HEAD's generation, epoch and
// holder only, inside the HEAD step's fixed 2 s limit, so it reads HEAD and
// nothing else: no root and no segment, whose number grows with the volume.
func TestTheConfirmationAfterAHeadWriteReadsNoManifest(t *testing.T) {
_, w, l, counting, reads := manifestReads(t)
w.onAfter = func() { counting.Store(true) } // count what is read once the HEAD write returns
if _, err := l.Cut(context.Background()); err != nil {
t.Fatal(err)
}
if !w.after.Load() {
t.Fatal("setup: the cut wrote no HEAD")
}
if n := reads.Load(); n != 0 {
t.Fatalf("the confirmation after the HEAD write read %d roots or segments; want 0 (HEAD only)", n)
}
}
// A cut with nothing new (a no-op cut, run each interval on an idle volume)
// still reads HEAD to observe authority. While HEAD is the image the layer
// already holds, it reads HEAD only and keeps its chunk list: no root and no
// segment.
func TestANoOpCutReadsNoManifestWhileHeadIsUnchanged(t *testing.T) {
_, _, l, counting, reads := manifestReads(t)
if _, err := l.Cut(context.Background()); err != nil { // publish the written chunks
t.Fatal(err)
}
counting.Store(true)
res, err := l.Cut(context.Background())
if err != nil {
t.Fatal(err)
}
if !res.Noop {
t.Fatalf("setup: the second cut was not a no-op: %+v", res)
}
if n := reads.Load(); n != 0 {
t.Fatalf("a no-op cut over an unchanged HEAD read %d roots or segments; want 0", n)
}
if len(res.Head.Chunks) != lrBlocks/lrChunkBlocks {
t.Fatalf("the no-op cut's HEAD names %d chunks; want the %d it already held", len(res.Head.Chunks), lrBlocks/lrChunkBlocks)
}
}
// A no-op cut over a HEAD another holder has claimed since the last cut reads
// HEAD's identity through the root reader, finds it changed, and fences: it
// never keeps its base over a changed HEAD.
func TestANoOpCutOverAForeignClaimFences(t *testing.T) {
ctx := context.Background()
_, w, l, _, _ := manifestReads(t)
if _, err := l.Cut(ctx); err != nil { // publish the written chunks
t.Fatal(err)
}
if _, err := layout.RunClaim(ctx, w.st, okClaimLease{}, layout.HolderID{Epoch: w.me.Epoch + 1, Holder: "foreign", ClaimID: "foreign-claim"}); err != nil {
t.Fatal(err)
}
if _, err := l.Cut(ctx); !errors.Is(err, storage.ErrChunkLayerFenced) {
t.Fatalf("a no-op cut over a foreign claim: %v; want ErrChunkLayerFenced", err)
}
if !l.Fenced() {
t.Fatal("the layer is not fenced after a no-op cut over a foreign claim")
}
}
// The generation token can move while HEAD keeps this holder's own identity
// and image: a session ended without its commit (a stop's abort), seen by a
// HEAD read before the abandonment notice, forces the view. A no-op cut then reads the whole HEAD and completes on the newer
// generation; keeping the base because epoch and holder still match would
// leave the layer on a generation HEAD no longer has.
func TestANoOpCutAfterTheTokenMovedUnderTheHoldersOwnIdentityReadsTheWholeHead(t *testing.T) {
ctx := context.Background()
lh := newLayoutHost(t)
s, l, r := lh.attach("a", true, true)
defer s.Close()
writeSync(t, s, map[uint32][]byte{2: block(2)})
first, err := l.Cut(ctx)
if err != nil {
t.Fatal(err)
}
session, err := r.Begin(ctx)
if err != nil {
t.Fatal(err)
}
st, err := lh.cat.Store(lh.v)
if err != nil {
t.Fatal(err)
}
if _, err := layout.RunAbort(ctx, st, lh.me, session, layout.CauseSessionRollback); err != nil {
t.Fatal(err)
}
// An adapter HEAD read in progress observes the ended session before the
// abandonment notice and forces the view: the token moves, identity and
// image stay.
if _, err := r.GetHead(ctx); err != nil {
t.Fatal(err)
}
r.Abort()
var reads atomic.Int64
lh.ff.afterLookup = func(p string) {
if strings.Contains(p, "/root/") || strings.Contains(p, "/seg/") {
reads.Add(1)
}
}
second, err := l.Cut(ctx)
if err != nil {
t.Fatalf("no-op cut after the token moved: %v", err)
}
if !second.Noop {
t.Fatalf("setup: the cut after the abort was not a no-op: %+v", second)
}
if second.Head.Gen == first.Head.Gen {
t.Fatalf("the no-op cut kept generation %d; HEAD's token moved, so it must complete on the newer one", first.Head.Gen)
}
if reads.Load() == 0 {
t.Fatal("the no-op cut read no root or segment although HEAD's token moved; want the whole HEAD")
}
if e, h := second.Head.Epoch, second.Head.Holder; e != first.Head.Epoch || h != first.Head.Holder {
t.Fatalf("setup: the holder's identity changed: %d/%s, was %d/%s", e, h, first.Head.Epoch, first.Head.Holder)
}
}
@@ -117,8 +117,11 @@ func (l *LayoutRemote) ProbeSnapshots(ctx context.Context) (map[string]struct{},
}
var (
_ storage.ChunkRemote = (*LayoutRemote)(nil)
_ storage.ChunkKeyer = (*LayoutRemote)(nil)
_ storage.ChunkRemote = (*LayoutRemote)(nil)
_ storage.ChunkKeyer = (*LayoutRemote)(nil)
_ storage.ChunkCommitChecker = (*LayoutRemote)(nil)
_ storage.ChunkHeadStepBounder = (*LayoutRemote)(nil)
_ storage.ChunkHeadRootReader = (*LayoutRemote)(nil)
)
// NewLayoutRemote returns the remote of volume v for the holder me (the
@@ -273,12 +276,17 @@ func (l *LayoutRemote) PutPaced(ctx context.Context, key string, data []byte, be
return fmt.Errorf("%w: %q is not this volume's name for these bytes", storage.ErrChunkKeyInvalid, key)
}
l.mu.Lock()
defer l.mu.Unlock()
l.takeAbandonLocked()
if err := l.openSessionLocked(ctx); err != nil {
l.mu.Unlock()
return err
}
return layoutRemoteErr(layout.EnsureObjectPaced(ctx, l.st, ref.Chunk.Path(), data, l.session, beforeSend))
session := l.session
l.mu.Unlock()
// Pacing and payload I/O do not serialize the upload workers or HEAD
// reads. Keep this upload's session even if it ends during the send:
// commit checks reject objects belonging to that ended session.
return layoutRemoteErr(layout.EnsureObjectPaced(ctx, l.st, ref.Chunk.Path(), data, session, beforeSend))
}
// Get reads a chunk by its key through the volume's reader: the owner's
@@ -299,26 +307,9 @@ func (l *LayoutRemote) Get(ctx context.Context, key string) ([]byte, error) {
func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
l.mu.Lock()
defer l.mu.Unlock()
l.takeAbandonLocked()
h, err := l.rollBackLocked(ctx)
if err != nil {
return storage.ChunkHead{}, err
}
if h.State == layout.StateDeleting || h.State == layout.StateDeleted {
return storage.ChunkHead{}, storage.ErrChunkHeadDeleted
}
// Another claim at this holder's own epoch is another owner of HEAD: the
// head the engine sees carries no claim id, so it must not read as its own.
if h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID != l.me.ClaimID {
return storage.ChunkHead{}, fmt.Errorf("%w: HEAD is held by %s at epoch %d (claim %q)", storage.ErrChunkLayerFenced, h.Holder, h.Epoch, h.ClaimID)
}
out := storage.ChunkHead{Gen: l.visible, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Chunks: map[uint64]storage.ChunkRef{}, State: "active"}
if h.State == layout.StateDetached {
out.State = "detached"
out.DetachedBy = &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen}
}
if h.Current == nil {
return out, nil
h, out, err := l.headIdentityLocked(ctx)
if err != nil || h.Current == nil {
return out, err
}
m, err := l.manifest(ctx, *h.Current)
if err != nil {
@@ -342,6 +333,45 @@ func (l *LayoutRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
return out, nil
}
// GetHeadRoot is GetHead without the manifest (storage.ChunkHeadRootReader):
// the same view of HEAD, its generation token, epoch, holder, position and
// state, after the same rollback and refusals, with no chunk listed. It reads
// HEAD only, never a root or a segment, so it does not grow with the volume.
// The token changes whenever HEAD's root does, so a caller that kept the
// chunks of a HEAD with the same token still has them.
func (l *LayoutRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
l.mu.Lock()
defer l.mu.Unlock()
_, out, err := l.headIdentityLocked(ctx)
out.Chunks = nil
return out, err
}
// headIdentityLocked reads HEAD as the engine's view, without its manifest:
// the rollback of a session this process does not hold, the deleted and
// other-claim refusals, and HEAD's identity (Chunks empty).
func (l *LayoutRemote) headIdentityLocked(ctx context.Context) (layout.Head, storage.ChunkHead, error) {
l.takeAbandonLocked()
h, err := l.rollBackLocked(ctx)
if err != nil {
return layout.Head{}, storage.ChunkHead{}, err
}
if h.State == layout.StateDeleting || h.State == layout.StateDeleted {
return layout.Head{}, storage.ChunkHead{}, storage.ErrChunkHeadDeleted
}
// Another claim at this holder's own epoch is another owner of HEAD: the
// head the engine sees carries no claim id, so it must not read as its own.
if h.Epoch == l.me.Epoch && h.Holder == l.me.Holder && h.ClaimID != l.me.ClaimID {
return layout.Head{}, storage.ChunkHead{}, fmt.Errorf("%w: HEAD is held by %s at epoch %d (claim %q)", storage.ErrChunkLayerFenced, h.Holder, h.Epoch, h.ClaimID)
}
out := storage.ChunkHead{Gen: l.visible, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.Position, Chunks: map[uint64]storage.ChunkRef{}, State: "active"}
if h.State == layout.StateDetached {
out.State = "detached"
out.DetachedBy = &storage.ChunkDetachedBy{Holder: h.Holder, Epoch: h.Epoch, Gen: h.Gen}
}
return h, out, nil
}
// manifest is the chunk map root names. Within an attach (ctx carries
// storage.AttachFetch) it is read fetch by fetch: the root and each segment
// under their own bound, each completed segment reported as progress, and
@@ -0,0 +1,221 @@
package chunkstore
import (
"context"
"errors"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type heldUploadStore struct {
sessionStore
entered chan string
release <-chan struct{}
}
func (s *heldUploadStore) Create(ctx context.Context, rel string, data []byte, session string) error {
select {
case <-s.release:
return s.sessionStore.Create(ctx, rel, data, session)
default:
}
s.entered <- session
select {
case <-s.release:
case <-ctx.Done():
return ctx.Err()
}
return s.sessionStore.Create(ctx, rel, data, session)
}
func TestLayoutRemoteUploadsOverlapWithoutBlockingHead(t *testing.T) {
for _, phase := range []string{"pacing", "upload"} {
t.Run(phase, func(t *testing.T) {
ctx := context.Background()
lh := newLayoutHost(t)
r, err := NewLayoutRemote(lh.cat, lh.v, lh.me)
if err != nil {
t.Fatal(err)
}
release := make(chan struct{})
entered := make(chan string, 4)
if phase == "upload" {
r.st = &heldUploadStore{sessionStore: r.st, entered: entered, release: release}
}
var wg sync.WaitGroup
results := make(chan error, 4)
var releaseOnce sync.Once
finish := func() { releaseOnce.Do(func() { close(release) }); wg.Wait() }
defer finish()
for i := 0; i < 4; i++ {
data := block(byte(i + 1))
key := r.ChunkKey(uint64(i), layout.Sum(data))
wg.Add(1)
go func() {
defer wg.Done()
results <- r.PutPaced(ctx, key, data, func(ctx context.Context, _ int) error {
if phase != "pacing" {
return nil
}
entered <- "pacing"
select {
case <-release:
return nil
case <-ctx.Done():
return ctx.Err()
}
})
}()
}
timer := time.NewTimer(time.Second)
defer timer.Stop()
for i := 0; i < 4; i++ {
select {
case <-entered:
case <-timer.C:
t.Fatalf("only %d of 4 uploads entered %s while held", i, phase)
}
}
head := make(chan error, 1)
wg.Add(1)
go func() { defer wg.Done(); _, err := r.GetHead(ctx); head <- err }()
select {
case err := <-head:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("HEAD read waited behind held uploads")
}
finish()
for i := 0; i < 4; i++ {
if err := <-results; err != nil {
t.Fatal(err)
}
}
})
}
}
func TestLayoutRemoteHeadReadDoesNotWaitForUpload(t *testing.T) {
ctx := context.Background()
lh := newLayoutHost(t)
r, err := NewLayoutRemote(lh.cat, lh.v, lh.me)
if err != nil {
t.Fatal(err)
}
release := make(chan struct{})
entered := make(chan string, 1)
r.st = &heldUploadStore{sessionStore: r.st, entered: entered, release: release}
var wg sync.WaitGroup
done := make(chan error, 1)
wg.Add(1)
go func() { defer wg.Done(); data := block(1); done <- r.Put(ctx, r.ChunkKey(0, layout.Sum(data)), data) }()
var releaseOnce sync.Once
finish := func() { releaseOnce.Do(func() { close(release) }); wg.Wait() }
defer finish()
select {
case <-entered:
case err := <-done:
t.Fatalf("upload returned before Create: %v", err)
case <-time.After(time.Second):
t.Fatal("upload did not enter Create")
}
read := make(chan error, 1)
wg.Add(1)
go func() { defer wg.Done(); _, err := r.GetHead(ctx); read <- err }()
select {
case err := <-read:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("HEAD read waited behind upload")
}
finish()
if err := <-done; err != nil {
t.Fatal(err)
}
}
func TestLayoutRemoteUploadFinishedAfterSessionEndCannotCommit(t *testing.T) {
ctx := context.Background()
lh := newLayoutHost(t)
r, err := NewLayoutRemote(lh.cat, lh.v, lh.me)
if err != nil {
t.Fatal(err)
}
before, err := r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
release := make(chan struct{})
entered := make(chan string, 1)
r.st = &heldUploadStore{sessionStore: r.st, entered: entered, release: release}
data := block(7)
key := r.ChunkKey(0, layout.Sum(data))
done := make(chan error, 1)
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); done <- r.Put(ctx, key, data) }()
defer func() {
if release != nil {
close(release)
}
wg.Wait()
}()
var oldSession string
select {
case oldSession = <-entered:
case err := <-done:
t.Fatalf("upload returned before Create: %v", err)
case <-time.After(time.Second):
t.Fatal("upload did not enter Create")
}
if outcome, err := r.AbortOpenSession(ctx); err != nil || outcome != SessionAborted {
t.Fatalf("abort: %s %v", outcome, err)
}
nextSession := make(chan string, 1)
wg.Add(1)
go func() {
defer wg.Done()
s, err := r.Begin(ctx)
if err != nil {
nextSession <- ""
return
}
nextSession <- s
}()
select {
case session := <-nextSession:
if session == "" || session == oldSession {
t.Fatalf("new session = %q, old = %q", session, oldSession)
}
case <-time.After(time.Second):
t.Fatal("new session waited behind ended upload")
}
// Use the new session's view: the commit must reject the object's
// session, rather than merely reject an old HEAD version.
before, err = r.GetHead(ctx)
if err != nil {
t.Fatal(err)
}
close(release)
release = nil
err = <-done
if err != nil {
t.Fatal(err)
}
next := storage.ChunkHead{Epoch: lh.me.Epoch, RemoteLSN: 1, Chunks: map[uint64]storage.ChunkRef{0: {Key: key, SHA256: layout.Sum(data), Encoding: "full"}}}
_, err = r.CASHead(ctx, storage.ChunkHeadVersion{Gen: before.Gen, Epoch: lh.me.Epoch}, next)
if !errors.Is(err, storage.ErrChunkHeadPrecondition) {
t.Fatalf("commit of ended upload: %v", err)
}
if h := lh.head(); h.Position != 0 || h.Current != nil {
t.Fatalf("refused commit published: %+v", h)
}
}
@@ -3,7 +3,9 @@ package chunkstore
import (
"context"
"errors"
"fmt"
"path"
"sort"
"strings"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
@@ -49,5 +51,75 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve
}
s := &LayoutStore{f: f, b: b, root: path.Join(base, vol)}
opts.List = s.List
return layout.Verify(ctx, base, vol, s.Fetch, opts)
// Keep the generation from the same lookup as the HEAD bytes walked by
// Verify. A later lookup must confirm every observed HEAD, including live
// dependent targets, before publishing absence/reachability findings.
heads := map[string]layout.Head{}
fetch := func(ctx context.Context, p string) ([]byte, bool, error) {
if path.Base(p) != layout.HeadName {
return s.Fetch(ctx, p)
}
b, head, found, err := s.verifyHead(ctx, p)
heads[p] = head
return b, found, err
}
res, err := layout.Verify(ctx, base, vol, fetch, opts)
if err != nil {
return res, err
}
why := ""
if len(heads) == 0 {
why = "HEAD generation unavailable"
}
paths := make([]string, 0, len(heads))
for p := range heads {
paths = append(paths, p)
}
sort.Strings(paths)
for _, p := range paths {
_, head, found, readErr := s.verifyHead(ctx, p)
if heads[p].Gen == 0 || !found || readErr != nil || head.Gen == 0 || head.Gen != heads[p].Gen || head.VolumeID != heads[p].VolumeID {
why = fmt.Sprintf("HEAD changed or generation unavailable: %s", p)
if readErr != nil {
why += ": " + readErr.Error()
}
break
}
}
if why != "" {
res.Complete = false
if res.Incomplete == "" {
res.Incomplete = why
}
res.OrphansChecked = false
kept := res.Findings[:0]
for _, f := range res.Findings {
if f.Class != layout.FindMissing && f.Class != layout.FindOrphan {
kept = append(kept, f)
}
}
res.Findings = kept
}
return res, nil
}
// verifyHead preserves inline bytes for the kernel's malformed/identity
// diagnostics; an invalid envelope has no usable generation for confirmation.
func (s *LayoutStore) verifyHead(ctx context.Context, p string) ([]byte, layout.Head, bool, error) {
e, err := s.f.LookupEntry(ctx, path.Dir(p), layout.HeadName)
if errors.Is(err, ErrNotFound) {
return nil, layout.Head{}, false, nil
}
if err != nil {
return nil, layout.Head{}, false, err
}
id, err := layout.ParseVolumeID(string(e.Extended[layoutVolume]))
if err != nil {
return e.Content, layout.Head{}, true, nil
}
h, err := DecodeLayoutHeadEntry(e, id)
if err != nil {
return e.Content, layout.Head{}, true, nil
}
return e.Content, h, true, nil
}
@@ -70,6 +70,7 @@ func verifyFixtureVolume(t *testing.T) (filerBlobs, layout.VolumeID) {
t.Fatal(err)
}
putFile(t, f, path.Join("/blocks", layout.VolumeDir("v", id))+"/"+layout.HeadName, hb)
f.entries[path.Join("/blocks", layout.VolumeDir("v", id), layout.HeadName)].Extended = map[string][]byte{layoutKind: []byte("head"), layoutVolume: []byte(id.String()), layoutGen: []byte("1")}
return filerBlobs{f, b}, id
}
@@ -144,7 +145,7 @@ func snapshotStore(fb filerBlobs) string {
fb.fakeFiler.mu.Lock()
var keys []string
for p, e := range fb.fakeFiler.entries {
raw, _ := proto.Marshal(e)
raw, _ := (proto.MarshalOptions{Deterministic: true}).Marshal(e)
keys = append(keys, fmt.Sprintf("%s=%x", p, sha256.Sum256(raw)))
}
fb.fakeFiler.mu.Unlock()
@@ -152,3 +153,66 @@ func snapshotStore(fb filerBlobs) string {
puts, _, stored := fb.fakeBlobs.counts()
return fmt.Sprintf("puts=%d stored=%d %s", puts, stored, strings.Join(keys, ","))
}
type verifyChangingHead struct {
filerBlobs
reads int
mode string
}
func (f *verifyChangingHead) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
e, err := f.filerBlobs.LookupEntry(ctx, dir, name)
if name != layout.HeadName || err != nil {
return e, err
}
f.reads++
e = proto.Clone(e).(*filerpb.Entry)
if f.mode == "initial-unknown" {
delete(e.Extended, layoutGen)
}
if f.reads >= 2 {
switch f.mode {
case "advance":
e.Extended[layoutGen] = []byte("2")
case "absent":
return nil, ErrNotFound
case "error":
return nil, fmt.Errorf("injected confirmation failure")
case "unknown":
delete(e.Extended, layoutGen)
}
}
return e, nil
}
func TestVerifyLayoutRequiresStableHeadForMissingAndOrphans(t *testing.T) {
for _, mode := range []string{"stable", "advance", "absent", "error", "unknown", "initial-unknown"} {
t.Run(mode, func(t *testing.T) {
fb, id := verifyFixtureVolume(t)
hp := path.Join("/blocks", layout.VolumeDir("v", id), layout.HeadName)
fb.fakeFiler.entries[hp].Extended = map[string][]byte{layoutKind: []byte("head"), layoutVolume: []byte(id.String()), layoutGen: []byte("1")}
c := layout.NameChunk(0, []byte(strings.Repeat("a", 64)))
delete(fb.fakeFiler.entries, path.Join("/blocks", layout.VolumeDir("v", id), c.Path()))
extra := layout.NameChunk(9, []byte("orphan"))
putFile(t, fb.fakeFiler, path.Join("/blocks", layout.VolumeDir("v", id), extra.Path()), []byte("orphan"))
f := &verifyChangingHead{filerBlobs: fb, mode: mode}
r, err := VerifyLayout(context.Background(), f, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Orphans: true})
if err != nil {
t.Fatal(err)
}
if mode == "stable" {
if !r.Complete || len(r.Findings) != 2 || f.reads != 2 {
t.Fatalf("stable: %+v reads=%d", r, f.reads)
}
} else {
for _, finding := range r.Findings {
if finding.Class == layout.FindMissing || finding.Class == layout.FindOrphan {
t.Fatalf("unstable HEAD published finding: %+v reads=%d", r, f.reads)
}
}
if r.Complete || r.OrphansChecked || r.Incomplete == "" {
t.Fatalf("unstable pass looks complete: %+v", r)
}
}
})
}
}
@@ -2,6 +2,9 @@ package chunkstore
import (
"context"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"google.golang.org/protobuf/proto"
"path"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
@@ -35,3 +38,45 @@ func TestVerifyProductionLayoutCurrentAndRestored(t *testing.T) {
}
}
}
type verifyMovingDependent struct {
verifyProductionStore
target string
reads int
}
func (f *verifyMovingDependent) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
e, err := f.Filer.LookupEntry(ctx, dir, name)
if err == nil && dir == f.target && name == layout.HeadName {
f.reads++
if f.reads == 2 {
e = proto.Clone(e).(*filerpb.Entry)
e.Extended[layoutGen] = []byte("99")
}
}
return e, err
}
func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) {
ctx := context.Background()
c, source, _, _ := cleanFixture(t)
target := newRef(t, "restored")
if _, err := c.Restore(ctx, source, "s", target); err != nil {
t.Fatal(err)
}
if _, _, err := cleanVia(ctx, c, source, cleanHolder); err != nil {
t.Fatal(err)
}
extra := layout.NameChunk(99, []byte("unused"))
if err := c.f.CreateEntry(ctx, path.Join(c.base, source.Dir(), path.Dir(extra.Path())), &filerpb.Entry{Name: path.Base(extra.Path()), Content: []byte("unused")}, true); err != nil {
t.Fatal(err)
}
stable, err := VerifyLayout(ctx, verifyProductionStore{c.f, c.b}, c.base, source.Dir(), layout.VerifyOptions{Orphans: true})
if err != nil || !stable.Complete || len(stable.Findings) != 1 || stable.Findings[0].Class != layout.FindOrphan {
t.Fatalf("stable: %+v %v", stable, err)
}
f := &verifyMovingDependent{verifyProductionStore: verifyProductionStore{c.f, c.b}, target: path.Join(c.base, target.Dir())}
r, err := VerifyLayout(ctx, f, c.base, source.Dir(), layout.VerifyOptions{Orphans: true})
if err != nil || r.Complete || r.OrphansChecked || len(r.Findings) != 0 || f.reads != 2 {
t.Fatalf("moving dependent: %+v %v reads=%d", r, err, f.reads)
}
}
@@ -40,6 +40,20 @@ func (r *casObservedRemote) GetHead(ctx context.Context) (storage.ChunkHead, err
return r.ChunkRemote.GetHead(ctx)
}
func (r *casObservedRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
r.reads++
if r.onGetHead != nil {
r.onGetHead(r.reads)
}
return r.ChunkRemote.(storage.ChunkHeadRootReader).GetHeadRoot(ctx)
}
func (r *casObservedRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error {
return r.ChunkRemote.(storage.ChunkCommitChecker).CheckCommit(ctx, expected, next)
}
func (r *casObservedRemote) BoundsHeadStep() bool {
return r.ChunkRemote.(storage.ChunkHeadStepBounder).BoundsHeadStep()
}
func (r *casObservedRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
r.cass++
gen, err := r.ChunkRemote.CASHead(ctx, expected, next)
@@ -56,9 +56,10 @@ var (
var ErrChunkStaleLocalRoot = errors.New("durable: local volume predates a HEAD published by another holder")
var (
errProviderClosed = errors.New("durable: provider closed")
errChunkForeignClaim = errors.New("durable: HEAD claim refused by another holder")
errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer")
errProviderClosed = errors.New("durable: provider closed")
errChunkForeignClaim = errors.New("durable: HEAD claim refused by another holder")
errChunkNoAuthority = errors.New("durable: projection carries no master authority for the chunk layer")
errChunkRemoteCapabilities = errors.New("durable: layout remote requires CheckCommit, BoundsHeadStep and GetHeadRoot")
)
const (
@@ -508,6 +509,10 @@ func (p *DurableProvider) newChunkLayer(ctx context.Context, volumeID string, h
inner, err = p.cfg.ChunkLayoutRemoteFor(volumeID, me)
}
if err == nil {
capabilities, ok := inner.(layoutRemoteCapabilities)
if !ok || !capabilities.BoundsHeadStep() {
return nil, errChunkRemoteCapabilities
}
p.mu.Lock()
h.layoutHolder, h.layoutHead, h.layoutRemote = me, st, inner
p.mu.Unlock()
@@ -597,6 +602,14 @@ func (p *DurableProvider) attachProgress() func(uint64) {
return func(n uint64) { report(storage.RecoveryAttach, done.Add(n)) }
}
// Layout adapters must keep the object's check outside the HEAD step and
// provide an identity-only read. Wrapping must not manufacture these features.
type layoutRemoteCapabilities interface {
storage.ChunkCommitChecker
storage.ChunkHeadStepBounder
storage.ChunkHeadRootReader
}
// closeBoundRemote ends every remote call when the provider closes, so a
// shutdown never waits on the remote for an attach or a cut. While an
// attach runs, its calls also end with the attach caller's context.
@@ -712,7 +725,7 @@ func (r *closeBoundRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead,
if reader, ok := r.ChunkRemote.(storage.ChunkHeadRootReader); ok {
return reader.GetHeadRoot(c)
}
return r.ChunkRemote.GetHead(c)
return storage.ChunkHead{}, fmt.Errorf("%w: GetHeadRoot unavailable", errChunkRemoteCapabilities)
}
func (r *closeBoundRemote) CASHead(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) (uint64, error) {
@@ -722,15 +735,15 @@ func (r *closeBoundRemote) CASHead(ctx context.Context, expected storage.ChunkHe
}
// CheckCommit forwards the commit's object check (storage.ChunkCommitChecker)
// with the same binding as CASHead. A remote without it passes: its CAS then
// runs the check itself.
// with the same binding as CASHead. A remote without it refuses; the
// wrapper must never manufacture a successful object check.
func (r *closeBoundRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error {
c, end := r.bind(ctx)
defer end()
if checker, ok := r.ChunkRemote.(storage.ChunkCommitChecker); ok {
return checker.CheckCommit(c, expected, next)
}
return nil
return fmt.Errorf("%w: CheckCommit unavailable", errChunkRemoteCapabilities)
}
// BoundsHeadStep forwards whether the wrapped remote bounds its own HEAD
@@ -64,6 +64,22 @@ func (g *gatedRemote) hold(ctx context.Context, what string, ch chan struct{}) e
}
func (g *gatedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
return g.getHead(ctx, false)
}
func (g *gatedRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
return g.getHead(ctx, true)
}
func (g *gatedRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error {
return g.ChunkRemote.(storage.ChunkCommitChecker).CheckCommit(ctx, expected, next)
}
func (g *gatedRemote) BoundsHeadStep() bool {
return g.ChunkRemote.(storage.ChunkHeadStepBounder).BoundsHeadStep()
}
func (g *gatedRemote) getHead(ctx context.Context, rootOnly bool) (storage.ChunkHead, error) {
read := g.ChunkRemote.GetHead
if rootOnly {
read = g.ChunkRemote.(storage.ChunkHeadRootReader).GetHeadRoot
}
g.mu.Lock()
fail := g.failGetHead > 0
if fail {
@@ -75,14 +91,14 @@ func (g *gatedRemote) GetHead(ctx context.Context) (storage.ChunkHead, error) {
return storage.ChunkHead{}, errors.New("injected GetHead failure")
}
if g.holdAfter {
h, err := g.ChunkRemote.GetHead(ctx)
h, err := read(ctx)
_ = g.hold(ctx, "gethead", ch)
return h, err
}
if err := g.hold(ctx, "gethead", ch); err != nil {
return storage.ChunkHead{}, err
}
return g.ChunkRemote.GetHead(ctx)
return read(ctx)
}
// B Start reads HEAD through StartStore before constructing its content
@@ -28,6 +28,14 @@ type sealProgressRemote struct {
calls int
}
func (r *sealProgressRemote) CheckCommit(ctx context.Context, expected storage.ChunkHeadVersion, next storage.ChunkHead) error {
return r.layoutRemote.CheckCommit(ctx, expected, next)
}
func (r *sealProgressRemote) GetHeadRoot(ctx context.Context) (storage.ChunkHead, error) {
return r.layoutRemote.GetHeadRoot(ctx)
}
func (r *sealProgressRemote) BoundsHeadStep() bool { return r.layoutRemote.BoundsHeadStep() }
func (r *sealProgressRemote) AbortOpenSession(ctx context.Context) (string, error) {
return r.layoutRemote.AbortOpenSession(ctx)
}
@@ -0,0 +1,156 @@
package durable
import (
"context"
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/storage"
)
type incompleteRemote struct {
storage.ChunkRemote
fullReads int
}
func (r *incompleteRemote) GetHead(context.Context) (storage.ChunkHead, error) {
r.fullReads++
return storage.ChunkHead{}, nil
}
func TestCloseBoundRemoteRefusesMissingCapabilities(t *testing.T) {
inner := &incompleteRemote{}
r := &closeBoundRemote{ChunkRemote: inner, done: context.Background()}
if err := r.CheckCommit(context.Background(), storage.ChunkHeadVersion{}, storage.ChunkHead{}); err == nil {
t.Error("missing CheckCommit silently passed")
}
if _, err := r.GetHeadRoot(context.Background()); err == nil {
t.Error("missing GetHeadRoot silently passed")
}
if inner.fullReads != 0 {
t.Errorf("root-only read fell back to %d full manifest reads", inner.fullReads)
}
if r.BoundsHeadStep() {
t.Error("missing BoundsHeadStep claimed a bounded step")
}
}
type missingCheckRemote struct {
storage.ChunkRemote
storage.ChunkKeyer
storage.ChunkHeadStepBounder
storage.ChunkHeadRootReader
}
type missingBoundRemote struct {
storage.ChunkRemote
storage.ChunkKeyer
storage.ChunkCommitChecker
storage.ChunkHeadRootReader
}
type missingRootRemote struct {
storage.ChunkRemote
storage.ChunkKeyer
storage.ChunkCommitChecker
storage.ChunkHeadStepBounder
}
func TestProviderRefusesLayoutRemoteMissingRequiredCapabilityAtStart(t *testing.T) {
for _, missing := range []string{"CheckCommit", "BoundsHeadStep", "GetHeadRoot", "complete"} {
t.Run(missing, func(t *testing.T) {
fixture := newKZLayout(t)
cfg := ProviderConfig{Impl: ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 256, BlockSize: 4096, ChunkBlocks: 16,
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) { return fixture.cat.Store(fixture.ref) },
ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) {
lr, err := chunkstore.NewLayoutRemote(fixture.cat, fixture.ref, me)
if err != nil {
return nil, err
}
switch missing {
case "CheckCommit":
return &missingCheckRemote{lr, lr, lr, lr}, nil
case "BoundsHeadStep":
return &missingBoundRemote{lr, lr, lr, lr}, nil
case "GetHeadRoot":
return &missingRootRemote{lr, lr, lr, lr}, nil
default:
return lr, nil
}
},
}
p, err := NewDurableProvider(cfg, precopyQueueView{frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 3, EndpointVersion: 1}})
if err != nil {
t.Fatal(err)
}
defer p.Close()
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
_, err = p.RecoverVolume(context.Background(), "v1")
if missing == "complete" {
if err != nil {
t.Fatalf("complete layout remote refused: %v", err)
}
} else if !errors.Is(err, errChunkRemoteCapabilities) {
t.Fatalf("missing %s: want capability refusal, got %v", missing, err)
}
for _, s := range p.DurableStatuses() {
if s.Operational != (missing == "complete") {
t.Fatalf("%s operational=%v", missing, s.Operational)
}
}
})
}
}
type capabilityProbe struct {
storage.ChunkRemote
got context.Context
expected storage.ChunkHeadVersion
next storage.ChunkHead
rootCalls int
}
var errProbeCheck = errors.New("object check refused")
func (r *capabilityProbe) CheckCommit(c context.Context, e storage.ChunkHeadVersion, n storage.ChunkHead) error {
r.got = c
r.expected = e
r.next = n
return errProbeCheck
}
func (r *capabilityProbe) BoundsHeadStep() bool { return true }
func (r *capabilityProbe) GetHeadRoot(c context.Context) (storage.ChunkHead, error) {
r.got = c
r.rootCalls++
return storage.ChunkHead{Gen: 17, Epoch: 3, Holder: "host-a/replica"}, nil
}
func TestCloseBoundRemoteForwardsCapabilitiesAndClose(t *testing.T) {
done, cancel := context.WithCancel(context.Background())
defer cancel()
probe := &capabilityProbe{}
r := &closeBoundRemote{ChunkRemote: probe, done: done}
expected := storage.ChunkHeadVersion{Gen: 16, Epoch: 3}
next := storage.ChunkHead{Gen: 17, Epoch: 3, Holder: "host-a/replica"}
if err := r.CheckCommit(context.Background(), expected, next); !errors.Is(err, errProbeCheck) || probe.expected != expected || probe.next.Holder != next.Holder {
t.Fatalf("check not forwarded: err=%v expected=%+v next=%+v", err, probe.expected, probe.next)
}
if !r.BoundsHeadStep() {
t.Fatal("bounded step lost")
}
h, err := r.GetHeadRoot(context.Background())
if err != nil || h.Gen != 17 || h.Epoch != 3 || h.Holder != "host-a/replica" || probe.rootCalls != 1 {
t.Fatalf("root not forwarded: %+v %v", h, err)
}
cancel()
_ = r.CheckCommit(context.Background(), expected, next)
if !errors.Is(probe.got.Err(), context.Canceled) {
t.Fatal("CheckCommit not canceled on Close")
}
_, _ = r.GetHeadRoot(context.Background())
if !errors.Is(probe.got.Err(), context.Canceled) {
t.Fatal("GetHeadRoot not canceled on Close")
}
}
@@ -68,12 +68,33 @@ func casChunkHead(ctx context.Context, remote chunkRemote, expected chunkHeadVer
return remote.CASHead(ctx, expected, next)
}
// readChunkHead reads HEAD with its whole manifest. A remote that bounds
// its own HEAD step reads it fetch by fetch (the root, then each segment),
// each fetch bounded by chunkHeadOperationTimeout and the read as a whole by
// ctx only: the segment count grows with the volume. Any other remote's read
// is bounded as one call.
func readChunkHead(ctx context.Context, remote chunkRemote) (chunkHead, error) {
if b, ok := remote.(chunkHeadStepBounder); ok && b.BoundsHeadStep() {
return remote.GetHead(WithAttachFetch(ctx, AttachFetch{Bound: chunkHeadOperationTimeout}))
}
ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout)
defer cancel()
return remote.GetHead(ctx)
}
// readChunkHeadRoot reads HEAD's identity without its manifest when the
// remote can (ChunkHeadRootReader); ok is false otherwise.
func readChunkHeadRoot(ctx context.Context, remote chunkRemote) (head chunkHead, ok bool, err error) {
reader, ok := remote.(ChunkHeadRootReader)
if !ok {
return chunkHead{}, false, nil
}
ctx, cancel := context.WithTimeout(ctx, chunkHeadOperationTimeout)
defer cancel()
head, err = reader.GetHeadRoot(ctx)
return head, true, err
}
// ChunkHeadRootReader confirms publication identity without resolving every
// immutable manifest. The returned Chunks need not be populated.
type ChunkHeadRootReader interface {
@@ -0,0 +1,128 @@
package storage
import (
"context"
"errors"
"testing"
"time"
)
// readRemote records the context its GetHead got; bounds says whether it
// declares that it bounds its own HEAD step.
type readRemote struct {
chunkRemote
bounds bool
deadline bool
at time.Time
err error
fetch AttachFetch
perFetch bool
}
func (r *readRemote) BoundsHeadStep() bool { return r.bounds }
func (r *readRemote) GetHead(ctx context.Context) (chunkHead, error) {
r.at, r.deadline = ctx.Deadline()
r.err = ctx.Err()
r.fetch, r.perFetch = AttachFetchFrom(ctx)
return chunkHead{}, nil
}
// A whole-manifest HEAD read from a remote that bounds its own step is read
// fetch by fetch: each fetch bounded by the HEAD operation limit, the read as
// a whole only by the caller (its segment count grows with the volume). Any
// other remote's read is bounded as one call, as before.
func TestAWholeHeadReadIsBoundedPerFetchWhenTheRemoteBoundsItsStep(t *testing.T) {
stepped := &readRemote{bounds: true}
if _, err := readChunkHead(context.Background(), stepped); err != nil {
t.Fatal(err)
}
if stepped.deadline || !stepped.perFetch || stepped.fetch.Bound != chunkHeadOperationTimeout {
t.Fatalf("a remote that bounds its step: deadline=%v per-fetch=%v bound=%v; want no deadline and a per-fetch bound of %v",
stepped.deadline, stepped.perFetch, stepped.fetch.Bound, chunkHeadOperationTimeout)
}
plain := &readRemote{bounds: false}
if _, err := readChunkHead(context.Background(), plain); err != nil {
t.Fatal(err)
}
if !plain.deadline || plain.perFetch {
t.Fatalf("a remote that does not bound its step: deadline=%v per-fetch=%v; want the whole read bounded", plain.deadline, plain.perFetch)
}
}
// A caller's deadline and cancellation reach a stepped whole read: the
// per-fetch bound is added, the caller's context is kept.
func TestAWholeHeadReadKeepsTheCallersDeadlineAndCancellation(t *testing.T) {
want := time.Now().Add(time.Hour)
ctx, cancel := context.WithDeadline(context.Background(), want)
defer cancel()
stepped := &readRemote{bounds: true}
if _, err := readChunkHead(ctx, stepped); err != nil {
t.Fatal(err)
}
if !stepped.deadline || !stepped.at.Equal(want) || !stepped.perFetch {
t.Fatalf("caller deadline: got deadline=%v at=%v per-fetch=%v; want the caller's %v with the per-fetch bound", stepped.deadline, stepped.at, stepped.perFetch, want)
}
gone, stop := context.WithCancel(context.Background())
stop()
if _, err := readChunkHead(gone, stepped); err != nil {
t.Fatal(err)
}
if !errors.Is(stepped.err, context.Canceled) {
t.Fatalf("caller cancellation: the read's context reports %v; want context.Canceled", stepped.err)
}
}
// gatedRootRemote reads HEAD's whole identity alone and runs during while it
// does, so a test can observe the cut while the read is in progress.
type gatedRootRemote struct {
*fakeChunkRemote
during func()
}
func (r *gatedRootRemote) GetHeadRoot(ctx context.Context) (ChunkHead, error) {
if r.during != nil {
r.during()
}
r.mu.Lock()
defer r.mu.Unlock()
h := r.head
return ChunkHead{Gen: h.Gen, Epoch: h.Epoch, Holder: h.Holder, RemoteLSN: h.RemoteLSN, State: h.State, DetachedBy: h.DetachedBy}, nil
}
// A no-op cut's identity read is the cut's settle phase and its time counts
// as HEAD read-back, as the whole read it replaces did.
func TestANoOpCutsRootReadIsTheSettlePhaseAndCountsItsTime(t *testing.T) {
s, _ := newChunkTestStore(t)
f := newFakeChunkRemote()
r := &gatedRootRemote{fakeChunkRemote: f}
layer := mustAttach(t, s, r, ctConfig(1))
if _, err := s.Write(0, makeBlock(4096, 0x42)); err != nil {
t.Fatal(err)
}
if _, err := layer.Cut(ctTimeout(t)); err != nil {
t.Fatal(err)
}
impl := layer.(*chunkLayerImpl)
const pause = 20 * time.Millisecond
phase := ""
r.during = func() {
if c := impl.Stats().CurrentCut; c != nil {
phase = c.Phase
}
time.Sleep(pause)
}
res, err := layer.Cut(ctTimeout(t))
if err != nil {
t.Fatal(err)
}
if !res.Noop {
t.Fatalf("setup: the second cut was not a no-op: %+v", res)
}
if phase != "settle" {
t.Fatalf("phase during the no-op cut's identity read: %q; want settle", phase)
}
if got := time.Duration(res.Stats.HeadReadbackNs); got < pause {
t.Fatalf("HEAD read-back time %v; want at least the %v the identity read took", got, pause)
}
}
+27 -1
View File
@@ -798,6 +798,15 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
st.HeadReadbackNs += time.Since(start).Nanoseconds()
return head, err
}
// readCapturedRoot is the same read of HEAD's identity alone, when the
// remote can; each read counts only its own time.
readCapturedRoot := func() (chunkHead, bool, error) {
l.cutPhase("settle")
start := time.Now()
head, ok, err := readChunkHeadRoot(ctx, l.remote)
st.HeadReadbackNs += time.Since(start).Nanoseconds()
return head, ok, err
}
finishCapturedCut := func(head chunkHead, h uint64, changed []uint64, keys map[uint64]string) {
start := time.Now()
l.finishCut(head, h, changed, keys)
@@ -1176,7 +1185,7 @@ func (l *chunkLayerImpl) captureLocked(ctx context.Context, detach bool) (res ch
if !detach && len(changed) == 0 && h == baseHead.RemoteLSN && baseHead.Gen != 0 && !chunkHeadIsDetached(baseHead) {
// A no-op cut still observes authority: a fresh host may have
// claimed HEAD without uploading a single chunk since our last cut.
cur, err := readCapturedHead()
cur, err := noopCutHead(baseHead, readCapturedRoot, readCapturedHead)
if err != nil {
l.requeueCut(all)
return chunkCutResult{}, fmt.Errorf("storage: no-op cut authority read: %w: %w", errChunkRemoteUnavailable, err)
@@ -1423,6 +1432,23 @@ func (l *chunkLayerImpl) supersededBy(cur chunkHead) bool {
// and who detached; the segments; per chunk its key, content hash and
// encoding. A value the store does not keep (a chunk's birth) or that it
// owns (a generation) would make an applied commit look foreign.
// noopCutHead is a no-op cut's authority read. When rootRead reads HEAD's
// identity alone (a ChunkHeadRootReader remote) and HEAD is still the image baseHead
// names (the same generation token, epoch, holder, position and detach
// state; the token changes whenever HEAD's root does), it is baseHead with
// its chunks, and no manifest is read. Otherwise it is the whole HEAD (full).
func noopCutHead(baseHead chunkHead, rootRead func() (chunkHead, bool, error), full func() (chunkHead, error)) (chunkHead, error) {
root, ok, err := rootRead()
if err != nil {
return chunkHead{}, err
}
if ok && root.Gen == baseHead.Gen && root.Epoch == baseHead.Epoch && root.Holder == baseHead.Holder &&
root.RemoteLSN == baseHead.RemoteLSN && chunkHeadIsDetached(root) == chunkHeadIsDetached(baseHead) {
return copyHead(baseHead), nil
}
return full()
}
func sameProposal(cur, next chunkHead) bool {
if (cur.Segments == nil) != (next.Segments == nil) || cur.ChunkBytes != next.ChunkBytes || cur.ManifestChunkCount != next.ManifestChunkCount || len(cur.Segments) != len(next.Segments) {
return false
+1 -1
View File
@@ -121,7 +121,7 @@ SWB_CHUNK_UPLOAD_CONCURRENCY=8
# snapshots, snapshot/delete, detach) on the status listener; needs
# SWB_STATUS_ADDR.
SWB_CHUNK_CONTROL_ENDPOINT=false
# --workspace-lease (default false). Require a host-owned master lease; fail
# --workspace-lease (default false; REQUIRED true for walstore-chunk). Require a host-owned master lease; fail
# closed when it is unavailable. Needs walstore-chunk and --workspace-rpc on
# blockmaster.
SWB_WORKSPACE_LEASE=false
+8 -4
View File
@@ -73,7 +73,7 @@ stateDiagram-v2
| — | CreateRefused | a new volume needs the durable root's free space >= its size + WAL, checked before the store, its WAL or its fresh marker is created (the replica floor, written when the assignment arrives, precedes the check and stays); the refusal ends the process with status 1; an existing volume opens and warns when its remaining data growth + WAL exceed the free space | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `openOrCreate` | `INV-LOCAL-HEADROOM-001` |
| — | CreateRefused | a chunk volume in create mode (no local store yet): before the provider is built, the geometry flags are compared with the volume record; they disagree, or the record is there but does not decode: exit 78; the filer failed the read: exit 75; nothing is created; an absent record keeps the create path; an existing store is never rechecked against the flags | `cmd/blockvolume/main.go` (create-mode check); `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal` | `INV-VOL-GEOMETRY-FLAGS-RECORD-001` |
| Opened | Recovering | the volume is open in the provider | `core/frontend/durable/provider.go` `RecoverVolume` | `INV-WAL-OPGATE-001`, `INV-RECOVERY-PROGRESS-WINDOW-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; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `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`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-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; the frontend targets start, and `FrontendPrimaryReady` is reported, only once the backend admits I/O (a chunk volume: after its storage claim; attach-pending or fenced reports not ready with the reason); a workspace primary claims HEAD, listens and reports ready only while its lease guard permits now (`WorkspaceLeaseGuard.Held`; without a grant: `NotReadyReason=lease_not_held`, exit 75 after the start-time wait); a primary of a replicated line serves only when its own `--replication-ack` is the profile its assignment names (otherwise not Healthy, `NotReadyReason` naming both profiles, ahead of the backend's own refusal) | `core/storage/walstore_v3.go` `recoverV3`; `core/storage/walstore.go` `WALStore.Recover`; `cmd/blockvolume/frontend_gate.go` `awaitFrontendStart`; `core/frontend/durable/storage_adapter.go` `FirstServing`; `core/host/volume/status_server.go` `statusProjection`; `core/host/volume/workspace_lease.go` `Held`; `core/host/volume/workspace_startup.go` `noteAckProfile` | `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`, `INV-FE-PRIMARY-READY-OPERATIONAL-001`, `INV-WS-SERVE-LEASE-HELD-001`, `INV-PRIMARY-ACK-PROFILE-001`, `INV-ATTACH-ASSIGNMENT-BOUND-001`, `INV-LAYOUT-REMOTE-CAPABILITIES-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`, `INV-WAL-V3-MAP-PRIOR-LIVE-001` |
@@ -830,6 +830,7 @@ Notes:
| `INV-VOL-GEOMETRY-FLAGS-RECORD-001` | A create-mode start whose `--durable-blocks`/`--durable-blocksize` disagree with the volume record exits 78 before any local store exists; an existing store is checked only at attach; an absent record keeps the create path; an unread record exits 75 (filer failed) or 78 (corrupt). | blockvolume startup (before the durable provider) | `cmd/blockvolume/main.go`; `cmd/blockvolume/chunk_remote.go` `geometryFlagsRefusal`; `core/frontend/chunkstore/layout/volume.go`, `start.go`, `create.go`; `core/frontend/chunkstore/catalog_b.go` | `TestGeometryFlagsRefusalComparesTheRecord`, `TestVolumeRequiresGeometry`, `TestVolumeGeometryChecksAndIsImmutable`, `TestStartGeometryMismatchPrecedesClaim`, `TestBCatalogRestoreCopiesVolumeGeometry`, `TestVolumeGeometryLivesOnlyInVolume` | K3: immutable required VOLUME geometry; Start checks the local persisted shape before claim; restores copy source geometry; no resize or compatibility path. | ACTIVE |
| `INV-WS-STALE-LOCAL-ROOT-001` | An old or rolled-back local root is refused by `layout.Start` before serving; synchronous and deferred attach end without retry and report the typed stale-root error and cure. A fresh root at its own epoch likewise ends with `ErrMissingLocalRoot` and its cure. | M4 Claiming → Refused | `core/frontend/durable/provider_layout.go` `startLayoutRoot`; `core/frontend/durable/provider_chunk.go` `recoverChunk`, `chunkAuthorityWait`; `core/frontend/durable/provider_startup.go` `endChunkStartup` | `TestLayoutProviderRefusesEmptyOwnEpochAndRemountedOldRoot`, `TestFinalLayoutStartRefusalTable` (`core/frontend/durable/provider_layout_test.go`, `provider_layout_start_class_test.go`) | — | ACTIVE |
| `INV-WS-ONE-PROCESS-PER-HOST-001` | One host runs at most one live blockvolume per volume: each takes the volume's exclusive host lock before its store opens and holds it until the store closes; a second is refused before it opens anything, whatever its `--durable-root`. | M4 (start) → Attaching, Refused | `core/frontend/durable/provider.go` `DurableProvider.lockVolumeOnHost` | `TestOneLiveProcessPerVolumePerHost`, `TestHostVolumeLockDirectoryCreatedOrRefused`, `TestHostVolumeLockRefusesNonDirectoryLockPath`, `TestHostVolumeLockTakesReadOnlyLockFile` (`core/frontend/durable/one_process_per_volume_test.go`); `TestHostVolumeLockCreatesParent0755AndLocks0700`, `TestHostVolumeLockKeepsExistingDirectoryModes` (`core/frontend/durable/volume_lock_parent_mode_test.go`); `TestVolumeLockDirTestOnlyRefusedUnderSystemd` (`cmd/blockvolume/volume_lock_flag_test.go`) | — | ACTIVE |
| `INV-CHUNK-LEASE-REQUIRED-001` | Blockvolume refuses walstore-chunk startup without --workspace-lease before any host or store is opened. The refusal names concurrent acknowledging writers and acknowledged-write loss after a forced move; plain walstore startup is unchanged. | M4 startup → Refused | `cmd/blockvolume/main.go` `parseFlags` | `TestChunkVolumeRequiresWorkspaceLeaseBeforeStart` | — | ACTIVE |
| `INV-WS-SINGLE-FILER-001` | A chunk volume starts only when `--chunk-filer` is its group's only filer, confirmed in a round where every master answered: a master listing another filer or several refuses at once; an unanswered master leaves the round unconfirmed; 60 s unconfirmed is refused. A startup census, not a fence. | M4 (startup) → Refused | `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `cmd/blockvolume/chunk_remote.go` `newChunkWiring`; `cmd/sw-block/chunk.go` `refuseUnlessSingleFiler` | `TestCheckSingleFilerRefusesAnotherOrSeveralFilers`, `TestCheckSingleFilerFailsClosed`, `TestCheckSingleFilerNeedsEveryMasterToAnswer`, `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_StartCheckRefusesAnUnparsableMaster` (`cmd/sw-block/chunk_single_filer_unanswered_test.go`), `TestOpsChunk_VerifyRunsTheSingleFilerCheck` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-WS-LEASE-REGRANT-001` | Re-grant after expiry keeps the same holder and epoch, with no pending move or revocation, a certain store, and one durable write after the horizon/deadline plus skew barrier. Restart begins a new session and voids the old; ordinary reopen keeps HEAD identity (epoch, holder, claim) unchanged. | M2 Expired → Granted; M9 Start | `core/authority/workspace_lease_view.go` `regrantWorkspaceLease`; `core/authority/workspace.go` `forcedMoveBarrierLocked`; `core/frontend/chunkstore/layout/start.go` `Start` | `TestWorkspaceLeaseExpiredSameHolderRegrantIsDurable`, `TestWorkspaceLeaseRegrantWaitsForFullSkew`, `TestWorkspaceLeaseRegrantDefeatsAlreadyPassedForcedPreflight`, `TestWorkspaceLeaseForcedIssueDefeatsOldHolderRegrant`, `TestWorkspaceLeaseRegrantWaitsForDurabilityAndLatchesFailure` (`core/authority/workspace_regrant_test.go`); `TestWorkspaceLeaseRegrantPreservesLocalLogThroughFirstCut` (`core/authority/workspace_regrant_storage_test.go`); `TestStart_OwnEpochFreshRootRefusedBeforeClaim`, `TestStart_OwnEpochSameRootContinues` (`core/frontend/chunkstore/layout/start_test.go`); `TestClaim_WritesItsClaimID`, `TestRunClaim_VoidsTheOldSession` (`core/frontend/chunkstore/layout/claim_test.go`); `TestLocalReopenClaimsBeforeServing` (`core/frontend/durable/provider_reopen_belt_test.go`) | `WorkspaceRegrant` `NoDualServingInc`, `RegrantNoLoss`, `DiskCoversMemory`; `INV-SNAPK-START-ROOT-001` | 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 |
@@ -878,7 +879,7 @@ Notes:
Notes:
- `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, fork, retain, volume-delete, gc --apply), and in verify, which writes nothing but would report false findings against a split filer view, before it reads or writes; other read-only commands and modes do not run it.
- `INV-WS-SINGLE-FILER-001`: the same census runs in every `sw-block ops chunk` command that writes chunk metadata (snapshot-delete, retain, volume-delete), and in verify, which writes nothing but would report false findings against a split filer view, before it reads or writes; other read-only commands and modes do not run it.
- `INV-WS-HEAD-CAS-001`: The integration test needs build tag `chunkstore_integration` and a pinned `weed` binary.
- `INV-WS-CAS-UNKNOWN-001`: An unknown-outcome CAS is not in the TLA+ models (`docs/spec/README.md`, Limits).
- `INV-WS-HEAD-KEY-PROVENANCE-001`: No test asserts it yet in this change. The legacy verifier that observed a key HEAD named, dropped and named again is removed; on the content-named layout a name is its content, so the case does not arise there.
@@ -910,6 +911,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` | Retired: B does not store per-chunk BirthLSN; `INV-SNAPK-COMMIT-REACH-001` protects the published object graph, and the surviving barrier-image test protects the cut image. | legacy M5 | — | — | — | 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`); `TestChunkStageV3_MidUploadAbortReducesRetryBytes` (`core/storage/chunk_abort_upload_bytes_test.go`); `TestCutRevokedMidUploadKeepsItsUploads` (`core/storage/chunk_cut_revoke_reuse_test.go`) | `CutPipeline` `HeadImage` | ACTIVE |
| `INV-LAYOUT-REMOTE-CAPABILITIES-001` | A provider attaches only a layout remote with commit checking, a bounded HEAD step and identity-only HEAD reads. Its wrapper refuses missing check/read capabilities and never substitutes a full manifest read or a successful check. | M1 attach; M5 object check and HEAD confirmation | `LayoutRemote` compile-time assertions; `DurableProvider.newChunkLayer`; `closeBoundRemote` | `TestCloseBoundRemoteRefusesMissingCapabilities`, `TestProviderRefusesLayoutRemoteMissingRequiredCapabilityAtStart`, `TestCloseBoundRemoteForwardsCapabilitiesAndClose` (`core/frontend/durable/remote_capabilities_test.go`) | existing adapter contract (no state or transition change) | ACTIVE |
| `INV-CUT-RETRY-FAIRNESS-001` | New staging retries without backoff; zero progress backs off. Dirty-start cleaning waits for a completed store attempt or one maintenance interval. K=3 admitted stalled background attempts yield reusable staging, never a pending or active/newer cut. | M5 Stage, M6 Clean (CUT-BUDGET B1/B3) | `core/frontend/durable/provider_chunk.go`; `core/frontend/durable/chunk_snapshot_schedule.go`; `core/storage/chunk_periodic_cut.go` | `TestCutLoopProgressRetriesWithoutBackoff`, `TestScheduledSnapshotProgressRetriesWithoutBackoff`, `TestDirtyStartCleaningWaitsForFirstCutAttempt`, `TestDirtyStartCaptureRefusalsDoNotReleaseCleaning`, `TestStalledCutYieldsSessionToCleaning` (`core/frontend/durable/cut_progress_test.go`); `TestDiscardStagedRechecksCaptureState` (`core/storage/chunk_stalled_discard_test.go`); `TestLayoutStalledSessionYieldAllowsCleaning` (`core/frontend/chunkstore/layout_stalled_discard_test.go`) | `CommitReach` `CBegin` (existing session exclusion; scheduling only) | ACTIVE |
| `INV-CUT-STAGED-COUNT-001` | `Stats.StagedChunks` counts each chunk staging finished (remembered for reuse) in every cut attempt, an interrupted round included, and only grows; a re-staged chunk counts again; it is in-process. A cut's `PayloadNs` includes its staging rounds whether or not they uploaded. | M5 Stage (before the barrier) | `core/storage/chunk_cut_payload.go` `rememberPayload`, `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkStage_StagedChunksCountsFailedAttempts`, `TestChunkStage_StagedChunksCountsAnInterruptedRound`, `TestChunkStage_PayloadTimeCountsStagingWithoutUploads` (`core/storage/chunk_stage_accounting_test.go`) | — | 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 (a cut, or a fresh store's claim: `INV-CUT-FRESH-KNOWN-ZERO-001`) 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 |
@@ -944,7 +946,7 @@ Notes:
| `INV-LOCAL-HEADROOM-001` | blockvolume refuses to create a volume when the durable root's free space is below the volume size plus its WAL, naming both numbers, before it creates the store, WAL or fresh marker, and warns at start when an existing volume's remaining sparse growth plus the WAL exceed the free space. | M1 open/create (durable provider start) | `core/frontend/durable/headroom.go`; `core/frontend/durable/provider.go` `createFresh`, `openExisting` | `TestCreateRefusesWithoutLocalHeadroom`, `TestOpenWarnsWithoutLocalHeadroom` (`core/frontend/durable/headroom_test.go`) | — | ACTIVE |
| `INV-CREATE-MAX-SIZE-001` | blockmaster refuses a new volume above `geometry.MaxNewVolumeBytes` at CreateVolume (InvalidArgument) and at a `--cluster-spec` start, with `ErrVolumeTooLarge` naming the size and the maximum, before any record or store exists. An existing volume keeps opening under `MaxVolumeBytes`. | create admission (CreateVolume, cluster-spec import) | `core/geometry/volume_size.go` `ValidateNewVolumeSize`; `core/lifecycle/store.go` `CreateVolume`; `cmd/blockmaster/cluster_spec.go` `loadClusterSpec`; `core/host/master/services.go` `CreateVolume` (restore geometry) | `TestCreateVolumeRefusesAVolumeAboveTheMaximum` (`core/host/master`), `TestClusterSpecRefusesAVolumeAboveTheMaximum` (`cmd/blockmaster`), `TestValidateNewVolumeSizeAtAndAboveTheMaximum` (`core/geometry`), `TestCreateVolumeRejectsBeyondUint32LBACap` (`core/lifecycle`) | — | ACTIVE |
| `INV-HOST-SLOT-BUSY-CODE-001` | The chunk control API refuses a cut, snapshot or detach that host admission refused because every slot is held (or urgent work is pending) with 503 host_slot_busy, retryable; every other capture refusal keeps capture_refused. | M7 free → admitted (refused, wait) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestHostSlotHeldHasItsOwnCode` (`core/host/volume/chunk_host_slot_code_test.go`) | — | ACTIVE |
| `INV-CUT-INTENT-FIRST-001` | Before the first chunk or segment PUT of a cut or staging round, the holder's session is begun (Begin; a replay while it is open): one Begin per round, however many upload waves it uses; every object the cut writes belongs to that session until its commit. | M5 Begin → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Begin` | `TestSession_BegunBeforeFirstUploadAndClosedByCommit`, `TestSession_FailedBeginUploadsNothing` (`core/storage/chunk_layer_session_test.go`); `TestCutPayloadSessionBeginsIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
| `INV-CUT-INTENT-FIRST-001` | A cut or staging round begins (or replays) its holder session before any chunk or segment PUT. All upload waves use that session until commit. Payload I/O and pacing hold no adapter lock, so independent uploads and HEAD reads proceed. | M5 Begin → Upload → CAS | `core/storage/chunk_cut_payload.go` `streamCutPayloads`; `core/storage/chunk_layer.go` `captureLocked`, `stage`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Begin` | `TestSession_BegunBeforeFirstUploadAndClosedByCommit`, `TestSession_FailedBeginUploadsNothing` (`core/storage/chunk_layer_session_test.go`); `TestCutPayloadSessionBeginsIndependentOfCandidates`, `TestCutPayloadReadsOverlapEarlierUploadsWithinBudget` (`core/storage/chunk_review271_test.go`); `TestChunkPrecopy_StagedUploadsAreCoveredByIntents` (`core/storage/chunk_layer_precopy_test.go`); `TestLayoutRemoteUploadsOverlapWithoutBlockingHead`, `TestLayoutRemoteHeadReadDoesNotWaitForUpload` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`) | `ChunkLifecycleFixed` `GCSafe`; `WorkspaceTakeover` `NoLiveIntentExpired` | ACTIVE |
| `INV-CUT-INTENT-CLOSE-001` | The session lives as long as the staged uploads: it is aborted only when they are dropped (Close, fenced, a HEAD moved past the commit's base, a settled proposal), never while a proposal's commit is unresolved; a refused cut that keeps its uploads keeps its session for the retry. | M5 Close | `core/storage/chunk_layer.go` `Close`, `captureLocked`, `discardStaged`, `requeueCut` | `TestChunkCloseAbortsTheOpenSessionUnlessACommitIsUnresolved` (`core/storage/chunk_review271_test.go`); `TestSession_AdmissionRefusedBeforeCommitKeepsReusableUploads` (`core/storage/chunk_layer_session_test.go`); `TestHeadBeltOldCASUnconfirmedKeepsSessionAndFrontier`, `TestHeadBeltLowerEpochConflictFencesWithoutCleanup`, `TestHeadBeltEmptyBaseForeignPublicationFences` (`core/storage/chunk_head_belt_test.go`) | — | 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-HYDRATION-PROGRESS-001` | The status reports per volume the HEAD-named chunks still to hydrate (`AbsentChunks`) and the chunks hydrated so far (`Hydration.Completed`, cumulative); a read of an un-hydrated chunk moves both by one, a repeat read neither. Observation only. | M5 hydration (reader; no transition) | `core/storage/chunk_layer.go` `Stats` (`absentHydratable`); `core/storage/chunk_hydration.go` `hydrationWorker` | `TestHydrationProgressCountersFollowFirstReads` (`core/frontend/durable/hydration_progress_test.go`) | — | ACTIVE |
@@ -1006,6 +1008,7 @@ Notes:
| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after the commit naming it is confirmed (every object its root reaches written by the session first); an unknown outcome reports failure, settled by reading HEAD. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead`; `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `TestLayoutRemote_CutCommitsThroughTheKernel` (`core/frontend/chunkstore/layout_remote_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE |
| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE |
| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-STABLE-HEAD-001` | Filer verify publishes MISSING or ORPHAN only after two HEAD observations agree on a nonzero generation and volume identity. An unavailable or changed own/dependent HEAD makes the pass incomplete and suppresses those findings. Unsupported verify options refuse before dialing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `cmd/sw-block/chunk_verify.go` `chunkVerify` | `TestVerifyLayoutRequiresStableHeadForMissingAndOrphans`; `TestVerifyConfirmsDependentHeadBeforeReportingOrphans`; `TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial` | — | ACTIVE |
| `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-REACH-001` | A complete pass checks every object the current root and every snapshot root name (roots, segments, chunks): an absent one is `MISSING`; one whose bytes do not hash to its name, at depth full, is `CORRUPT`. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyCleanVolume`, `TestVerifyFindsMissingAndCorrupt`, `TestVerifyWalksSnapshotRoots` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-INCOMPLETE-001` | A volume whose VOLUME or HEAD is absent or does not decode is never reported clean: the pass is incomplete and says which object. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyHeadMissingOrMalformedIsIncomplete` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE |
@@ -1121,7 +1124,7 @@ Notes:
| `INV-SNAPK-HEAD-CODEC-001` | HEAD is canonical JSON with at most 10 snapshots (`MaxSnapshots`) and sorted unique dependents; unknown fields, non-canonical bytes and names that are not valid UTF-8 are refused at encode and decode, and the next HEAD is checked before it is written. | M9 every transition | `core/frontend/chunkstore/layout` `head.go` `Head.check`, `Head.Encode`, `DecodeHead` | `TestHead_GoldenEncodingRoundTrip`, `TestHead_Refusals`, `TestHead_RefusesInvalidUTF8` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-BEGIN-001` | Begin opens snap(s) only for the holder at HEAD's epoch and only from idle; a re-run of the open session writes nothing; killed at its write and re-run, it ends in snap(s) at one generation step. | M9 idle → snap | `core/frontend/chunkstore/layout` `head.go` `Head.Begin`, `RunBegin` | `TestBegin_Closure`, `TestRunBegin_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-ABORT-001` | Abort closes the holder's own snap(s) and changes nothing else; after its own crash a holder rolls the open session back before beginning another; over idle Abort writes nothing and its success never says whether the work was committed. | M9 snap → idle (Abort) | `core/frontend/chunkstore/layout` `head.go` `Head.Abort`, `RunAbort`; `core/frontend/durable/provider_layout.go` `settleLayoutStop` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestLayoutRemote_AbortOpenSessionDoesNotWaitForAHeldCommit`, `TestLayoutRemote_AbortOpenSessionFencesAForeignHead`, `TestLayoutRemoteSessionFieldSites`, `TestAbort_Closure`, `TestAbort_IdleMeansNoActivityRemains`, `TestAbort_RollBackAfterOwnCrash`, `TestRunAbort_InterruptAtEveryStep` | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-COMMIT-REACH-001` | A commit never names an object that is not written: before its one HEAD update it finds present the own chunks new against HEAD's current root (that root rebuilt from the previous manifest, an empty image included), every segment and the root; unchanged and foreign chunks are not looked up. | M9 snap → idle (Commit) | `core/frontend/chunkstore/layout` `commit.go` `RunCommit`, `CheckCommitObjects`, `Head.Commit`; the lookups run with the cut's budget before the bounded HEAD update (`layout_remote.go` `LayoutRemote.CheckCommit`, called by `core/storage/chunk_layer.go`), and the CAS skips them only for the (session, root) checked | `TestCommit_Closure`, `TestRunCommit_LooksUpOnlyWhatIsNew`, `TestRunCommit_RefusesUnwrittenObjects`, `TestRunCommit_StaleBaseAndLookupFailure`, `TestRunCommit_AfterAnEmptyPublishedRoot`, `TestRunCommit_InterruptAtEveryStep`; its verification is bounded parallel and stays all-or-nothing: `TestCommitVerifiesManyNewChunksWithinTheBudget`, `TestADetachingCommitOfManyNewChunksCompletesWithinTheBudget`, `TestCommitRefusesWhenOneOfManyNewChunksIsNotPrepared`, `TestCommitLookupsNeverExceedTheCap`, `TestACancelledCommitStopsJoinsAndWritesNothing`, `TestTheEarliestFailureByPositionDecidesTheError` (`commit_verify_scale_test.go`, `commit_verify_controls_test.go`); outside the 2 s update: `TestCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestCASSkipsTheLookupsCheckedForItsSessionAndRoot`, `TestCASWithNoPassedCheckDoesTheLookups`, `TestCASAfterACheckOfAnotherRootDoesTheLookups`, `TestBeginCleanBetweenTheCheckAndTheUpdateIsBusy`, `TestAPreCheckThatFindsAChunkMissingEndsWithNoLookupInTheCAS` (`core/frontend/chunkstore/layout_commit_check_budget_test.go`); `TestObjectsCheckedIsWrittenOnlyByCASHead`, `TestCASAfterAnAbortAndANewSessionAtTheSameRootDoesTheLookups`, `TestCommitPendingSnapshotLooksUpTheRootAndSegments`, `TestMetadataRetryLooksUpOnlyWithoutAPassedCheck` (`core/frontend/chunkstore/layout_commit_check_guards_test.go`); through the provider's wrapped remote: `TestProviderCutCommitsWhenItsObjectCheckOutlastsTheHeadUpdate`, `TestProviderWrappedRemoteKeepsTheLayoutRemotesOptionalInterfaces` (`core/frontend/durable/commit_check_budget_test.go`); `TestLayoutRemoteUploadFinishedAfterSessionEndCannotCommit` (`core/frontend/chunkstore/layout_upload_concurrency_test.go`) | — (the snapshot kernel model is not in this repository) | ACTIVE |
| `INV-SNAPK-SNAPSHOT-META-001` | Snapshot retention metadata (creation time, class, expiry and at most four bounded labels) is written by the commit that creates the snapshot name and never changed by a replay. | M9 snap -> idle (named Commit) | `core/frontend/chunkstore/layout/head.go` `SnapshotMeta`, codec; `commit.go` `Head.Commit`, `RunCommit`; `core/host/volume/chunk_control.go` `chunkControl.Snapshot`, `chunkControl.ListSnapshots` | `TestSnapshotMeta_WrittenOnceByTheCommit`, `TestHead_BoundsRefused`, `TestGuard_SafetyIgnoresSnapshotMeta`; `TestChunkControlPassesRetentionFactsToTheNamedCommit`, `TestChunkControlUsesTheBoundLayoutIdentity` | Retention facts affect policy only; the safety guard forbids their use in reachability/removal. Actual provider and scheduled capture integration remain cutover work; no live-path claim. | ACTIVE |
| `INV-SNAPK-DETACHED-001` | A detached HEAD remains closed to its same-epoch holder; only a higher-epoch Claim returns it to live. | M9 snap → detached → higher-epoch idle | `core/frontend/chunkstore/layout` `commit.go`, `head.go`, `claim.go`, `start.go` | `TestLayoutStopAbortMustConfirmItsOutcome`, `TestWorkspaceLayoutDetachedProof`, `TestCommitDetached_ProofAndLostReply`, `TestDetachedHEAD_RefusesEveryHolderTransition`, `TestDetachedHEAD_NewGrantStillWaitsForTheOldLease` | Caller write-barrier and synced-position join, master clean-proof reader and composed model review remain cutover gates. | ACTIVE |
| `INV-SNAPK-TXN-INTERRUPT-001` | A snapshot transaction killed at any of its writes (Begin, each object, Commit), before the write or after it applied with its reply lost, never leaves HEAD reaching a missing object, and the restarted holder (roll back, new session, base recomputed from HEAD) ends at the committed image. | M9 idle → snap → idle | `core/frontend/chunkstore/layout` `head.go`, `commit.go` (the transitions above) | `TestSnapshotSession_InterruptAtEveryStep`, `TestReachableMissing_Controls`, `TestAbort_AfterCommitLeavesTheCommit` | — (the snapshot kernel model is not in this repository) | ACTIVE |
@@ -1214,6 +1217,7 @@ One row per fixed time limit on a volume's path that surrounds, or once surround
|---|---|---|---|---|---|
| `core/storage/chunk_head_belt.go` `casChunkHead`, applied by `LayoutRemote.commitStepLocked` | 2 s per attempt | one HEAD step: the HEAD read, the commit's decision from its plan, the conditional write | no | the commit's preparation (the previous manifest, the next root and segments, the plan) and its object lookups, under the cut's limit; a commit after a passed check reuses the preparation | `TestHolderCommitAtOneTiBKeepsItsPreparationOutOfTheHeadStep`, `TestCommitUpdateStepDoesNotRereadTheManifests` |
| the same step, for a commit that was NOT checked first | 2 s per attempt | the step and the object lookups of every new chunk, and of a new root's segments and root even when no chunk is new | **yes** | nothing: no production caller commits without the check; a new caller must check first | none: a known gap, stated here so it is not claimed. Kept true by `TestEveryHeadCommitIsCheckedFirst`: every HEAD commit of the chunk layer (a cut's commit, a detach's cancellation, an unresolved cut's re-proposal) runs the object check before its CAS, and a new site fails until it does. `TestDetachCancellationAfterALostUpdateLooksUpNothingInTheHeadStep` measures the cancellation. The snapshot of an unchanged image commits under its caller's limit, not in this step |
| `core/storage/chunk_head_belt.go` the chunk layer's HEAD reads: `confirmChunkHead` after a HEAD write, a no-op cut's authority read (`noopCutHead`), and `readChunkHead` when a write's outcome is settled | 2 s per remote call | the confirmation and a no-op cut over an unchanged HEAD read HEAD only (`GetHeadRoot`), no root and no segment; a settlement reads the whole manifest, one root fetch and one fetch per segment, each bounded on its own | the confirmation and the no-op read: no; a settlement's fetch count: **yes** | a settlement's read as a whole, under the cut's limit; a no-op cut over a changed HEAD reads the whole manifest the same way | `TestTheConfirmationAfterAHeadWriteReadsNoManifest`, `TestANoOpCutReadsNoManifestWhileHeadIsUnchanged` (count 0 fetches whatever the size), `TestAWholeHeadReadIsBoundedPerFetchWhenTheRemoteBoundsItsStep` |
| `DurableProvider.chunkCutContext` (`ChunkCutTimeout`) | 5 min per attempt | staging the changed chunks, the check, the commit | yes | uploads finished by an attempt are kept; the next attempt uploads only the rest (same process) | `TestACutAttemptThatRunsOutOfTimeLeavesUploadsTheNextAttemptKeeps` |
| the cleaning pass (`boundedPass`) | the configured pass limit | listing and removing by page | yes | the pass resumes at its cursor; a session after a restart starts at the root page | the cleaning cursor's tests |
| `core/host/volume/chunk_control.go` `chunkContext` (a chunk control operation: a cut, a snapshot or a detach, each of which takes a cut; the chunk status read also runs under it and reads one HEAD) | 5 min, or the request's shorter limit | the operation, including the cut it takes | yes | the cut's uploads, as the cut's row: an attempt that runs out of time keeps what it uploaded | STUB: no test at the control operation's level yet |
+3 -8
View File
@@ -449,14 +449,9 @@ acts. The limits, as they show on a running system:
In the acknowledging modes, acknowledged writes were read back intact in every run that found these limits. What the
release supports without these limits is the single-replica volume.
**Planned for v1.0.1.** Two replicated configurations are planned to become supported:
- **RF3 `sync-quorum`, installed on hosts:** writes continue through one replica's fault, and that replica returns
by itself.
- **RF2 `sync-quorum`, with its limit:** no acknowledged write is lost and failover is automatic, but writes stop
while either replica is out.
`sync-all` and Kubernetes RF3 stay a preview. In every replicated configuration, an old primary cut off from
blockmaster by a partition may keep serving reads of older data until its lease ends.
**Planned for v1.1.0.** Supported replicated volumes are planned for v1.1.0; v1.0.1 keeps every replicated
configuration a preview. In every replicated configuration, an old primary cut off from blockmaster by a partition
may keep serving reads of older data until its lease ends.
## When a host is lost
@@ -26,11 +26,9 @@ writing guest:
replica, so a replica whose connection dropped can keep showing `healthy` while it misses writes. Use `sync-quorum`
when the replicas must hold the data.
**Planned for v1.0.1.** Supported: RF3 `sync-quorum` installed on hosts (writes continue through one replica's
fault, and that replica returns by itself), and RF2 `sync-quorum` with its limit (no acknowledged write is lost and
failover is automatic, but writes stop while either replica is out). `sync-all` and Kubernetes RF3 stay a preview. In
every replicated configuration, an old primary cut off from blockmaster by a partition may keep serving reads of
older data until its lease ends.
**Planned for v1.1.0.** Supported replicated volumes are planned for v1.1.0; v1.0.1 keeps every replicated
configuration a preview. In every replicated configuration, an old primary cut off from blockmaster by a partition
may keep serving reads of older data until its lease ends.
**Carrying over.** No change to the store format is planned for the release that lifts the preview, so a replicated
volume created under it is expected to carry over without re-creating it. That release's design is still under
+21 -3
View File
@@ -287,7 +287,11 @@ listener before it has an assignment. Without one, the status shows
| 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,
**Workspace lease volumes (`--workspace-lease`).** The flag is required for every
`--durable-impl=walstore-chunk` volume. Blockvolume refuses to start without it:
unleased holders can both acknowledge writes, and an old holder can lose
acknowledged writes after a forced move. Plain walstore volumes do not require
this flag. Besides the steps above,
blockmaster needs `--workspace-rpc`, `--chunk-filer` (and blockvolume's
`--chunk-path`, when not the default) and `--lifecycle-store`, and the volume needs a single-replica volume record in
that store. To create and place an RF1 volume online on an already registered
@@ -430,7 +434,7 @@ volume or prove frontend readiness.
| `SWB_CHUNK_SNAPSHOT_SCHEDULE` | `--chunk-snapshot-schedule` | `daily:7` | Scheduled named snapshots: `daily:N` or `weekly:N` (one per period at a per-volume offset, the newest N kept), or `off` |
| `SWB_CHUNK_UPLOAD_CONCURRENCY` | `--chunk-upload-concurrency` | `8` | Parallel chunk uploads (1..64) |
| `SWB_CHUNK_CONTROL_ENDPOINT` | `--chunk-control-endpoint` | `false` | `/chunk/*` routes on the status listener |
| `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Require a master lease; fail closed without one |
| `SWB_WORKSPACE_LEASE` | `--workspace-lease` | `false` | Required for walstore-chunk: require a master lease; fail closed without one |
| `SWB_VOLUME_EXTRA_ARGS` | any | empty | Other flags (Kubernetes gate and source-gated flags) |
The `--chunk-*` and `--workspace-lease` flags are refused unless
@@ -867,7 +871,18 @@ directories using each reference's full owner id.
Verify is read-only: exit 0 means complete with no findings, 3 means complete
with findings, 1 means incomplete, and 2 means invalid arguments. `--depth data`
checks chunk hashes and requires an explicit timeout. `--orphans` only reports;
it never deletes anything. Master connections use the same TLS environment as
it never deletes anything. `--snapshot`, `--all-snapshots`, `--concurrency` and
`--bytes-per-sec` are unsupported and refuse even when explicitly set to their
default values; all named snapshots are checked sequentially without pacing.
`MISSING` and `ORPHAN` findings require matching nonzero generations on the
HEAD read before the walk and the confirmation read after it. Live dependent
HEADs used for orphan reachability are confirmed too. A changed, absent,
unreadable or generation-less HEAD makes the pass incomplete (exit 1), with
those findings suppressed; retry against a stable volume. HEAD generation advances
on every cut, snapshot and cleaning pass, so MISSING/ORPHAN verification may never
complete on a served volume; run it on a stopped volume or between cuts, snapshots
and cleaning passes. This is an observation window, not a lock against later writes. Master connections use the same TLS environment as
the other `sw-block ops` commands.
@@ -935,6 +950,9 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i
#### Lifetime of a restore target
- **v2 never becomes independent of the source snapshot**, not even after its whole device has been read: the
snapshot stays pinned while v2 exists and counts toward the source's limit of 10 snapshots, and the source volume
cannot be deleted before v2. Making a restored volume independent is planned for v1.1.0.
- **The source snapshot cannot be deleted** while v2 exists: `ops chunk snapshot-delete` is refused with `snapshot_has_dependents`. Delete v2 first (see [Delete a volume](volume-lifecycle.md#delete-a-volume)); the snapshot can be deleted after that.
- **A snapshot of v2 cannot be restored:** it names the source's chunks. The restore exits 1 with `"code":"restore_source_not_own"` (from the master's typed reason, not its text) and a message ending in `snapshot names another volume's chunks: "<snapshot>"`. The refused restore changes nothing: the target name stays free, and a restore from the source's own snapshot may use it.
- **v2's own writes stay in v2:** the source's snapshot never changes.
+1 -1
View File
@@ -59,7 +59,7 @@ For a workspace volume that can change host, this page adds three things.
| Answer | Setup | What this page offers |
|---|---|---|
| exit 0, `volume: v1 (query snapshot, ...)` | cluster spec with a lifecycle store and workspace RPCs | everything below |
| exit 1, ends with `workspace RPC disabled` or `lifecycle store unavailable` | `--topology` only | **nothing on this page.** With `--workspace-lease` the volume never gets a lease and never serves; without it, it serves on its host but cannot be moved: neither the planned hand-over nor the forced move works |
| exit 1, ends with `workspace RPC disabled` or `lifecycle store unavailable` | `--topology` only | **nothing on this page.** The volume never gets a lease and never serves. Starting walstore-chunk without `--workspace-lease` is refused; it is not an alternative deployment mode. |
| exit 1, ends with `workspace move requires an existing RF1 volume` | lifecycle store without a volume record | fix the cluster spec below |
**2. The volume record comes from the cluster spec.** There is no command that